@storvia/sdk 0.5.1 → 0.5.2

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 B=Object.defineProperty;var ne=Object.getOwnPropertyDescriptor;var ie=Object.getOwnPropertyNames;var se=Object.prototype.hasOwnProperty;var re=(o,e)=>{for(var t in e)B(o,t,{get:e[t],enumerable:!0})},oe=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ie(e))!se.call(o,i)&&i!==t&&B(o,i,{get:()=>e[i],enumerable:!(n=ne(e,i))||n.enumerable});return o};var ae=o=>oe(B({},"__esModule",{value:!0}),o);var Ee={};re(Ee,{StorviaError:()=>g,StorviaSDK:()=>D,createStorviaSDK:()=>ee,extractFieldValue:()=>te,isRichFieldValue:()=>z,setToastEnabled:()=>W,showToast:()=>U});module.exports=ae(Ee);var g=class extends Error{constructor(e,t){super(t),this.name="StorviaError",this.code=e}};var j="storvia-sdk-toast-style",_="storvia-sdk-toast-stack",de=`
2
- #${_} {
1
+ "use strict";var B=Object.defineProperty;var ne=Object.getOwnPropertyDescriptor;var ie=Object.getOwnPropertyNames;var se=Object.prototype.hasOwnProperty;var re=(o,e)=>{for(var t in e)B(o,t,{get:e[t],enumerable:!0})},oe=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ie(e))!se.call(o,i)&&i!==t&&B(o,i,{get:()=>e[i],enumerable:!(n=ne(e,i))||n.enumerable});return o};var ae=o=>oe(B({},"__esModule",{value:!0}),o);var Ee={};re(Ee,{StorviaError:()=>g,StorviaSDK:()=>_,createStorviaSDK:()=>ee,extractFieldValue:()=>te,isRichFieldValue:()=>z,setToastEnabled:()=>W,showToast:()=>U});module.exports=ae(Ee);var g=class extends Error{constructor(e,t){super(t),this.name="StorviaError",this.code=e}};var j="storvia-sdk-toast-style",D="storvia-sdk-toast-stack",de=`
2
+ #${D} {
3
3
  position: fixed;
4
4
  top: max(20px, env(safe-area-inset-top, 0px) + 20px);
5
5
  right: max(20px, env(safe-area-inset-right, 0px) + 20px);
@@ -12,7 +12,7 @@
12
12
  }
13
13
 
14
14
  @media (max-width: 768px) {
15
- #${_} {
15
+ #${D} {
16
16
  top: max(10px, env(safe-area-inset-top, 0px) + 10px);
17
17
  left: 10px;
18
18
  right: 10px;
@@ -76,11 +76,11 @@
76
76
  @media (max-width: 768px) {
77
77
  .storvia-toast { max-width: none; }
78
78
  }
79
- `,le={success:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',error:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" 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>',warning:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',info:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>'},ce={UNAUTHORIZED:"\u767B\u5F55\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55",INSUFFICIENT_CREDITS:"\u82B1\u56ED\u5E01\u4E0D\u8DB3\uFF0C\u8BF7\u5145\u503C\u540E\u518D\u7EE7\u7EED\u6E38\u620F",VIOLATION_WORD_DETECTED:"\u5185\u5BB9\u542B\u6709\u8FDD\u7981\u8BCD\uFF0C\u8BF7\u4FEE\u6539\u540E\u91CD\u8BD5",MESSAGE_TOO_LONG:"\u6D88\u606F\u8FC7\u957F\uFF0C\u8BF7\u7CBE\u7B80\u540E\u518D\u53D1\u9001",CONTENT_FILTERED:"\u5185\u5BB9\u88AB\u5B89\u5168\u7B56\u7565\u62E6\u622A\uFF0C\u8BF7\u8C03\u6574\u540E\u91CD\u8BD5",MODEL_REFUSAL:"\u6A21\u578B\u62D2\u7EDD\u54CD\u5E94\uFF0C\u6362\u4E2A\u8BF4\u6CD5\u8BD5\u8BD5",STREAM_INTERRUPTED:"\u56DE\u590D\u5DF2\u4E2D\u65AD\uFF0C\u8BF7\u91CD\u8BD5",RATE_LIMITED:"\u64CD\u4F5C\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5",MODEL_NOT_FOUND:"\u6240\u9009\u6A21\u578B\u4E0D\u53EF\u7528\uFF0C\u8BF7\u5207\u6362\u5176\u4ED6\u6A21\u578B",GAME_NOT_FOUND:"\u672A\u627E\u5230\u5BF9\u5E94\u6E38\u620F",INVALID_REQUEST:"\u8BF7\u6C42\u65E0\u6548\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",INTERNAL_ERROR:"\u670D\u52A1\u51FA\u4E86\u70B9\u5C0F\u95EE\u9898\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",NOT_INITIALIZED:"SDK \u5C1A\u672A\u521D\u59CB\u5316",NETWORK_ERROR:"\u7F51\u7EDC\u5F02\u5E38\uFF0C\u8BF7\u68C0\u67E5\u8FDE\u63A5"},V=!0;function W(o){V=o}function pe(){if(typeof document>"u")return null;let o=document.getElementById(_);if(!o){if(!document.getElementById(j)){let e=document.createElement("style");e.id=j,e.textContent=de,document.head.appendChild(e)}o=document.createElement("div"),o.id=_,document.body.appendChild(o)}return o}function U(o,e="info",t=3500){if(!V)return;let n=pe();if(!n)return;let i=document.createElement("div");i.className=`storvia-toast ${e}`,i.innerHTML=`
79
+ `,le={success:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',error:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" 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>',warning:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',info:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>'},ce={UNAUTHORIZED:"\u767B\u5F55\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55",INSUFFICIENT_CREDITS:"\u82B1\u56ED\u5E01\u4E0D\u8DB3\uFF0C\u8BF7\u5145\u503C\u540E\u518D\u7EE7\u7EED\u6E38\u620F",VIOLATION_WORD_DETECTED:"\u5185\u5BB9\u542B\u6709\u8FDD\u7981\u8BCD\uFF0C\u8BF7\u4FEE\u6539\u540E\u91CD\u8BD5",MESSAGE_TOO_LONG:"\u6D88\u606F\u8FC7\u957F\uFF0C\u8BF7\u7CBE\u7B80\u540E\u518D\u53D1\u9001",CONTENT_FILTERED:"\u5185\u5BB9\u88AB\u5B89\u5168\u7B56\u7565\u62E6\u622A\uFF0C\u8BF7\u8C03\u6574\u540E\u91CD\u8BD5",MODEL_REFUSAL:"\u6A21\u578B\u62D2\u7EDD\u54CD\u5E94\uFF0C\u6362\u4E2A\u8BF4\u6CD5\u8BD5\u8BD5",STREAM_INTERRUPTED:"\u56DE\u590D\u5DF2\u4E2D\u65AD\uFF0C\u8BF7\u91CD\u8BD5",RATE_LIMITED:"\u64CD\u4F5C\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5",MODEL_NOT_FOUND:"\u6240\u9009\u6A21\u578B\u4E0D\u53EF\u7528\uFF0C\u8BF7\u5207\u6362\u5176\u4ED6\u6A21\u578B",GAME_NOT_FOUND:"\u672A\u627E\u5230\u5BF9\u5E94\u6E38\u620F",INVALID_REQUEST:"\u8BF7\u6C42\u65E0\u6548\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",INTERNAL_ERROR:"\u670D\u52A1\u51FA\u4E86\u70B9\u5C0F\u95EE\u9898\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",NOT_INITIALIZED:"SDK \u5C1A\u672A\u521D\u59CB\u5316",NETWORK_ERROR:"\u7F51\u7EDC\u5F02\u5E38\uFF0C\u8BF7\u68C0\u67E5\u8FDE\u63A5"},V=!0;function W(o){V=o}function pe(){if(typeof document>"u")return null;let o=document.getElementById(D);if(!o){if(!document.getElementById(j)){let e=document.createElement("style");e.id=j,e.textContent=de,document.head.appendChild(e)}o=document.createElement("div"),o.id=D,document.body.appendChild(o)}return o}function U(o,e="info",t=3500){if(!V)return;let n=pe();if(!n)return;let i=document.createElement("div");i.className=`storvia-toast ${e}`,i.innerHTML=`
80
80
  <span class="storvia-toast-icon">${le[e]}</span>
81
81
  <span class="storvia-toast-msg"></span>
82
- `;let r=i.querySelector(".storvia-toast-msg");r&&(r.textContent=o),n.appendChild(i),requestAnimationFrame(()=>i.classList.add("show")),setTimeout(()=>{i.isConnected&&(i.classList.add("leaving"),i.classList.remove("show"),setTimeout(()=>i.remove(),320))},t)}function $(o,e){let t=ce[o]||e||"\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5";U(t,o==="INSUFFICIENT_CREDITS"||o==="RATE_LIMITED"?"warning":"error")}var N=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}maybeShowNetworkToast(e){e instanceof g||$("NETWORK_ERROR")}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){if(!this.debug)return;let{method:t,path:n,body:i,status:r,rawResponse:s,parsedData:a,error:d,durationMs:l,modelName:h}=e,m="%c[Storvia SDK]",c="color: #6366f1; font-weight: bold",p=l!==void 0?` (${l}ms)`:"",u=r!==void 0?` [${r}]`:"",f=h?` [model: ${h}]`:"";d?(console.groupCollapsed(`${m} %c${t} ${n}${u}${f}${p} %c\u2717`,c,"color: #e0e0e0","color: #ef4444"),i!==void 0&&console.log("Request:",i),s!==void 0&&console.log("Response (raw):",s),console.error("Error:",d),console.groupEnd()):(console.groupCollapsed(`${m} %c${t} ${n}${u}${f}${p} %c\u2713`,c,"color: #e0e0e0","color: #22c55e"),i!==void 0&&console.log("Request:",i),s!==void 0&&console.log("Response (raw):",s),a!==void 0&&a!==s&&console.log("Response (data):",a),console.groupEnd())}async get(e,t){let n=new URL(`${this.baseUrl}${e}`);t&&Object.entries(t).forEach(([a,d])=>n.searchParams.set(a,d));let i=Date.now(),r,s;try{let a=await fetch(n.toString(),{method:"GET",headers:this.buildHeaders()});r=a.status;let{raw:d,data:l}=await this.handleResponseWithRaw(a);return s=d,this.log({method:"GET",path:e,body:t,status:r,rawResponse:s,parsedData:l,durationMs:Date.now()-i}),l}catch(a){throw this.log({method:"GET",path:e,body:t,status:r,rawResponse:s,error:a,durationMs:Date.now()-i}),this.maybeShowNetworkToast(a),a}}async post(e,t,n){let i=Date.now(),r,s;try{let a=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0});r=a.status;let{raw:d,data:l}=await this.handleResponseWithRaw(a);return s=d,this.log({method:"POST",path:e,body:t,status:r,rawResponse:s,parsedData:l,durationMs:Date.now()-i,modelName:n?.modelName}),l}catch(a){throw this.log({method:"POST",path:e,body:t,status:r,rawResponse:s,error:a,durationMs:Date.now()-i,modelName:n?.modelName}),this.maybeShowNetworkToast(a),a}}async patch(e,t){let n=Date.now(),i,r;try{let s=await fetch(`${this.baseUrl}${e}`,{method:"PATCH",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0});i=s.status;let{raw:a,data:d}=await this.handleResponseWithRaw(s);return r=a,this.log({method:"PATCH",path:e,body:t,status:i,rawResponse:r,parsedData:d,durationMs:Date.now()-n}),d}catch(s){throw this.log({method:"PATCH",path:e,body:t,status:i,rawResponse:r,error:s,durationMs:Date.now()-n}),this.maybeShowNetworkToast(s),s}}async delete(e){let t=Date.now(),n,i;try{let r=await fetch(`${this.baseUrl}${e}`,{method:"DELETE",headers:this.buildHeaders()});n=r.status;let{raw:s,data:a}=await this.handleResponseWithRaw(r);return i=s,this.log({method:"DELETE",path:e,status:n,rawResponse:i,parsedData:a,durationMs:Date.now()-t}),a}catch(r){throw this.log({method:"DELETE",path:e,status:n,rawResponse:i,error:r,durationMs:Date.now()-t}),this.maybeShowNetworkToast(r),r}}async stream(e,t,n,i,r){let s=Date.now(),a=r?.modelName?` [model: ${r.modelName}]`:"",d=[],l=f=>{this.debug&&d.push({t:Date.now()-s,event:f})},h=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify(t)});if(!h.ok){let f=await h.text().catch(()=>""),v={};try{v=JSON.parse(f)}catch{}let L=v.code||"INTERNAL_ERROR",C=new g(L,v.message||`HTTP ${h.status}`);throw $(L,v.message),this.log({method:"STREAM",path:e,body:t,status:h.status,rawResponse:f,error:C,durationMs:Date.now()-s,modelName:r?.modelName}),C}let m=h.body?.getReader();if(!m)throw new g("INTERNAL_ERROR","No response body for stream");let c=new TextDecoder,p="",u="";try{for(;;){let{done:f,value:v}=await m.read();if(f)break;let C=c.decode(v,{stream:!0}).split(`
83
- `);for(let w of C){if(!w.startsWith("data: "))continue;let A=w.slice(6);if(A==="[DONE]"){l("[DONE]"),this.debug&&(console.groupCollapsed(`%c[Storvia SDK] %cSTREAM ${e} [${h.status}]${a} (${Date.now()-s}ms) %c\u2713`,"color: #6366f1; font-weight: bold","color: #e0e0e0","color: #22c55e"),console.log("Request:",t),console.log(`Accumulated content (${u.length} chars):`,u),console.log("Message ID:",p),console.log(`SSE events (${d.length}):`,d),console.groupEnd()),i(p);return}try{let x=JSON.parse(A);l(x),x.type==="done"&&x.id?p=x.id:x.content&&(u+=x.content,n(x.content))}catch{l({raw:A})}}}}catch(f){throw this.debug&&(console.groupCollapsed(`%c[Storvia SDK] %cSTREAM ${e} [${h.status}]${a} (${Date.now()-s}ms) %c\u2717`,"color: #6366f1; font-weight: bold","color: #e0e0e0","color: #ef4444"),console.log("Request:",t),console.log(`Accumulated content (${u.length} chars):`,u),console.log(`SSE events (${d.length}):`,d),console.error("Stream error:",f),console.groupEnd()),f}p&&i(p)}async handleResponseWithRaw(e){let t=await e.text(),n;try{n=t?JSON.parse(t):null}catch{n=t}if(!e.ok){let i=n&&typeof n=="object"?n:{},r={401:"UNAUTHORIZED",402:"INSUFFICIENT_CREDITS",404:"GAME_NOT_FOUND",429:"RATE_LIMITED"},s=i.code||r[e.status]||"INTERNAL_ERROR",a=new g(s,i.message||`HTTP ${e.status}`);throw $(s,i.message),a}return n&&typeof n=="object"&&"data"in n?{raw:n,data:n.data}:{raw:n,data:n}}};var O=[{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"}],K=[{value:"low",label:"\u7B80\u77ED"},{value:"medium",label:"\u9002\u4E2D"},{value:"high",label:"\u8BE6\u7EC6"}],he="https://cdn.storvia.ai/default/logo.png",ge="https://api.storvia.ai/storage/v1/object/public/storvia/default/credits.png",me=`
82
+ `;let r=i.querySelector(".storvia-toast-msg");r&&(r.textContent=o),n.appendChild(i),requestAnimationFrame(()=>i.classList.add("show")),setTimeout(()=>{i.isConnected&&(i.classList.add("leaving"),i.classList.remove("show"),setTimeout(()=>i.remove(),320))},t)}function $(o,e){let t=ce[o]||e||"\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5";U(t,o==="INSUFFICIENT_CREDITS"||o==="RATE_LIMITED"?"warning":"error")}var L=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}maybeShowNetworkToast(e){e instanceof g||$("NETWORK_ERROR")}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){if(!this.debug)return;let{method:t,path:n,body:i,status:r,rawResponse:s,parsedData:a,error:d,durationMs:l,modelName:h}=e,m="%c[Storvia SDK]",c="color: #6366f1; font-weight: bold",p=l!==void 0?` (${l}ms)`:"",u=r!==void 0?` [${r}]`:"",f=h?` [model: ${h}]`:"";d?(console.groupCollapsed(`${m} %c${t} ${n}${u}${f}${p} %c\u2717`,c,"color: #e0e0e0","color: #ef4444"),i!==void 0&&console.log("Request:",i),s!==void 0&&console.log("Response (raw):",s),console.error("Error:",d),console.groupEnd()):(console.groupCollapsed(`${m} %c${t} ${n}${u}${f}${p} %c\u2713`,c,"color: #e0e0e0","color: #22c55e"),i!==void 0&&console.log("Request:",i),s!==void 0&&console.log("Response (raw):",s),a!==void 0&&a!==s&&console.log("Response (data):",a),console.groupEnd())}async get(e,t){let n=new URL(`${this.baseUrl}${e}`);t&&Object.entries(t).forEach(([a,d])=>n.searchParams.set(a,d));let i=Date.now(),r,s;try{let a=await fetch(n.toString(),{method:"GET",headers:this.buildHeaders()});r=a.status;let{raw:d,data:l}=await this.handleResponseWithRaw(a);return s=d,this.log({method:"GET",path:e,body:t,status:r,rawResponse:s,parsedData:l,durationMs:Date.now()-i}),l}catch(a){throw this.log({method:"GET",path:e,body:t,status:r,rawResponse:s,error:a,durationMs:Date.now()-i}),this.maybeShowNetworkToast(a),a}}async post(e,t,n){let i=Date.now(),r,s;try{let a=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0});r=a.status;let{raw:d,data:l}=await this.handleResponseWithRaw(a);return s=d,this.log({method:"POST",path:e,body:t,status:r,rawResponse:s,parsedData:l,durationMs:Date.now()-i,modelName:n?.modelName}),l}catch(a){throw this.log({method:"POST",path:e,body:t,status:r,rawResponse:s,error:a,durationMs:Date.now()-i,modelName:n?.modelName}),this.maybeShowNetworkToast(a),a}}async patch(e,t){let n=Date.now(),i,r;try{let s=await fetch(`${this.baseUrl}${e}`,{method:"PATCH",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0});i=s.status;let{raw:a,data:d}=await this.handleResponseWithRaw(s);return r=a,this.log({method:"PATCH",path:e,body:t,status:i,rawResponse:r,parsedData:d,durationMs:Date.now()-n}),d}catch(s){throw this.log({method:"PATCH",path:e,body:t,status:i,rawResponse:r,error:s,durationMs:Date.now()-n}),this.maybeShowNetworkToast(s),s}}async delete(e){let t=Date.now(),n,i;try{let r=await fetch(`${this.baseUrl}${e}`,{method:"DELETE",headers:this.buildHeaders()});n=r.status;let{raw:s,data:a}=await this.handleResponseWithRaw(r);return i=s,this.log({method:"DELETE",path:e,status:n,rawResponse:i,parsedData:a,durationMs:Date.now()-t}),a}catch(r){throw this.log({method:"DELETE",path:e,status:n,rawResponse:i,error:r,durationMs:Date.now()-t}),this.maybeShowNetworkToast(r),r}}async stream(e,t,n,i,r){let s=Date.now(),a=r?.modelName?` [model: ${r.modelName}]`:"",d=[],l=f=>{this.debug&&d.push({t:Date.now()-s,event:f})},h=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify(t)});if(!h.ok){let f=await h.text().catch(()=>""),v={};try{v=JSON.parse(f)}catch{}let O=v.code||"INTERNAL_ERROR",C=new g(O,v.message||`HTTP ${h.status}`);throw $(O,v.message),this.log({method:"STREAM",path:e,body:t,status:h.status,rawResponse:f,error:C,durationMs:Date.now()-s,modelName:r?.modelName}),C}let m=h.body?.getReader();if(!m)throw new g("INTERNAL_ERROR","No response body for stream");let c=new TextDecoder,p="",u="";try{for(;;){let{done:f,value:v}=await m.read();if(f)break;let C=c.decode(v,{stream:!0}).split(`
83
+ `);for(let w of C){if(!w.startsWith("data: "))continue;let A=w.slice(6);if(A==="[DONE]"){l("[DONE]"),this.debug&&(console.groupCollapsed(`%c[Storvia SDK] %cSTREAM ${e} [${h.status}]${a} (${Date.now()-s}ms) %c\u2713`,"color: #6366f1; font-weight: bold","color: #e0e0e0","color: #22c55e"),console.log("Request:",t),console.log(`Accumulated content (${u.length} chars):`,u),console.log("Message ID:",p),console.log(`SSE events (${d.length}):`,d),console.groupEnd()),i(p);return}try{let x=JSON.parse(A);l(x),x.type==="done"&&x.id?p=x.id:x.content&&(u+=x.content,n(x.content))}catch{l({raw:A})}}}}catch(f){throw this.debug&&(console.groupCollapsed(`%c[Storvia SDK] %cSTREAM ${e} [${h.status}]${a} (${Date.now()-s}ms) %c\u2717`,"color: #6366f1; font-weight: bold","color: #e0e0e0","color: #ef4444"),console.log("Request:",t),console.log(`Accumulated content (${u.length} chars):`,u),console.log(`SSE events (${d.length}):`,d),console.error("Stream error:",f),console.groupEnd()),f}p&&i(p)}async handleResponseWithRaw(e){let t=await e.text(),n;try{n=t?JSON.parse(t):null}catch{n=t}if(!e.ok){let i=n&&typeof n=="object"?n:{},r={401:"UNAUTHORIZED",402:"INSUFFICIENT_CREDITS",404:"GAME_NOT_FOUND",429:"RATE_LIMITED"},s=i.code||r[e.status]||"INTERNAL_ERROR",a=new g(s,i.message||`HTTP ${e.status}`);throw $(s,i.message),a}return n&&typeof n=="object"&&"data"in n?{raw:n,data:n.data}:{raw:n,data:n}}};var N=[{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"}],K=[{value:"low",label:"\u7B80\u77ED"},{value:"medium",label:"\u9002\u4E2D"},{value:"high",label:"\u8BE6\u7EC6"}],he="https://cdn.storvia.ai/default/logo.png",ge="https://api.storvia.ai/storage/v1/object/public/storvia/default/credits.png",me=`
84
84
  :host {
85
85
  position: fixed;
86
86
  z-index: 2147483647;
@@ -766,4 +766,4 @@
766
766
  <span class="credits-unit">/\u6B21</span>
767
767
  </div>`:""}
768
768
  ${r?`<div class="detail-description">${this.escapeHtml(r)}</div>`:""}
769
- `}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 r=document.createElement("p");r.className="form-hint",r.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(r);let s=document.createElement("input");s.type="range",s.className="slider",s.min="0",s.max="1",s.step="0.1",s.value=String(this.settings.temperature),s.addEventListener("input",()=>{let d=parseFloat(s.value);this.settings.temperature=d,this.tempValueEl&&(this.tempValueEl.textContent=d.toFixed(1))}),e.appendChild(s);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=[],K.forEach(i=>{let r=document.createElement("button");r.className=`segment-button${i.value===this.settings.replyLength?" active":""}`,r.textContent=i.label,r.addEventListener("click",()=>{this.settings.replyLength=i.value,this.segmentBtns.forEach((s,a)=>{s.classList.toggle("active",K[a].value===i.value)})}),this.segmentBtns.push(r),n.appendChild(r)}),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 r=document.createElement("span");r.textContent=O.find(d=>d.value===this.settings.replyLanguage)?.label||"";let s=document.createElement("span");s.className="select-arrow",s.textContent="\u25BE",this.langArrow=s,i.appendChild(r),i.appendChild(s),i.addEventListener("click",d=>{d.stopPropagation(),this.toggleLangDropdown()}),n.appendChild(i);let a=document.createElement("div");return a.className="select-dropdown",this.langDropdown=a,this.langOptions=[],O.forEach(d=>{let l=document.createElement("button");l.className=`select-option${d.value===this.settings.replyLanguage?" active":""}`,l.innerHTML=`<span>${d.label}</span>${d.value===this.settings.replyLanguage?Y:""}`,l.addEventListener("click",()=>{this.settings.replyLanguage=d.value,r.textContent=d.label,this.langOptions.forEach((h,m)=>{h.classList.toggle("active",O[m].value===d.value),h.innerHTML=`<span>${O[m].label}</span>${O[m].value===d.value?Y:""}`}),this.closeLangDropdown()}),this.langOptions.push(l),a.appendChild(l)}),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.playerNote.length}/50`,this.noteCounter=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let r=document.createElement("p");r.className="form-hint",r.textContent="\u5199\u4E0B\u4F60\u5BF9\u8FD9\u4E2A\u6E38\u620F\u7684\u5907\u6CE8\uFF0C\u4F1A\u663E\u793A\u5728\u5B58\u6863\u5217\u8868",e.appendChild(r);let s=document.createElement("textarea");return s.className="player-note-input",s.placeholder="\u5907\u6CE8",s.maxLength=50,s.rows=2,s.value=this.settings.playerNote,s.addEventListener("input",()=>{this.settings.playerNote=s.value,this.noteCounter&&(this.noteCounter.textContent=`${s.value.length}/50`)}),e.appendChild(s),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 r=document.createElement("button");return r.className="btn btn-sync",this.syncBtn=r,this.renderSyncBtn(),r.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(r),e}setSyncState(e){this.syncState=e,this.renderSyncBtn()}renderSyncBtn(){if(!this.syncBtn)return;let e=this.syncState,t={idle:fe,loading:ve,success:be,error:ye},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{if(this.pendingModelId&&this.pendingModelId!==this.selectedModelId){let e=this.models.find(t=>t.id===this.pendingModelId);if(e&&e.is_active!==!1){this.selectedModelId=this.pendingModelId,this.callbacks.onModelChange(this.pendingModelId);try{localStorage.setItem("storvia_model_id",this.pendingModelId)}catch{}}else this.pendingModelId=this.selectedModelId}await this.callbacks.onSettingsChange({temperature:this.settings.temperature,replyLength:this.settings.replyLength,replyLanguage:this.settings.replyLanguage,playerNote:this.settings.playerNote}),this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1),this.closePanel()}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+b/2<window.innerWidth/2,t=380;e?(this.panel.style.left="0",this.panel.style.right="auto"):(this.panel.style.left=`${b-t}px`,this.panel.style.right="auto"),this.fabY>500?(this.panel.style.bottom=`${b+8}px`,this.panel.style.top="auto"):(this.panel.style.top=`${b+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.fabWrap&&(this.fabWrap.style.pointerEvents="none"))}),this.isMobile()&&this.lockBodyScroll()))}closePanel(){if(this.panel&&this.panel.classList.remove("open"),this.fab&&(this.fab.style.visibility="visible"),this.fabDot&&(this.fabDot.style.visibility="visible"),this.fabWrap&&(this.fabWrap.style.pointerEvents=""),this.unlockBodyScroll(),this.pendingModelId!==this.selectedModelId){if(this.pendingModelId=this.selectedModelId,this.modelGrid){let e=this.getFilteredModels();this.modelGrid.querySelectorAll(".model-card").forEach((t,n)=>{t.classList.toggle("selected",e[n].id===this.pendingModelId)})}this.renderModelDetail()}}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 S=class{constructor(e,t,n,i,r=!1,s,a,d){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=i;this.isPreview=r;this.previewConfig=s,this.getSettings=a,this.getModelName=d}reqMeta(){let e=this.getModelName?.();return e?{modelName:e}:void 0}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.sceneKey,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta());return}return this.http.post("/chat",t,this.reqMeta())}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,sceneKey:e.sceneKey,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.sceneKey,stream:e.stream??!1};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta());return}return this.http.post("/generate",t,this.reqMeta())}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.sceneKey,stream:e.stream??!1};if(e.stream){await this.http.stream("/retry",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta());return}return this.http.post("/retry",t,this.reqMeta())}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,scene_key:e.sceneKey,history_messages:[]};this.previewConfig?t.prompt_config=this.previewConfig:t.game_id=this.getGameId();let n=this.getSettings?.();if(n&&(typeof n.temperature=="number"&&(t.temperature=n.temperature),n.replyLength&&(t.reply_length=n.replyLength),n.replyLanguage&&(t.reply_language=n.replyLanguage)),e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta());return}let i="";return await this.http.stream("/preview",t,r=>{i+=r},()=>{},this.reqMeta()),{id:"",content:i}}};var H=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,t){if(this.isPreview){let i=this.mem[e]||{};return t?{...i[t]||{}}:{...i}}let n=t?{group:t}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,n)}async update(e,t,n){if(this.isPreview){let i=this.mem[e]||(this.mem[e]={});i[t]={...i[t]||{},...n};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,{group:t,values:n})}},E=class{constructor(e,t,n=!1,i,r){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];i&&(this.mem=i.map(X)),this.state=new H(e,t,n,r)}setInitial(e,t){this.mem=e?e.map(X):[],this.state.setInitial(t)}async list(){return this.isPreview?this.mem.map(q):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return t?q(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 X(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 q(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 R=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];i&&(this.mem=i.map(r=>({...r})))}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(r=>r.from===e&&r.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)}`)}};function Z(o){let e={count:o.count};return o.desc!==void 0&&(e.desc=o.desc),o.icon_url!==void 0&&(e.iconUrl=o.icon_url),e}function F(o){let e={};if(!o)return e;for(let[t,n]of Object.entries(o)){let i={};for(let[r,s]of Object.entries(n))i[r]=Z(s);e[t]=i}return e}function xe(o){let e={};if(!o)return e;for(let[t,n]of Object.entries(o))e[t]=Z(n);return e}var T=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem=F(i))}setInitial(e){this.mem=e?F(e):{}}async list(e){if(this.isPreview){if(e!==void 0)return{...this.mem[e]||{}};let n={};for(let[i,r]of Object.entries(this.mem))n[i]={...r};return n}if(e!==void 0){let n=await this.http.get(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`);return xe(n)}let t=await this.http.get(`/conversations/${this.getConversationId()}/inventory`);return F(t)}async add(e){let{group:t,name:n,count:i=1,desc:r,iconUrl:s}=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 d={count:i};r!==void 0&&(d.desc=r),s!==void 0&&(d.iconUrl=s),this.mem[t][n]=d;return}let a={group:t,name:n,count:i};r!==void 0&&(a.desc=r),s!==void 0&&(a.icon_url=s),await this.http.post(`/conversations/${this.getConversationId()}/inventory`,a)}async update(e){let{group:t,name:n,count:i,desc:r,iconUrl:s}=e;if(this.isPreview){let d=this.mem[t];if(!d||!(n in d))throw new Error(`Item "${t}/${n}" not found`);let l=d[n];i!==void 0&&(l.count=i),r!==void 0&&(l.desc=r),s!==void 0&&(l.iconUrl=s);return}let a={};i!==void 0&&(a.count=i),r!==void 0&&(a.desc=r),s!==void 0&&(a.icon_url=s),await this.http.patch(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,a)}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:r}=e;if(this.isPreview){let s=this.mem[t];if(!s||!(i in s))throw new Error(`Source item "${t}/${i}" not found`);if(!this.mem[n])throw new Error(`Target group "${n}" does not exist`);let a=r||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]=s[i],delete s[i];return}await this.http.post(`/conversations/${this.getConversationId()}/inventory/move`,{fromGroup:t,toGroup:n,name:i,newName:r})}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 r=this.mem[e];if(r&&Object.keys(r).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 k=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 G=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})}},P=class{constructor(e,t,n=!1,i,r){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};i&&(this.memPersona={...i}),this.state=new G(e,t,n,r)}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 M=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem=J(i))}setInitial(e){this.mem=e?J(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 J(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 Q="/functions/v1/world-engine/v1",Ce="https://api.storvia.ai";function Ie(){return window.__STORVIA__||{}}function Se(o=5e3){let e=Ie();return e.apiBase?Promise.resolve(e):new Promise((t,n)=>{let i=setTimeout(()=>{window.removeEventListener("message",r),n(new g("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},o);function r(s){let a=null;if(s.data?.type==="storvia-init"&&s.data.apiBase?a={apiBase:s.data.apiBase,gameId:s.data.gameId,accessToken:s.data.accessToken}:s.data?.type==="storvia-preview-init"&&s.data.config&&(a=s.data.config),a&&a.apiBase){clearTimeout(i),window.removeEventListener("message",r);let d=window;d.__STORVIA__=a,t(a)}}window.addEventListener("message",r)})}var D=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.models=[];this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){if(this.initialized)return;let e=await Se(),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}${Q}`,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 N(this.baseUrl,this.accessToken,!!e.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let[c,p]=await Promise.all([this.fetchModels(),this.fetchPreviewSnapshot()]);this.models=c;let u=this.getSavedModelId();this.modelId=e.selectedModelId||(u&&c.some(w=>w.id===u)?u:"")||c[0]?.id||"",this.settingsSheet=new I({onModelChange:w=>{this.modelId=w},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),c.length>0&&this.settingsSheet.mount(c,this.modelId,{temperature:1,replyLength:"medium",replyLanguage:"zh-CN",playerNote:""},!1);let f=()=>this.gameId,v=()=>this.conversationId,L=()=>this.modelId,C=()=>this.models.find(w=>w.id===this.modelId)?.name;this.chat=new S(this.http,f,v,L,!0,this.previewConfig,()=>this.settingsSheet?.getSettings()??null,C),this.characters=new E(this.http,v,!0,p?.characters,p?.characterStates),this.relationships=new R(this.http,v,!0,p?.relationships),this.inventory=new T(this.http,v,!0,p?.inventory),this.world=new k(this.http,v,!0,p?.world),this.player=new P(this.http,v,!0,p?.player,p?.playerState),this.custom=new M(this.http,v,!0,p?.custom),this.initialized=!0,this.listenForPreviewMessages();return}let[n,i]=await Promise.all([this.authenticate(),this.fetchModels()]);this.conversationId=n.conversationId,this.models=i;let r=this.getSavedModelId();this.modelId=r&&i.some(c=>c.id===r)?r:i[0]?.id||"";let s=n.settings,a=s?{temperature:s.temperature??1,replyLength:s.reply_length??"medium",replyLanguage:s.reply_language??"zh-CN",playerNote:s.player_note??""}:{temperature:1,replyLength:"medium",replyLanguage:"zh-CN",playerNote:""};this.settingsSheet=new I({onModelChange:c=>{this.modelId=c},onSettingsChange:c=>this.saveSettings(c),onSync:()=>this.syncSettings()}),this.settingsSheet.mount(i,this.modelId,a,n.hasWorldUpdate??!1);let d=()=>this.gameId,l=()=>this.conversationId,h=()=>this.modelId,m=()=>this.models.find(c=>c.id===this.modelId)?.name;this.chat=new S(this.http,d,l,h,!1,void 0,void 0,m),this.characters=new E(this.http,l),this.relationships=new R(this.http,l),this.inventory=new T(this.http,l),this.world=new k(this.http,l),this.player=new P(this.http,l),this.custom=new M(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){let t={conversation_id:this.conversationId};e.temperature!==void 0&&(t.temperature=e.temperature),e.replyLength!==void 0&&(t.reply_length=e.replyLength),e.replyLanguage!==void 0&&(t.reply_language=e.replyLanguage),e.playerNote!==void 0&&(t.player_note=e.playerNote),await this.http.patch("/settings",t)}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=`${Ce}${Q}`,this.gameId=e.gameId,this.isPreview=!0,this.http=new N(this.baseUrl,"",!1,e.apiKey);let[t,n]=await Promise.all([this.fetchModels(),this.fetchPreviewSnapshot()]);this.models=t;let i=this.getSavedModelId();this.modelId=(i&&t.some(l=>l.id===i)?i:"")||t[0]?.id||"",this.conversationId="00000000-0000-0000-0000-000000000000",this.settingsSheet=new I({onModelChange:l=>{this.modelId=l},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),t.length>0&&this.settingsSheet.mount(t,this.modelId,{temperature:1,replyLength:"medium",replyLanguage:"zh-CN",playerNote:""},!1);let r=()=>this.gameId,s=()=>this.conversationId,a=()=>this.modelId,d=()=>this.models.find(l=>l.id===this.modelId)?.name;this.chat=new S(this.http,r,s,a,!0,void 0,()=>this.settingsSheet?.getSettings()??null,d),this.characters=new E(this.http,s,!0,n?.characters,n?.characterStates),this.relationships=new R(this.http,s,!0,n?.relationships),this.inventory=new T(this.http,s,!0,n?.inventory),this.world=new k(this.http,s,!0,n?.world),this.player=new P(this.http,s,!0,n?.player,n?.playerState),this.custom=new M(this.http,s,!0,n?.custom),this.initialized=!0}};async function ee(o){let e=new D;return o?.dev?await e.initDev(o.dev):await e.init(),e}function z(o){return typeof o=="object"&&o!==null&&"value"in o&&"type"in o&&(o.type==="number"||o.type==="text")}function te(o){return z(o)?o.value:o}0&&(module.exports={StorviaError,StorviaSDK,createStorviaSDK,extractFieldValue,isRichFieldValue,setToastEnabled,showToast});
769
+ `}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 r=document.createElement("p");r.className="form-hint",r.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(r);let s=document.createElement("input");s.type="range",s.className="slider",s.min="0",s.max="1",s.step="0.1",s.value=String(this.settings.temperature),s.addEventListener("input",()=>{let d=parseFloat(s.value);this.settings.temperature=d,this.tempValueEl&&(this.tempValueEl.textContent=d.toFixed(1))}),e.appendChild(s);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=[],K.forEach(i=>{let r=document.createElement("button");r.className=`segment-button${i.value===this.settings.replyLength?" active":""}`,r.textContent=i.label,r.addEventListener("click",()=>{this.settings.replyLength=i.value,this.segmentBtns.forEach((s,a)=>{s.classList.toggle("active",K[a].value===i.value)})}),this.segmentBtns.push(r),n.appendChild(r)}),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 r=document.createElement("span");r.textContent=N.find(d=>d.value===this.settings.replyLanguage)?.label||"";let s=document.createElement("span");s.className="select-arrow",s.textContent="\u25BE",this.langArrow=s,i.appendChild(r),i.appendChild(s),i.addEventListener("click",d=>{d.stopPropagation(),this.toggleLangDropdown()}),n.appendChild(i);let a=document.createElement("div");return a.className="select-dropdown",this.langDropdown=a,this.langOptions=[],N.forEach(d=>{let l=document.createElement("button");l.className=`select-option${d.value===this.settings.replyLanguage?" active":""}`,l.innerHTML=`<span>${d.label}</span>${d.value===this.settings.replyLanguage?Y:""}`,l.addEventListener("click",()=>{this.settings.replyLanguage=d.value,r.textContent=d.label,this.langOptions.forEach((h,m)=>{h.classList.toggle("active",N[m].value===d.value),h.innerHTML=`<span>${N[m].label}</span>${N[m].value===d.value?Y:""}`}),this.closeLangDropdown()}),this.langOptions.push(l),a.appendChild(l)}),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.playerNote.length}/50`,this.noteCounter=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let r=document.createElement("p");r.className="form-hint",r.textContent="\u5199\u4E0B\u4F60\u5BF9\u8FD9\u4E2A\u6E38\u620F\u7684\u5907\u6CE8\uFF0C\u4F1A\u663E\u793A\u5728\u5B58\u6863\u5217\u8868",e.appendChild(r);let s=document.createElement("textarea");return s.className="player-note-input",s.placeholder="\u5907\u6CE8",s.maxLength=50,s.rows=2,s.value=this.settings.playerNote,s.addEventListener("input",()=>{this.settings.playerNote=s.value,this.noteCounter&&(this.noteCounter.textContent=`${s.value.length}/50`)}),e.appendChild(s),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 r=document.createElement("button");return r.className="btn btn-sync",this.syncBtn=r,this.renderSyncBtn(),r.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(r),e}setSyncState(e){this.syncState=e,this.renderSyncBtn()}renderSyncBtn(){if(!this.syncBtn)return;let e=this.syncState,t={idle:fe,loading:ve,success:be,error:ye},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{if(this.pendingModelId&&this.pendingModelId!==this.selectedModelId){let e=this.models.find(t=>t.id===this.pendingModelId);if(e&&e.is_active!==!1){this.selectedModelId=this.pendingModelId,this.callbacks.onModelChange(this.pendingModelId);try{localStorage.setItem("storvia_model_id",this.pendingModelId)}catch{}}else this.pendingModelId=this.selectedModelId}await this.callbacks.onSettingsChange({temperature:this.settings.temperature,replyLength:this.settings.replyLength,replyLanguage:this.settings.replyLanguage,playerNote:this.settings.playerNote}),this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1),this.closePanel()}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+b/2<window.innerWidth/2,t=380;e?(this.panel.style.left="0",this.panel.style.right="auto"):(this.panel.style.left=`${b-t}px`,this.panel.style.right="auto"),this.fabY>500?(this.panel.style.bottom=`${b+8}px`,this.panel.style.top="auto"):(this.panel.style.top=`${b+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.fabWrap&&(this.fabWrap.style.pointerEvents="none"))}),this.isMobile()&&this.lockBodyScroll()))}closePanel(){if(this.panel&&this.panel.classList.remove("open"),this.fab&&(this.fab.style.visibility="visible"),this.fabDot&&(this.fabDot.style.visibility="visible"),this.fabWrap&&(this.fabWrap.style.pointerEvents=""),this.unlockBodyScroll(),this.pendingModelId!==this.selectedModelId){if(this.pendingModelId=this.selectedModelId,this.modelGrid){let e=this.getFilteredModels();this.modelGrid.querySelectorAll(".model-card").forEach((t,n)=>{t.classList.toggle("selected",e[n].id===this.pendingModelId)})}this.renderModelDetail()}}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 S=class{constructor(e,t,n,i,r=!1,s,a,d){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=i;this.isPreview=r;this.previewConfig=s,this.getSettings=a,this.getModelName=d}reqMeta(){let e=this.getModelName?.();return e?{modelName:e}:void 0}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.sceneKey,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta());return}return this.http.post("/chat",t,this.reqMeta())}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,sceneKey:e.sceneKey,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.sceneKey,stream:e.stream??!1};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta());return}return this.http.post("/generate",t,this.reqMeta())}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.sceneKey,stream:e.stream??!1};if(e.stream){await this.http.stream("/retry",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta());return}return this.http.post("/retry",t,this.reqMeta())}async messages(e){if(this.isPreview)return{data:[],hasMore:!1,nextCursor:null};let t={conversation_id:this.getConversationId(),order:e.order,limit:String(e.limit??20)};e.topic&&(t.topic=e.topic),e.cursor&&(t.cursor_uuid=e.cursor.uuid,t.cursor_created_at=e.cursor.createdAt);let n=await this.http.get("/messages",t);return{data:n.messages.map(i=>({uuid:i.uuid,role:i.role,content:i.content,topic:i.topic,status:i.status,model:i.model,createdAt:i.created_at})),hasMore:n.has_more,nextCursor:n.next_cursor?{uuid:n.next_cursor.cursor_uuid,createdAt:n.next_cursor.cursor_created_at}:null}}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,scene_key:e.sceneKey,history_messages:[]};this.previewConfig?t.prompt_config=this.previewConfig:t.game_id=this.getGameId();let n=this.getSettings?.();if(n&&(typeof n.temperature=="number"&&(t.temperature=n.temperature),n.replyLength&&(t.reply_length=n.replyLength),n.replyLanguage&&(t.reply_language=n.replyLanguage)),e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta());return}let i="";return await this.http.stream("/preview",t,r=>{i+=r},()=>{},this.reqMeta()),{id:"",content:i}}};var H=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,t){if(this.isPreview){let i=this.mem[e]||{};return t?{...i[t]||{}}:{...i}}let n=t?{group:t}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,n)}async update(e,t,n){if(this.isPreview){let i=this.mem[e]||(this.mem[e]={});i[t]={...i[t]||{},...n};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,{group:t,values:n})}},E=class{constructor(e,t,n=!1,i,r){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];i&&(this.mem=i.map(X)),this.state=new H(e,t,n,r)}setInitial(e,t){this.mem=e?e.map(X):[],this.state.setInitial(t)}async list(){return this.isPreview?this.mem.map(q):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return t?q(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 X(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 q(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 R=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];i&&(this.mem=i.map(r=>({...r})))}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(r=>r.from===e&&r.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)}`)}};function Z(o){let e={count:o.count};return o.desc!==void 0&&(e.desc=o.desc),o.icon_url!==void 0&&(e.iconUrl=o.icon_url),e}function F(o){let e={};if(!o)return e;for(let[t,n]of Object.entries(o)){let i={};for(let[r,s]of Object.entries(n))i[r]=Z(s);e[t]=i}return e}function xe(o){let e={};if(!o)return e;for(let[t,n]of Object.entries(o))e[t]=Z(n);return e}var T=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem=F(i))}setInitial(e){this.mem=e?F(e):{}}async list(e){if(this.isPreview){if(e!==void 0)return{...this.mem[e]||{}};let n={};for(let[i,r]of Object.entries(this.mem))n[i]={...r};return n}if(e!==void 0){let n=await this.http.get(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`);return xe(n)}let t=await this.http.get(`/conversations/${this.getConversationId()}/inventory`);return F(t)}async add(e){let{group:t,name:n,count:i=1,desc:r,iconUrl:s}=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 d={count:i};r!==void 0&&(d.desc=r),s!==void 0&&(d.iconUrl=s),this.mem[t][n]=d;return}let a={group:t,name:n,count:i};r!==void 0&&(a.desc=r),s!==void 0&&(a.icon_url=s),await this.http.post(`/conversations/${this.getConversationId()}/inventory`,a)}async update(e){let{group:t,name:n,count:i,desc:r,iconUrl:s}=e;if(this.isPreview){let d=this.mem[t];if(!d||!(n in d))throw new Error(`Item "${t}/${n}" not found`);let l=d[n];i!==void 0&&(l.count=i),r!==void 0&&(l.desc=r),s!==void 0&&(l.iconUrl=s);return}let a={};i!==void 0&&(a.count=i),r!==void 0&&(a.desc=r),s!==void 0&&(a.icon_url=s),await this.http.patch(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,a)}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:r}=e;if(this.isPreview){let s=this.mem[t];if(!s||!(i in s))throw new Error(`Source item "${t}/${i}" not found`);if(!this.mem[n])throw new Error(`Target group "${n}" does not exist`);let a=r||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]=s[i],delete s[i];return}await this.http.post(`/conversations/${this.getConversationId()}/inventory/move`,{fromGroup:t,toGroup:n,name:i,newName:r})}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 r=this.mem[e];if(r&&Object.keys(r).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 k=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 G=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})}},P=class{constructor(e,t,n=!1,i,r){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};i&&(this.memPersona={...i}),this.state=new G(e,t,n,r)}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 M=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem=J(i))}setInitial(e){this.mem=e?J(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 J(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 Q="/functions/v1/world-engine/v1",Ce="https://api.storvia.ai";function Ie(){return window.__STORVIA__||{}}function Se(o=5e3){let e=Ie();return e.apiBase?Promise.resolve(e):new Promise((t,n)=>{let i=setTimeout(()=>{window.removeEventListener("message",r),n(new g("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},o);function r(s){let a=null;if(s.data?.type==="storvia-init"&&s.data.apiBase?a={apiBase:s.data.apiBase,gameId:s.data.gameId,accessToken:s.data.accessToken}:s.data?.type==="storvia-preview-init"&&s.data.config&&(a=s.data.config),a&&a.apiBase){clearTimeout(i),window.removeEventListener("message",r);let d=window;d.__STORVIA__=a,t(a)}}window.addEventListener("message",r)})}var _=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.models=[];this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){if(this.initialized)return;let e=await Se(),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}${Q}`,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 L(this.baseUrl,this.accessToken,!!e.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let[c,p]=await Promise.all([this.fetchModels(),this.fetchPreviewSnapshot()]);this.models=c;let u=this.getSavedModelId();this.modelId=e.selectedModelId||(u&&c.some(w=>w.id===u)?u:"")||c[0]?.id||"",this.settingsSheet=new I({onModelChange:w=>{this.modelId=w},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),c.length>0&&this.settingsSheet.mount(c,this.modelId,{temperature:1,replyLength:"medium",replyLanguage:"zh-CN",playerNote:""},!1);let f=()=>this.gameId,v=()=>this.conversationId,O=()=>this.modelId,C=()=>this.models.find(w=>w.id===this.modelId)?.name;this.chat=new S(this.http,f,v,O,!0,this.previewConfig,()=>this.settingsSheet?.getSettings()??null,C),this.characters=new E(this.http,v,!0,p?.characters,p?.characterStates),this.relationships=new R(this.http,v,!0,p?.relationships),this.inventory=new T(this.http,v,!0,p?.inventory),this.world=new k(this.http,v,!0,p?.world),this.player=new P(this.http,v,!0,p?.player,p?.playerState),this.custom=new M(this.http,v,!0,p?.custom),this.initialized=!0,this.listenForPreviewMessages();return}let[n,i]=await Promise.all([this.authenticate(),this.fetchModels()]);this.conversationId=n.conversationId,this.models=i;let r=this.getSavedModelId();this.modelId=r&&i.some(c=>c.id===r)?r:i[0]?.id||"";let s=n.settings,a=s?{temperature:s.temperature??1,replyLength:s.reply_length??"medium",replyLanguage:s.reply_language??"zh-CN",playerNote:s.player_note??""}:{temperature:1,replyLength:"medium",replyLanguage:"zh-CN",playerNote:""};this.settingsSheet=new I({onModelChange:c=>{this.modelId=c},onSettingsChange:c=>this.saveSettings(c),onSync:()=>this.syncSettings()}),this.settingsSheet.mount(i,this.modelId,a,n.hasWorldUpdate??!1);let d=()=>this.gameId,l=()=>this.conversationId,h=()=>this.modelId,m=()=>this.models.find(c=>c.id===this.modelId)?.name;this.chat=new S(this.http,d,l,h,!1,void 0,void 0,m),this.characters=new E(this.http,l),this.relationships=new R(this.http,l),this.inventory=new T(this.http,l),this.world=new k(this.http,l),this.player=new P(this.http,l),this.custom=new M(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){let t={conversation_id:this.conversationId};e.temperature!==void 0&&(t.temperature=e.temperature),e.replyLength!==void 0&&(t.reply_length=e.replyLength),e.replyLanguage!==void 0&&(t.reply_language=e.replyLanguage),e.playerNote!==void 0&&(t.player_note=e.playerNote),await this.http.patch("/settings",t)}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=`${Ce}${Q}`,this.gameId=e.gameId,this.isPreview=!0,this.http=new L(this.baseUrl,"",!1,e.apiKey);let[t,n]=await Promise.all([this.fetchModels(),this.fetchPreviewSnapshot()]);this.models=t;let i=this.getSavedModelId();this.modelId=(i&&t.some(l=>l.id===i)?i:"")||t[0]?.id||"",this.conversationId="00000000-0000-0000-0000-000000000000",this.settingsSheet=new I({onModelChange:l=>{this.modelId=l},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),t.length>0&&this.settingsSheet.mount(t,this.modelId,{temperature:1,replyLength:"medium",replyLanguage:"zh-CN",playerNote:""},!1);let r=()=>this.gameId,s=()=>this.conversationId,a=()=>this.modelId,d=()=>this.models.find(l=>l.id===this.modelId)?.name;this.chat=new S(this.http,r,s,a,!0,void 0,()=>this.settingsSheet?.getSettings()??null,d),this.characters=new E(this.http,s,!0,n?.characters,n?.characterStates),this.relationships=new R(this.http,s,!0,n?.relationships),this.inventory=new T(this.http,s,!0,n?.inventory),this.world=new k(this.http,s,!0,n?.world),this.player=new P(this.http,s,!0,n?.player,n?.playerState),this.custom=new M(this.http,s,!0,n?.custom),this.initialized=!0}};async function ee(o){let e=new _;return o?.dev?await e.initDev(o.dev):await e.init(),e}function z(o){return typeof o=="object"&&o!==null&&"value"in o&&"type"in o&&(o.type==="number"||o.type==="text")}function te(o){return z(o)?o.value:o}0&&(module.exports={StorviaError,StorviaSDK,createStorviaSDK,extractFieldValue,isRichFieldValue,setToastEnabled,showToast});
package/dist/index.d.mts CHANGED
@@ -64,6 +64,30 @@ interface ChatResponse {
64
64
  id: string;
65
65
  content: string;
66
66
  }
67
+ interface ChatMessageCursor {
68
+ uuid: string;
69
+ createdAt: string;
70
+ }
71
+ interface ChatMessagesOptions {
72
+ order: 'asc' | 'desc';
73
+ limit?: number;
74
+ topic?: string;
75
+ cursor?: ChatMessageCursor;
76
+ }
77
+ interface ChatMessage {
78
+ uuid: string;
79
+ role: 'user' | 'assistant' | string;
80
+ content: string;
81
+ topic: string | null;
82
+ status: string;
83
+ model: string | null;
84
+ createdAt: string;
85
+ }
86
+ interface ChatMessagesResponse {
87
+ data: ChatMessage[];
88
+ hasMore: boolean;
89
+ nextCursor: ChatMessageCursor | null;
90
+ }
67
91
  /** 富字段值:携带类型和范围元数据 */
68
92
  interface RichFieldValue {
69
93
  value: string | number | boolean;
@@ -210,6 +234,11 @@ declare class ChatModule {
210
234
  * 适用于 AI 回复出错或不满意时重新生成
211
235
  */
212
236
  retry(options?: ChatRetryOptions): Promise<ChatResponse | void>;
237
+ /**
238
+ * 获取当前会话的消息列表(支持 topic 过滤 + 游标分页)
239
+ * order: 'asc' = 从旧到新(历史展示),'desc' = 从新到旧(游戏内聊天框)
240
+ */
241
+ messages(options: ChatMessagesOptions): Promise<ChatMessagesResponse>;
213
242
  /** 预览模式:发到 /preview 端点
214
243
  * - 创作台预览:父页面已注入 previewConfig,请求体塞 prompt_config,服务端不查库
215
244
  * - 本地预览 / dev:无 previewConfig,请求体塞 game_id,服务端按 hash_id 查 prompts
@@ -429,4 +458,4 @@ type ToastType = 'success' | 'error' | 'warning' | 'info';
429
458
  declare function setToastEnabled(enabled: boolean): void;
430
459
  declare function showToast(message: string, type?: ToastType, duration?: number): void;
431
460
 
432
- export { type CharacterAddOptions, type CharacterDetail, type CharacterPersona, type CharacterUpdateOptions, type ChatGenerateOptions, type ChatResponse, type ChatSaveOptions, type ChatSendOptions, type FieldValue, type Gender, type InventoryAddOptions, type InventoryMoveOptions, type InventoryRemoveGroupOptions, type InventoryRemoveOptions, type InventoryState, type InventoryUpdateOptions, type ItemData, type PlayerPersona, type Relationship, type RichFieldValue, StorviaError, type StorviaErrorCode, StorviaSDK, createStorviaSDK, extractFieldValue, isRichFieldValue, setToastEnabled, showToast };
461
+ export { type CharacterAddOptions, type CharacterDetail, type CharacterPersona, type CharacterUpdateOptions, type ChatGenerateOptions, type ChatMessage, type ChatMessageCursor, type ChatMessagesOptions, type ChatMessagesResponse, type ChatResponse, type ChatRetryOptions, type ChatSaveOptions, type ChatSendOptions, type FieldValue, type Gender, type InventoryAddOptions, type InventoryMoveOptions, type InventoryRemoveGroupOptions, type InventoryRemoveOptions, type InventoryState, type InventoryUpdateOptions, type ItemData, type PlayerPersona, type Relationship, type RichFieldValue, StorviaError, type StorviaErrorCode, StorviaSDK, createStorviaSDK, extractFieldValue, isRichFieldValue, setToastEnabled, showToast };
package/dist/index.esm.js CHANGED
@@ -1,5 +1,5 @@
1
- var u=class extends Error{constructor(e,t){super(t),this.name="StorviaError",this.code=e}};var F="storvia-sdk-toast-style",D="storvia-sdk-toast-stack",J=`
2
- #${D} {
1
+ var u=class extends Error{constructor(e,t){super(t),this.name="StorviaError",this.code=e}};var F="storvia-sdk-toast-style",_="storvia-sdk-toast-stack",J=`
2
+ #${_} {
3
3
  position: fixed;
4
4
  top: max(20px, env(safe-area-inset-top, 0px) + 20px);
5
5
  right: max(20px, env(safe-area-inset-right, 0px) + 20px);
@@ -12,7 +12,7 @@ var u=class extends Error{constructor(e,t){super(t),this.name="StorviaError",thi
12
12
  }
13
13
 
14
14
  @media (max-width: 768px) {
15
- #${D} {
15
+ #${_} {
16
16
  top: max(10px, env(safe-area-inset-top, 0px) + 10px);
17
17
  left: 10px;
18
18
  right: 10px;
@@ -76,11 +76,11 @@ var u=class extends Error{constructor(e,t){super(t),this.name="StorviaError",thi
76
76
  @media (max-width: 768px) {
77
77
  .storvia-toast { max-width: none; }
78
78
  }
79
- `,Q={success:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',error:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" 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>',warning:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',info:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>'},ee={UNAUTHORIZED:"\u767B\u5F55\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55",INSUFFICIENT_CREDITS:"\u82B1\u56ED\u5E01\u4E0D\u8DB3\uFF0C\u8BF7\u5145\u503C\u540E\u518D\u7EE7\u7EED\u6E38\u620F",VIOLATION_WORD_DETECTED:"\u5185\u5BB9\u542B\u6709\u8FDD\u7981\u8BCD\uFF0C\u8BF7\u4FEE\u6539\u540E\u91CD\u8BD5",MESSAGE_TOO_LONG:"\u6D88\u606F\u8FC7\u957F\uFF0C\u8BF7\u7CBE\u7B80\u540E\u518D\u53D1\u9001",CONTENT_FILTERED:"\u5185\u5BB9\u88AB\u5B89\u5168\u7B56\u7565\u62E6\u622A\uFF0C\u8BF7\u8C03\u6574\u540E\u91CD\u8BD5",MODEL_REFUSAL:"\u6A21\u578B\u62D2\u7EDD\u54CD\u5E94\uFF0C\u6362\u4E2A\u8BF4\u6CD5\u8BD5\u8BD5",STREAM_INTERRUPTED:"\u56DE\u590D\u5DF2\u4E2D\u65AD\uFF0C\u8BF7\u91CD\u8BD5",RATE_LIMITED:"\u64CD\u4F5C\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5",MODEL_NOT_FOUND:"\u6240\u9009\u6A21\u578B\u4E0D\u53EF\u7528\uFF0C\u8BF7\u5207\u6362\u5176\u4ED6\u6A21\u578B",GAME_NOT_FOUND:"\u672A\u627E\u5230\u5BF9\u5E94\u6E38\u620F",INVALID_REQUEST:"\u8BF7\u6C42\u65E0\u6548\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",INTERNAL_ERROR:"\u670D\u52A1\u51FA\u4E86\u70B9\u5C0F\u95EE\u9898\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",NOT_INITIALIZED:"SDK \u5C1A\u672A\u521D\u59CB\u5316",NETWORK_ERROR:"\u7F51\u7EDC\u5F02\u5E38\uFF0C\u8BF7\u68C0\u67E5\u8FDE\u63A5"},G=!0;function te(a){G=a}function ne(){if(typeof document>"u")return null;let a=document.getElementById(D);if(!a){if(!document.getElementById(F)){let e=document.createElement("style");e.id=F,e.textContent=J,document.head.appendChild(e)}a=document.createElement("div"),a.id=D,document.body.appendChild(a)}return a}function z(a,e="info",t=3500){if(!G)return;let n=ne();if(!n)return;let i=document.createElement("div");i.className=`storvia-toast ${e}`,i.innerHTML=`
79
+ `,Q={success:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',error:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" 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>',warning:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',info:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>'},ee={UNAUTHORIZED:"\u767B\u5F55\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55",INSUFFICIENT_CREDITS:"\u82B1\u56ED\u5E01\u4E0D\u8DB3\uFF0C\u8BF7\u5145\u503C\u540E\u518D\u7EE7\u7EED\u6E38\u620F",VIOLATION_WORD_DETECTED:"\u5185\u5BB9\u542B\u6709\u8FDD\u7981\u8BCD\uFF0C\u8BF7\u4FEE\u6539\u540E\u91CD\u8BD5",MESSAGE_TOO_LONG:"\u6D88\u606F\u8FC7\u957F\uFF0C\u8BF7\u7CBE\u7B80\u540E\u518D\u53D1\u9001",CONTENT_FILTERED:"\u5185\u5BB9\u88AB\u5B89\u5168\u7B56\u7565\u62E6\u622A\uFF0C\u8BF7\u8C03\u6574\u540E\u91CD\u8BD5",MODEL_REFUSAL:"\u6A21\u578B\u62D2\u7EDD\u54CD\u5E94\uFF0C\u6362\u4E2A\u8BF4\u6CD5\u8BD5\u8BD5",STREAM_INTERRUPTED:"\u56DE\u590D\u5DF2\u4E2D\u65AD\uFF0C\u8BF7\u91CD\u8BD5",RATE_LIMITED:"\u64CD\u4F5C\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5",MODEL_NOT_FOUND:"\u6240\u9009\u6A21\u578B\u4E0D\u53EF\u7528\uFF0C\u8BF7\u5207\u6362\u5176\u4ED6\u6A21\u578B",GAME_NOT_FOUND:"\u672A\u627E\u5230\u5BF9\u5E94\u6E38\u620F",INVALID_REQUEST:"\u8BF7\u6C42\u65E0\u6548\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",INTERNAL_ERROR:"\u670D\u52A1\u51FA\u4E86\u70B9\u5C0F\u95EE\u9898\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",NOT_INITIALIZED:"SDK \u5C1A\u672A\u521D\u59CB\u5316",NETWORK_ERROR:"\u7F51\u7EDC\u5F02\u5E38\uFF0C\u8BF7\u68C0\u67E5\u8FDE\u63A5"},G=!0;function te(a){G=a}function ne(){if(typeof document>"u")return null;let a=document.getElementById(_);if(!a){if(!document.getElementById(F)){let e=document.createElement("style");e.id=F,e.textContent=J,document.head.appendChild(e)}a=document.createElement("div"),a.id=_,document.body.appendChild(a)}return a}function z(a,e="info",t=3500){if(!G)return;let n=ne();if(!n)return;let i=document.createElement("div");i.className=`storvia-toast ${e}`,i.innerHTML=`
80
80
  <span class="storvia-toast-icon">${Q[e]}</span>
81
81
  <span class="storvia-toast-msg"></span>
82
- `;let r=i.querySelector(".storvia-toast-msg");r&&(r.textContent=a),n.appendChild(i),requestAnimationFrame(()=>i.classList.add("show")),setTimeout(()=>{i.isConnected&&(i.classList.add("leaving"),i.classList.remove("show"),setTimeout(()=>i.remove(),320))},t)}function _(a,e){let t=ee[a]||e||"\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5";z(t,a==="INSUFFICIENT_CREDITS"||a==="RATE_LIMITED"?"warning":"error")}var N=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}maybeShowNetworkToast(e){e instanceof u||_("NETWORK_ERROR")}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){if(!this.debug)return;let{method:t,path:n,body:i,status:r,rawResponse:s,parsedData:o,error:d,durationMs:l,modelName:h}=e,g="%c[Storvia SDK]",c="color: #6366f1; font-weight: bold",p=l!==void 0?` (${l}ms)`:"",m=r!==void 0?` [${r}]`:"",f=h?` [model: ${h}]`:"";d?(console.groupCollapsed(`${g} %c${t} ${n}${m}${f}${p} %c\u2717`,c,"color: #e0e0e0","color: #ef4444"),i!==void 0&&console.log("Request:",i),s!==void 0&&console.log("Response (raw):",s),console.error("Error:",d),console.groupEnd()):(console.groupCollapsed(`${g} %c${t} ${n}${m}${f}${p} %c\u2713`,c,"color: #e0e0e0","color: #22c55e"),i!==void 0&&console.log("Request:",i),s!==void 0&&console.log("Response (raw):",s),o!==void 0&&o!==s&&console.log("Response (data):",o),console.groupEnd())}async get(e,t){let n=new URL(`${this.baseUrl}${e}`);t&&Object.entries(t).forEach(([o,d])=>n.searchParams.set(o,d));let i=Date.now(),r,s;try{let o=await fetch(n.toString(),{method:"GET",headers:this.buildHeaders()});r=o.status;let{raw:d,data:l}=await this.handleResponseWithRaw(o);return s=d,this.log({method:"GET",path:e,body:t,status:r,rawResponse:s,parsedData:l,durationMs:Date.now()-i}),l}catch(o){throw this.log({method:"GET",path:e,body:t,status:r,rawResponse:s,error:o,durationMs:Date.now()-i}),this.maybeShowNetworkToast(o),o}}async post(e,t,n){let i=Date.now(),r,s;try{let o=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0});r=o.status;let{raw:d,data:l}=await this.handleResponseWithRaw(o);return s=d,this.log({method:"POST",path:e,body:t,status:r,rawResponse:s,parsedData:l,durationMs:Date.now()-i,modelName:n?.modelName}),l}catch(o){throw this.log({method:"POST",path:e,body:t,status:r,rawResponse:s,error:o,durationMs:Date.now()-i,modelName:n?.modelName}),this.maybeShowNetworkToast(o),o}}async patch(e,t){let n=Date.now(),i,r;try{let s=await fetch(`${this.baseUrl}${e}`,{method:"PATCH",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0});i=s.status;let{raw:o,data:d}=await this.handleResponseWithRaw(s);return r=o,this.log({method:"PATCH",path:e,body:t,status:i,rawResponse:r,parsedData:d,durationMs:Date.now()-n}),d}catch(s){throw this.log({method:"PATCH",path:e,body:t,status:i,rawResponse:r,error:s,durationMs:Date.now()-n}),this.maybeShowNetworkToast(s),s}}async delete(e){let t=Date.now(),n,i;try{let r=await fetch(`${this.baseUrl}${e}`,{method:"DELETE",headers:this.buildHeaders()});n=r.status;let{raw:s,data:o}=await this.handleResponseWithRaw(r);return i=s,this.log({method:"DELETE",path:e,status:n,rawResponse:i,parsedData:o,durationMs:Date.now()-t}),o}catch(r){throw this.log({method:"DELETE",path:e,status:n,rawResponse:i,error:r,durationMs:Date.now()-t}),this.maybeShowNetworkToast(r),r}}async stream(e,t,n,i,r){let s=Date.now(),o=r?.modelName?` [model: ${r.modelName}]`:"",d=[],l=f=>{this.debug&&d.push({t:Date.now()-s,event:f})},h=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify(t)});if(!h.ok){let f=await h.text().catch(()=>""),v={};try{v=JSON.parse(f)}catch{}let L=v.code||"INTERNAL_ERROR",C=new u(L,v.message||`HTTP ${h.status}`);throw _(L,v.message),this.log({method:"STREAM",path:e,body:t,status:h.status,rawResponse:f,error:C,durationMs:Date.now()-s,modelName:r?.modelName}),C}let g=h.body?.getReader();if(!g)throw new u("INTERNAL_ERROR","No response body for stream");let c=new TextDecoder,p="",m="";try{for(;;){let{done:f,value:v}=await g.read();if(f)break;let C=c.decode(v,{stream:!0}).split(`
83
- `);for(let w of C){if(!w.startsWith("data: "))continue;let A=w.slice(6);if(A==="[DONE]"){l("[DONE]"),this.debug&&(console.groupCollapsed(`%c[Storvia SDK] %cSTREAM ${e} [${h.status}]${o} (${Date.now()-s}ms) %c\u2713`,"color: #6366f1; font-weight: bold","color: #e0e0e0","color: #22c55e"),console.log("Request:",t),console.log(`Accumulated content (${m.length} chars):`,m),console.log("Message ID:",p),console.log(`SSE events (${d.length}):`,d),console.groupEnd()),i(p);return}try{let x=JSON.parse(A);l(x),x.type==="done"&&x.id?p=x.id:x.content&&(m+=x.content,n(x.content))}catch{l({raw:A})}}}}catch(f){throw this.debug&&(console.groupCollapsed(`%c[Storvia SDK] %cSTREAM ${e} [${h.status}]${o} (${Date.now()-s}ms) %c\u2717`,"color: #6366f1; font-weight: bold","color: #e0e0e0","color: #ef4444"),console.log("Request:",t),console.log(`Accumulated content (${m.length} chars):`,m),console.log(`SSE events (${d.length}):`,d),console.error("Stream error:",f),console.groupEnd()),f}p&&i(p)}async handleResponseWithRaw(e){let t=await e.text(),n;try{n=t?JSON.parse(t):null}catch{n=t}if(!e.ok){let i=n&&typeof n=="object"?n:{},r={401:"UNAUTHORIZED",402:"INSUFFICIENT_CREDITS",404:"GAME_NOT_FOUND",429:"RATE_LIMITED"},s=i.code||r[e.status]||"INTERNAL_ERROR",o=new u(s,i.message||`HTTP ${e.status}`);throw _(s,i.message),o}return n&&typeof n=="object"&&"data"in n?{raw:n,data:n.data}:{raw:n,data:n}}};var O=[{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"}],j=[{value:"low",label:"\u7B80\u77ED"},{value:"medium",label:"\u9002\u4E2D"},{value:"high",label:"\u8BE6\u7EC6"}],ie="https://cdn.storvia.ai/default/logo.png",se="https://api.storvia.ai/storage/v1/object/public/storvia/default/credits.png",re=`
82
+ `;let r=i.querySelector(".storvia-toast-msg");r&&(r.textContent=a),n.appendChild(i),requestAnimationFrame(()=>i.classList.add("show")),setTimeout(()=>{i.isConnected&&(i.classList.add("leaving"),i.classList.remove("show"),setTimeout(()=>i.remove(),320))},t)}function D(a,e){let t=ee[a]||e||"\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5";z(t,a==="INSUFFICIENT_CREDITS"||a==="RATE_LIMITED"?"warning":"error")}var L=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}maybeShowNetworkToast(e){e instanceof u||D("NETWORK_ERROR")}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){if(!this.debug)return;let{method:t,path:n,body:i,status:r,rawResponse:s,parsedData:o,error:d,durationMs:l,modelName:h}=e,g="%c[Storvia SDK]",c="color: #6366f1; font-weight: bold",p=l!==void 0?` (${l}ms)`:"",m=r!==void 0?` [${r}]`:"",f=h?` [model: ${h}]`:"";d?(console.groupCollapsed(`${g} %c${t} ${n}${m}${f}${p} %c\u2717`,c,"color: #e0e0e0","color: #ef4444"),i!==void 0&&console.log("Request:",i),s!==void 0&&console.log("Response (raw):",s),console.error("Error:",d),console.groupEnd()):(console.groupCollapsed(`${g} %c${t} ${n}${m}${f}${p} %c\u2713`,c,"color: #e0e0e0","color: #22c55e"),i!==void 0&&console.log("Request:",i),s!==void 0&&console.log("Response (raw):",s),o!==void 0&&o!==s&&console.log("Response (data):",o),console.groupEnd())}async get(e,t){let n=new URL(`${this.baseUrl}${e}`);t&&Object.entries(t).forEach(([o,d])=>n.searchParams.set(o,d));let i=Date.now(),r,s;try{let o=await fetch(n.toString(),{method:"GET",headers:this.buildHeaders()});r=o.status;let{raw:d,data:l}=await this.handleResponseWithRaw(o);return s=d,this.log({method:"GET",path:e,body:t,status:r,rawResponse:s,parsedData:l,durationMs:Date.now()-i}),l}catch(o){throw this.log({method:"GET",path:e,body:t,status:r,rawResponse:s,error:o,durationMs:Date.now()-i}),this.maybeShowNetworkToast(o),o}}async post(e,t,n){let i=Date.now(),r,s;try{let o=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0});r=o.status;let{raw:d,data:l}=await this.handleResponseWithRaw(o);return s=d,this.log({method:"POST",path:e,body:t,status:r,rawResponse:s,parsedData:l,durationMs:Date.now()-i,modelName:n?.modelName}),l}catch(o){throw this.log({method:"POST",path:e,body:t,status:r,rawResponse:s,error:o,durationMs:Date.now()-i,modelName:n?.modelName}),this.maybeShowNetworkToast(o),o}}async patch(e,t){let n=Date.now(),i,r;try{let s=await fetch(`${this.baseUrl}${e}`,{method:"PATCH",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0});i=s.status;let{raw:o,data:d}=await this.handleResponseWithRaw(s);return r=o,this.log({method:"PATCH",path:e,body:t,status:i,rawResponse:r,parsedData:d,durationMs:Date.now()-n}),d}catch(s){throw this.log({method:"PATCH",path:e,body:t,status:i,rawResponse:r,error:s,durationMs:Date.now()-n}),this.maybeShowNetworkToast(s),s}}async delete(e){let t=Date.now(),n,i;try{let r=await fetch(`${this.baseUrl}${e}`,{method:"DELETE",headers:this.buildHeaders()});n=r.status;let{raw:s,data:o}=await this.handleResponseWithRaw(r);return i=s,this.log({method:"DELETE",path:e,status:n,rawResponse:i,parsedData:o,durationMs:Date.now()-t}),o}catch(r){throw this.log({method:"DELETE",path:e,status:n,rawResponse:i,error:r,durationMs:Date.now()-t}),this.maybeShowNetworkToast(r),r}}async stream(e,t,n,i,r){let s=Date.now(),o=r?.modelName?` [model: ${r.modelName}]`:"",d=[],l=f=>{this.debug&&d.push({t:Date.now()-s,event:f})},h=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify(t)});if(!h.ok){let f=await h.text().catch(()=>""),v={};try{v=JSON.parse(f)}catch{}let O=v.code||"INTERNAL_ERROR",C=new u(O,v.message||`HTTP ${h.status}`);throw D(O,v.message),this.log({method:"STREAM",path:e,body:t,status:h.status,rawResponse:f,error:C,durationMs:Date.now()-s,modelName:r?.modelName}),C}let g=h.body?.getReader();if(!g)throw new u("INTERNAL_ERROR","No response body for stream");let c=new TextDecoder,p="",m="";try{for(;;){let{done:f,value:v}=await g.read();if(f)break;let C=c.decode(v,{stream:!0}).split(`
83
+ `);for(let w of C){if(!w.startsWith("data: "))continue;let A=w.slice(6);if(A==="[DONE]"){l("[DONE]"),this.debug&&(console.groupCollapsed(`%c[Storvia SDK] %cSTREAM ${e} [${h.status}]${o} (${Date.now()-s}ms) %c\u2713`,"color: #6366f1; font-weight: bold","color: #e0e0e0","color: #22c55e"),console.log("Request:",t),console.log(`Accumulated content (${m.length} chars):`,m),console.log("Message ID:",p),console.log(`SSE events (${d.length}):`,d),console.groupEnd()),i(p);return}try{let x=JSON.parse(A);l(x),x.type==="done"&&x.id?p=x.id:x.content&&(m+=x.content,n(x.content))}catch{l({raw:A})}}}}catch(f){throw this.debug&&(console.groupCollapsed(`%c[Storvia SDK] %cSTREAM ${e} [${h.status}]${o} (${Date.now()-s}ms) %c\u2717`,"color: #6366f1; font-weight: bold","color: #e0e0e0","color: #ef4444"),console.log("Request:",t),console.log(`Accumulated content (${m.length} chars):`,m),console.log(`SSE events (${d.length}):`,d),console.error("Stream error:",f),console.groupEnd()),f}p&&i(p)}async handleResponseWithRaw(e){let t=await e.text(),n;try{n=t?JSON.parse(t):null}catch{n=t}if(!e.ok){let i=n&&typeof n=="object"?n:{},r={401:"UNAUTHORIZED",402:"INSUFFICIENT_CREDITS",404:"GAME_NOT_FOUND",429:"RATE_LIMITED"},s=i.code||r[e.status]||"INTERNAL_ERROR",o=new u(s,i.message||`HTTP ${e.status}`);throw D(s,i.message),o}return n&&typeof n=="object"&&"data"in n?{raw:n,data:n.data}:{raw:n,data:n}}};var N=[{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"}],j=[{value:"low",label:"\u7B80\u77ED"},{value:"medium",label:"\u9002\u4E2D"},{value:"high",label:"\u8BE6\u7EC6"}],ie="https://cdn.storvia.ai/default/logo.png",se="https://api.storvia.ai/storage/v1/object/public/storvia/default/credits.png",re=`
84
84
  :host {
85
85
  position: fixed;
86
86
  z-index: 2147483647;
@@ -766,4 +766,4 @@ var u=class extends Error{constructor(e,t){super(t),this.name="StorviaError",thi
766
766
  <span class="credits-unit">/\u6B21</span>
767
767
  </div>`:""}
768
768
  ${r?`<div class="detail-description">${this.escapeHtml(r)}</div>`:""}
769
- `}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 r=document.createElement("p");r.className="form-hint",r.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(r);let s=document.createElement("input");s.type="range",s.className="slider",s.min="0",s.max="1",s.step="0.1",s.value=String(this.settings.temperature),s.addEventListener("input",()=>{let d=parseFloat(s.value);this.settings.temperature=d,this.tempValueEl&&(this.tempValueEl.textContent=d.toFixed(1))}),e.appendChild(s);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=[],j.forEach(i=>{let r=document.createElement("button");r.className=`segment-button${i.value===this.settings.replyLength?" active":""}`,r.textContent=i.label,r.addEventListener("click",()=>{this.settings.replyLength=i.value,this.segmentBtns.forEach((s,o)=>{s.classList.toggle("active",j[o].value===i.value)})}),this.segmentBtns.push(r),n.appendChild(r)}),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 r=document.createElement("span");r.textContent=O.find(d=>d.value===this.settings.replyLanguage)?.label||"";let s=document.createElement("span");s.className="select-arrow",s.textContent="\u25BE",this.langArrow=s,i.appendChild(r),i.appendChild(s),i.addEventListener("click",d=>{d.stopPropagation(),this.toggleLangDropdown()}),n.appendChild(i);let o=document.createElement("div");return o.className="select-dropdown",this.langDropdown=o,this.langOptions=[],O.forEach(d=>{let l=document.createElement("button");l.className=`select-option${d.value===this.settings.replyLanguage?" active":""}`,l.innerHTML=`<span>${d.label}</span>${d.value===this.settings.replyLanguage?V:""}`,l.addEventListener("click",()=>{this.settings.replyLanguage=d.value,r.textContent=d.label,this.langOptions.forEach((h,g)=>{h.classList.toggle("active",O[g].value===d.value),h.innerHTML=`<span>${O[g].label}</span>${O[g].value===d.value?V:""}`}),this.closeLangDropdown()}),this.langOptions.push(l),o.appendChild(l)}),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.playerNote.length}/50`,this.noteCounter=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let r=document.createElement("p");r.className="form-hint",r.textContent="\u5199\u4E0B\u4F60\u5BF9\u8FD9\u4E2A\u6E38\u620F\u7684\u5907\u6CE8\uFF0C\u4F1A\u663E\u793A\u5728\u5B58\u6863\u5217\u8868",e.appendChild(r);let s=document.createElement("textarea");return s.className="player-note-input",s.placeholder="\u5907\u6CE8",s.maxLength=50,s.rows=2,s.value=this.settings.playerNote,s.addEventListener("input",()=>{this.settings.playerNote=s.value,this.noteCounter&&(this.noteCounter.textContent=`${s.value.length}/50`)}),e.appendChild(s),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 r=document.createElement("button");return r.className="btn btn-sync",this.syncBtn=r,this.renderSyncBtn(),r.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(r),e}setSyncState(e){this.syncState=e,this.renderSyncBtn()}renderSyncBtn(){if(!this.syncBtn)return;let e=this.syncState,t={idle:ae,loading:de,success:le,error:ce},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{if(this.pendingModelId&&this.pendingModelId!==this.selectedModelId){let e=this.models.find(t=>t.id===this.pendingModelId);if(e&&e.is_active!==!1){this.selectedModelId=this.pendingModelId,this.callbacks.onModelChange(this.pendingModelId);try{localStorage.setItem("storvia_model_id",this.pendingModelId)}catch{}}else this.pendingModelId=this.selectedModelId}await this.callbacks.onSettingsChange({temperature:this.settings.temperature,replyLength:this.settings.replyLength,replyLanguage:this.settings.replyLanguage,playerNote:this.settings.playerNote}),this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1),this.closePanel()}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+b/2<window.innerWidth/2,t=380;e?(this.panel.style.left="0",this.panel.style.right="auto"):(this.panel.style.left=`${b-t}px`,this.panel.style.right="auto"),this.fabY>500?(this.panel.style.bottom=`${b+8}px`,this.panel.style.top="auto"):(this.panel.style.top=`${b+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.fabWrap&&(this.fabWrap.style.pointerEvents="none"))}),this.isMobile()&&this.lockBodyScroll()))}closePanel(){if(this.panel&&this.panel.classList.remove("open"),this.fab&&(this.fab.style.visibility="visible"),this.fabDot&&(this.fabDot.style.visibility="visible"),this.fabWrap&&(this.fabWrap.style.pointerEvents=""),this.unlockBodyScroll(),this.pendingModelId!==this.selectedModelId){if(this.pendingModelId=this.selectedModelId,this.modelGrid){let e=this.getFilteredModels();this.modelGrid.querySelectorAll(".model-card").forEach((t,n)=>{t.classList.toggle("selected",e[n].id===this.pendingModelId)})}this.renderModelDetail()}}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 S=class{constructor(e,t,n,i,r=!1,s,o,d){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=i;this.isPreview=r;this.previewConfig=s,this.getSettings=o,this.getModelName=d}reqMeta(){let e=this.getModelName?.();return e?{modelName:e}:void 0}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.sceneKey,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta());return}return this.http.post("/chat",t,this.reqMeta())}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,sceneKey:e.sceneKey,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.sceneKey,stream:e.stream??!1};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta());return}return this.http.post("/generate",t,this.reqMeta())}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.sceneKey,stream:e.stream??!1};if(e.stream){await this.http.stream("/retry",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta());return}return this.http.post("/retry",t,this.reqMeta())}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,scene_key:e.sceneKey,history_messages:[]};this.previewConfig?t.prompt_config=this.previewConfig:t.game_id=this.getGameId();let n=this.getSettings?.();if(n&&(typeof n.temperature=="number"&&(t.temperature=n.temperature),n.replyLength&&(t.reply_length=n.replyLength),n.replyLanguage&&(t.reply_language=n.replyLanguage)),e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta());return}let i="";return await this.http.stream("/preview",t,r=>{i+=r},()=>{},this.reqMeta()),{id:"",content:i}}};var B=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,t){if(this.isPreview){let i=this.mem[e]||{};return t?{...i[t]||{}}:{...i}}let n=t?{group:t}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,n)}async update(e,t,n){if(this.isPreview){let i=this.mem[e]||(this.mem[e]={});i[t]={...i[t]||{},...n};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,{group:t,values:n})}},E=class{constructor(e,t,n=!1,i,r){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];i&&(this.mem=i.map(W)),this.state=new B(e,t,n,r)}setInitial(e,t){this.mem=e?e.map(W):[],this.state.setInitial(t)}async list(){return this.isPreview?this.mem.map(K):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return t?K(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 W(a){return{name:a.name,description:a.description,avatar:a.avatar,...a.gender?{gender:a.gender}:{},...a.userDescription!==void 0?{userDescription:a.userDescription}:{},...a.isPreset!==void 0?{isPreset:a.isPreset}:{}}}function K(a){return{name:a.name,avatar:a.avatar,description:a.description,...a.userDescription!==void 0?{userDescription:a.userDescription}:{},...a.gender?{gender:a.gender}:{},...a.isPreset!==void 0?{isPreset:a.isPreset}:{}}}var R=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];i&&(this.mem=i.map(r=>({...r})))}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(r=>r.from===e&&r.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)}`)}};function Y(a){let e={count:a.count};return a.desc!==void 0&&(e.desc=a.desc),a.icon_url!==void 0&&(e.iconUrl=a.icon_url),e}function U(a){let e={};if(!a)return e;for(let[t,n]of Object.entries(a)){let i={};for(let[r,s]of Object.entries(n))i[r]=Y(s);e[t]=i}return e}function he(a){let e={};if(!a)return e;for(let[t,n]of Object.entries(a))e[t]=Y(n);return e}var T=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 n={};for(let[i,r]of Object.entries(this.mem))n[i]={...r};return n}if(e!==void 0){let n=await this.http.get(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`);return he(n)}let t=await this.http.get(`/conversations/${this.getConversationId()}/inventory`);return U(t)}async add(e){let{group:t,name:n,count:i=1,desc:r,iconUrl:s}=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 d={count:i};r!==void 0&&(d.desc=r),s!==void 0&&(d.iconUrl=s),this.mem[t][n]=d;return}let o={group:t,name:n,count:i};r!==void 0&&(o.desc=r),s!==void 0&&(o.icon_url=s),await this.http.post(`/conversations/${this.getConversationId()}/inventory`,o)}async update(e){let{group:t,name:n,count:i,desc:r,iconUrl:s}=e;if(this.isPreview){let d=this.mem[t];if(!d||!(n in d))throw new Error(`Item "${t}/${n}" not found`);let l=d[n];i!==void 0&&(l.count=i),r!==void 0&&(l.desc=r),s!==void 0&&(l.iconUrl=s);return}let o={};i!==void 0&&(o.count=i),r!==void 0&&(o.desc=r),s!==void 0&&(o.icon_url=s),await this.http.patch(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,o)}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:r}=e;if(this.isPreview){let s=this.mem[t];if(!s||!(i in s))throw new Error(`Source item "${t}/${i}" not found`);if(!this.mem[n])throw new Error(`Target group "${n}" does not exist`);let o=r||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]=s[i],delete s[i];return}await this.http.post(`/conversations/${this.getConversationId()}/inventory/move`,{fromGroup:t,toGroup:n,name:i,newName:r})}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 r=this.mem[e];if(r&&Object.keys(r).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 k=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 H=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})}},P=class{constructor(e,t,n=!1,i,r){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};i&&(this.memPersona={...i}),this.state=new H(e,t,n,r)}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 M=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem=X(i))}setInitial(e){this.mem=e?X(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 X(a){let e={};for(let[t,n]of Object.entries(a))typeof n=="object"&&n!==null&&!Array.isArray(n)?e[t]={...n}:e[t]=n;return e}var q="/functions/v1/world-engine/v1",ge="https://api.storvia.ai";function me(){return window.__STORVIA__||{}}function ue(a=5e3){let e=me();return e.apiBase?Promise.resolve(e):new Promise((t,n)=>{let i=setTimeout(()=>{window.removeEventListener("message",r),n(new u("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},a);function r(s){let o=null;if(s.data?.type==="storvia-init"&&s.data.apiBase?o={apiBase:s.data.apiBase,gameId:s.data.gameId,accessToken:s.data.accessToken}:s.data?.type==="storvia-preview-init"&&s.data.config&&(o=s.data.config),o&&o.apiBase){clearTimeout(i),window.removeEventListener("message",r);let d=window;d.__STORVIA__=o,t(o)}}window.addEventListener("message",r)})}var $=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.models=[];this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){if(this.initialized)return;let e=await ue(),t=e.apiBase;if(!t)throw new u("NOT_INITIALIZED","window.__STORVIA__.apiBase is not set. The platform must inject it before SDK init.");if(this.baseUrl=`${t}${q}`,this.isPreview=!!e.preview,this.previewConfig=e.previewConfig,!e.gameId)throw new u("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 u("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 N(this.baseUrl,this.accessToken,!!e.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let[c,p]=await Promise.all([this.fetchModels(),this.fetchPreviewSnapshot()]);this.models=c;let m=this.getSavedModelId();this.modelId=e.selectedModelId||(m&&c.some(w=>w.id===m)?m:"")||c[0]?.id||"",this.settingsSheet=new I({onModelChange:w=>{this.modelId=w},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),c.length>0&&this.settingsSheet.mount(c,this.modelId,{temperature:1,replyLength:"medium",replyLanguage:"zh-CN",playerNote:""},!1);let f=()=>this.gameId,v=()=>this.conversationId,L=()=>this.modelId,C=()=>this.models.find(w=>w.id===this.modelId)?.name;this.chat=new S(this.http,f,v,L,!0,this.previewConfig,()=>this.settingsSheet?.getSettings()??null,C),this.characters=new E(this.http,v,!0,p?.characters,p?.characterStates),this.relationships=new R(this.http,v,!0,p?.relationships),this.inventory=new T(this.http,v,!0,p?.inventory),this.world=new k(this.http,v,!0,p?.world),this.player=new P(this.http,v,!0,p?.player,p?.playerState),this.custom=new M(this.http,v,!0,p?.custom),this.initialized=!0,this.listenForPreviewMessages();return}let[n,i]=await Promise.all([this.authenticate(),this.fetchModels()]);this.conversationId=n.conversationId,this.models=i;let r=this.getSavedModelId();this.modelId=r&&i.some(c=>c.id===r)?r:i[0]?.id||"";let s=n.settings,o=s?{temperature:s.temperature??1,replyLength:s.reply_length??"medium",replyLanguage:s.reply_language??"zh-CN",playerNote:s.player_note??""}:{temperature:1,replyLength:"medium",replyLanguage:"zh-CN",playerNote:""};this.settingsSheet=new I({onModelChange:c=>{this.modelId=c},onSettingsChange:c=>this.saveSettings(c),onSync:()=>this.syncSettings()}),this.settingsSheet.mount(i,this.modelId,o,n.hasWorldUpdate??!1);let d=()=>this.gameId,l=()=>this.conversationId,h=()=>this.modelId,g=()=>this.models.find(c=>c.id===this.modelId)?.name;this.chat=new S(this.http,d,l,h,!1,void 0,void 0,g),this.characters=new E(this.http,l),this.relationships=new R(this.http,l),this.inventory=new T(this.http,l),this.world=new k(this.http,l),this.player=new P(this.http,l),this.custom=new M(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){let t={conversation_id:this.conversationId};e.temperature!==void 0&&(t.temperature=e.temperature),e.replyLength!==void 0&&(t.reply_length=e.replyLength),e.replyLanguage!==void 0&&(t.reply_language=e.replyLanguage),e.playerNote!==void 0&&(t.player_note=e.playerNote),await this.http.patch("/settings",t)}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 u("UNAUTHORIZED","User not authenticated"):e.status===404?new u("GAME_NOT_FOUND","Game not found or not published"):new u("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=`${ge}${q}`,this.gameId=e.gameId,this.isPreview=!0,this.http=new N(this.baseUrl,"",!1,e.apiKey);let[t,n]=await Promise.all([this.fetchModels(),this.fetchPreviewSnapshot()]);this.models=t;let i=this.getSavedModelId();this.modelId=(i&&t.some(l=>l.id===i)?i:"")||t[0]?.id||"",this.conversationId="00000000-0000-0000-0000-000000000000",this.settingsSheet=new I({onModelChange:l=>{this.modelId=l},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),t.length>0&&this.settingsSheet.mount(t,this.modelId,{temperature:1,replyLength:"medium",replyLanguage:"zh-CN",playerNote:""},!1);let r=()=>this.gameId,s=()=>this.conversationId,o=()=>this.modelId,d=()=>this.models.find(l=>l.id===this.modelId)?.name;this.chat=new S(this.http,r,s,o,!0,void 0,()=>this.settingsSheet?.getSettings()??null,d),this.characters=new E(this.http,s,!0,n?.characters,n?.characterStates),this.relationships=new R(this.http,s,!0,n?.relationships),this.inventory=new T(this.http,s,!0,n?.inventory),this.world=new k(this.http,s,!0,n?.world),this.player=new P(this.http,s,!0,n?.player,n?.playerState),this.custom=new M(this.http,s,!0,n?.custom),this.initialized=!0}};async function fe(a){let e=new $;return a?.dev?await e.initDev(a.dev):await e.init(),e}function Z(a){return typeof a=="object"&&a!==null&&"value"in a&&"type"in a&&(a.type==="number"||a.type==="text")}function ve(a){return Z(a)?a.value:a}export{u as StorviaError,$ as StorviaSDK,fe as createStorviaSDK,ve as extractFieldValue,Z as isRichFieldValue,te as setToastEnabled,z as showToast};
769
+ `}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 r=document.createElement("p");r.className="form-hint",r.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(r);let s=document.createElement("input");s.type="range",s.className="slider",s.min="0",s.max="1",s.step="0.1",s.value=String(this.settings.temperature),s.addEventListener("input",()=>{let d=parseFloat(s.value);this.settings.temperature=d,this.tempValueEl&&(this.tempValueEl.textContent=d.toFixed(1))}),e.appendChild(s);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=[],j.forEach(i=>{let r=document.createElement("button");r.className=`segment-button${i.value===this.settings.replyLength?" active":""}`,r.textContent=i.label,r.addEventListener("click",()=>{this.settings.replyLength=i.value,this.segmentBtns.forEach((s,o)=>{s.classList.toggle("active",j[o].value===i.value)})}),this.segmentBtns.push(r),n.appendChild(r)}),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 r=document.createElement("span");r.textContent=N.find(d=>d.value===this.settings.replyLanguage)?.label||"";let s=document.createElement("span");s.className="select-arrow",s.textContent="\u25BE",this.langArrow=s,i.appendChild(r),i.appendChild(s),i.addEventListener("click",d=>{d.stopPropagation(),this.toggleLangDropdown()}),n.appendChild(i);let o=document.createElement("div");return o.className="select-dropdown",this.langDropdown=o,this.langOptions=[],N.forEach(d=>{let l=document.createElement("button");l.className=`select-option${d.value===this.settings.replyLanguage?" active":""}`,l.innerHTML=`<span>${d.label}</span>${d.value===this.settings.replyLanguage?V:""}`,l.addEventListener("click",()=>{this.settings.replyLanguage=d.value,r.textContent=d.label,this.langOptions.forEach((h,g)=>{h.classList.toggle("active",N[g].value===d.value),h.innerHTML=`<span>${N[g].label}</span>${N[g].value===d.value?V:""}`}),this.closeLangDropdown()}),this.langOptions.push(l),o.appendChild(l)}),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.playerNote.length}/50`,this.noteCounter=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let r=document.createElement("p");r.className="form-hint",r.textContent="\u5199\u4E0B\u4F60\u5BF9\u8FD9\u4E2A\u6E38\u620F\u7684\u5907\u6CE8\uFF0C\u4F1A\u663E\u793A\u5728\u5B58\u6863\u5217\u8868",e.appendChild(r);let s=document.createElement("textarea");return s.className="player-note-input",s.placeholder="\u5907\u6CE8",s.maxLength=50,s.rows=2,s.value=this.settings.playerNote,s.addEventListener("input",()=>{this.settings.playerNote=s.value,this.noteCounter&&(this.noteCounter.textContent=`${s.value.length}/50`)}),e.appendChild(s),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 r=document.createElement("button");return r.className="btn btn-sync",this.syncBtn=r,this.renderSyncBtn(),r.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(r),e}setSyncState(e){this.syncState=e,this.renderSyncBtn()}renderSyncBtn(){if(!this.syncBtn)return;let e=this.syncState,t={idle:ae,loading:de,success:le,error:ce},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{if(this.pendingModelId&&this.pendingModelId!==this.selectedModelId){let e=this.models.find(t=>t.id===this.pendingModelId);if(e&&e.is_active!==!1){this.selectedModelId=this.pendingModelId,this.callbacks.onModelChange(this.pendingModelId);try{localStorage.setItem("storvia_model_id",this.pendingModelId)}catch{}}else this.pendingModelId=this.selectedModelId}await this.callbacks.onSettingsChange({temperature:this.settings.temperature,replyLength:this.settings.replyLength,replyLanguage:this.settings.replyLanguage,playerNote:this.settings.playerNote}),this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1),this.closePanel()}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+b/2<window.innerWidth/2,t=380;e?(this.panel.style.left="0",this.panel.style.right="auto"):(this.panel.style.left=`${b-t}px`,this.panel.style.right="auto"),this.fabY>500?(this.panel.style.bottom=`${b+8}px`,this.panel.style.top="auto"):(this.panel.style.top=`${b+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.fabWrap&&(this.fabWrap.style.pointerEvents="none"))}),this.isMobile()&&this.lockBodyScroll()))}closePanel(){if(this.panel&&this.panel.classList.remove("open"),this.fab&&(this.fab.style.visibility="visible"),this.fabDot&&(this.fabDot.style.visibility="visible"),this.fabWrap&&(this.fabWrap.style.pointerEvents=""),this.unlockBodyScroll(),this.pendingModelId!==this.selectedModelId){if(this.pendingModelId=this.selectedModelId,this.modelGrid){let e=this.getFilteredModels();this.modelGrid.querySelectorAll(".model-card").forEach((t,n)=>{t.classList.toggle("selected",e[n].id===this.pendingModelId)})}this.renderModelDetail()}}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 S=class{constructor(e,t,n,i,r=!1,s,o,d){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=i;this.isPreview=r;this.previewConfig=s,this.getSettings=o,this.getModelName=d}reqMeta(){let e=this.getModelName?.();return e?{modelName:e}:void 0}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.sceneKey,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta());return}return this.http.post("/chat",t,this.reqMeta())}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,sceneKey:e.sceneKey,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.sceneKey,stream:e.stream??!1};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta());return}return this.http.post("/generate",t,this.reqMeta())}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.sceneKey,stream:e.stream??!1};if(e.stream){await this.http.stream("/retry",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta());return}return this.http.post("/retry",t,this.reqMeta())}async messages(e){if(this.isPreview)return{data:[],hasMore:!1,nextCursor:null};let t={conversation_id:this.getConversationId(),order:e.order,limit:String(e.limit??20)};e.topic&&(t.topic=e.topic),e.cursor&&(t.cursor_uuid=e.cursor.uuid,t.cursor_created_at=e.cursor.createdAt);let n=await this.http.get("/messages",t);return{data:n.messages.map(i=>({uuid:i.uuid,role:i.role,content:i.content,topic:i.topic,status:i.status,model:i.model,createdAt:i.created_at})),hasMore:n.has_more,nextCursor:n.next_cursor?{uuid:n.next_cursor.cursor_uuid,createdAt:n.next_cursor.cursor_created_at}:null}}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,scene_key:e.sceneKey,history_messages:[]};this.previewConfig?t.prompt_config=this.previewConfig:t.game_id=this.getGameId();let n=this.getSettings?.();if(n&&(typeof n.temperature=="number"&&(t.temperature=n.temperature),n.replyLength&&(t.reply_length=n.replyLength),n.replyLanguage&&(t.reply_language=n.replyLanguage)),e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta());return}let i="";return await this.http.stream("/preview",t,r=>{i+=r},()=>{},this.reqMeta()),{id:"",content:i}}};var B=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,t){if(this.isPreview){let i=this.mem[e]||{};return t?{...i[t]||{}}:{...i}}let n=t?{group:t}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,n)}async update(e,t,n){if(this.isPreview){let i=this.mem[e]||(this.mem[e]={});i[t]={...i[t]||{},...n};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,{group:t,values:n})}},E=class{constructor(e,t,n=!1,i,r){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];i&&(this.mem=i.map(W)),this.state=new B(e,t,n,r)}setInitial(e,t){this.mem=e?e.map(W):[],this.state.setInitial(t)}async list(){return this.isPreview?this.mem.map(K):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return t?K(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 W(a){return{name:a.name,description:a.description,avatar:a.avatar,...a.gender?{gender:a.gender}:{},...a.userDescription!==void 0?{userDescription:a.userDescription}:{},...a.isPreset!==void 0?{isPreset:a.isPreset}:{}}}function K(a){return{name:a.name,avatar:a.avatar,description:a.description,...a.userDescription!==void 0?{userDescription:a.userDescription}:{},...a.gender?{gender:a.gender}:{},...a.isPreset!==void 0?{isPreset:a.isPreset}:{}}}var R=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];i&&(this.mem=i.map(r=>({...r})))}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(r=>r.from===e&&r.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)}`)}};function Y(a){let e={count:a.count};return a.desc!==void 0&&(e.desc=a.desc),a.icon_url!==void 0&&(e.iconUrl=a.icon_url),e}function U(a){let e={};if(!a)return e;for(let[t,n]of Object.entries(a)){let i={};for(let[r,s]of Object.entries(n))i[r]=Y(s);e[t]=i}return e}function he(a){let e={};if(!a)return e;for(let[t,n]of Object.entries(a))e[t]=Y(n);return e}var T=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 n={};for(let[i,r]of Object.entries(this.mem))n[i]={...r};return n}if(e!==void 0){let n=await this.http.get(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`);return he(n)}let t=await this.http.get(`/conversations/${this.getConversationId()}/inventory`);return U(t)}async add(e){let{group:t,name:n,count:i=1,desc:r,iconUrl:s}=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 d={count:i};r!==void 0&&(d.desc=r),s!==void 0&&(d.iconUrl=s),this.mem[t][n]=d;return}let o={group:t,name:n,count:i};r!==void 0&&(o.desc=r),s!==void 0&&(o.icon_url=s),await this.http.post(`/conversations/${this.getConversationId()}/inventory`,o)}async update(e){let{group:t,name:n,count:i,desc:r,iconUrl:s}=e;if(this.isPreview){let d=this.mem[t];if(!d||!(n in d))throw new Error(`Item "${t}/${n}" not found`);let l=d[n];i!==void 0&&(l.count=i),r!==void 0&&(l.desc=r),s!==void 0&&(l.iconUrl=s);return}let o={};i!==void 0&&(o.count=i),r!==void 0&&(o.desc=r),s!==void 0&&(o.icon_url=s),await this.http.patch(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,o)}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:r}=e;if(this.isPreview){let s=this.mem[t];if(!s||!(i in s))throw new Error(`Source item "${t}/${i}" not found`);if(!this.mem[n])throw new Error(`Target group "${n}" does not exist`);let o=r||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]=s[i],delete s[i];return}await this.http.post(`/conversations/${this.getConversationId()}/inventory/move`,{fromGroup:t,toGroup:n,name:i,newName:r})}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 r=this.mem[e];if(r&&Object.keys(r).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 k=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 H=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})}},P=class{constructor(e,t,n=!1,i,r){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};i&&(this.memPersona={...i}),this.state=new H(e,t,n,r)}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 M=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem=X(i))}setInitial(e){this.mem=e?X(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 X(a){let e={};for(let[t,n]of Object.entries(a))typeof n=="object"&&n!==null&&!Array.isArray(n)?e[t]={...n}:e[t]=n;return e}var q="/functions/v1/world-engine/v1",ge="https://api.storvia.ai";function me(){return window.__STORVIA__||{}}function ue(a=5e3){let e=me();return e.apiBase?Promise.resolve(e):new Promise((t,n)=>{let i=setTimeout(()=>{window.removeEventListener("message",r),n(new u("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},a);function r(s){let o=null;if(s.data?.type==="storvia-init"&&s.data.apiBase?o={apiBase:s.data.apiBase,gameId:s.data.gameId,accessToken:s.data.accessToken}:s.data?.type==="storvia-preview-init"&&s.data.config&&(o=s.data.config),o&&o.apiBase){clearTimeout(i),window.removeEventListener("message",r);let d=window;d.__STORVIA__=o,t(o)}}window.addEventListener("message",r)})}var $=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.models=[];this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){if(this.initialized)return;let e=await ue(),t=e.apiBase;if(!t)throw new u("NOT_INITIALIZED","window.__STORVIA__.apiBase is not set. The platform must inject it before SDK init.");if(this.baseUrl=`${t}${q}`,this.isPreview=!!e.preview,this.previewConfig=e.previewConfig,!e.gameId)throw new u("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 u("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 L(this.baseUrl,this.accessToken,!!e.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let[c,p]=await Promise.all([this.fetchModels(),this.fetchPreviewSnapshot()]);this.models=c;let m=this.getSavedModelId();this.modelId=e.selectedModelId||(m&&c.some(w=>w.id===m)?m:"")||c[0]?.id||"",this.settingsSheet=new I({onModelChange:w=>{this.modelId=w},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),c.length>0&&this.settingsSheet.mount(c,this.modelId,{temperature:1,replyLength:"medium",replyLanguage:"zh-CN",playerNote:""},!1);let f=()=>this.gameId,v=()=>this.conversationId,O=()=>this.modelId,C=()=>this.models.find(w=>w.id===this.modelId)?.name;this.chat=new S(this.http,f,v,O,!0,this.previewConfig,()=>this.settingsSheet?.getSettings()??null,C),this.characters=new E(this.http,v,!0,p?.characters,p?.characterStates),this.relationships=new R(this.http,v,!0,p?.relationships),this.inventory=new T(this.http,v,!0,p?.inventory),this.world=new k(this.http,v,!0,p?.world),this.player=new P(this.http,v,!0,p?.player,p?.playerState),this.custom=new M(this.http,v,!0,p?.custom),this.initialized=!0,this.listenForPreviewMessages();return}let[n,i]=await Promise.all([this.authenticate(),this.fetchModels()]);this.conversationId=n.conversationId,this.models=i;let r=this.getSavedModelId();this.modelId=r&&i.some(c=>c.id===r)?r:i[0]?.id||"";let s=n.settings,o=s?{temperature:s.temperature??1,replyLength:s.reply_length??"medium",replyLanguage:s.reply_language??"zh-CN",playerNote:s.player_note??""}:{temperature:1,replyLength:"medium",replyLanguage:"zh-CN",playerNote:""};this.settingsSheet=new I({onModelChange:c=>{this.modelId=c},onSettingsChange:c=>this.saveSettings(c),onSync:()=>this.syncSettings()}),this.settingsSheet.mount(i,this.modelId,o,n.hasWorldUpdate??!1);let d=()=>this.gameId,l=()=>this.conversationId,h=()=>this.modelId,g=()=>this.models.find(c=>c.id===this.modelId)?.name;this.chat=new S(this.http,d,l,h,!1,void 0,void 0,g),this.characters=new E(this.http,l),this.relationships=new R(this.http,l),this.inventory=new T(this.http,l),this.world=new k(this.http,l),this.player=new P(this.http,l),this.custom=new M(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){let t={conversation_id:this.conversationId};e.temperature!==void 0&&(t.temperature=e.temperature),e.replyLength!==void 0&&(t.reply_length=e.replyLength),e.replyLanguage!==void 0&&(t.reply_language=e.replyLanguage),e.playerNote!==void 0&&(t.player_note=e.playerNote),await this.http.patch("/settings",t)}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 u("UNAUTHORIZED","User not authenticated"):e.status===404?new u("GAME_NOT_FOUND","Game not found or not published"):new u("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=`${ge}${q}`,this.gameId=e.gameId,this.isPreview=!0,this.http=new L(this.baseUrl,"",!1,e.apiKey);let[t,n]=await Promise.all([this.fetchModels(),this.fetchPreviewSnapshot()]);this.models=t;let i=this.getSavedModelId();this.modelId=(i&&t.some(l=>l.id===i)?i:"")||t[0]?.id||"",this.conversationId="00000000-0000-0000-0000-000000000000",this.settingsSheet=new I({onModelChange:l=>{this.modelId=l},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),t.length>0&&this.settingsSheet.mount(t,this.modelId,{temperature:1,replyLength:"medium",replyLanguage:"zh-CN",playerNote:""},!1);let r=()=>this.gameId,s=()=>this.conversationId,o=()=>this.modelId,d=()=>this.models.find(l=>l.id===this.modelId)?.name;this.chat=new S(this.http,r,s,o,!0,void 0,()=>this.settingsSheet?.getSettings()??null,d),this.characters=new E(this.http,s,!0,n?.characters,n?.characterStates),this.relationships=new R(this.http,s,!0,n?.relationships),this.inventory=new T(this.http,s,!0,n?.inventory),this.world=new k(this.http,s,!0,n?.world),this.player=new P(this.http,s,!0,n?.player,n?.playerState),this.custom=new M(this.http,s,!0,n?.custom),this.initialized=!0}};async function fe(a){let e=new $;return a?.dev?await e.initDev(a.dev):await e.init(),e}function Z(a){return typeof a=="object"&&a!==null&&"value"in a&&"type"in a&&(a.type==="number"||a.type==="text")}function ve(a){return Z(a)?a.value:a}export{u as StorviaError,$ as StorviaSDK,fe as createStorviaSDK,ve as extractFieldValue,Z as isRichFieldValue,te as setToastEnabled,z as showToast};
package/dist/index.umd.js CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var StorviaSDK=(()=>{var B=Object.defineProperty;var ne=Object.getOwnPropertyDescriptor;var ie=Object.getOwnPropertyNames;var se=Object.prototype.hasOwnProperty;var re=(o,e)=>{for(var t in e)B(o,t,{get:e[t],enumerable:!0})},oe=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ie(e))!se.call(o,i)&&i!==t&&B(o,i,{get:()=>e[i],enumerable:!(n=ne(e,i))||n.enumerable});return o};var ae=o=>oe(B({},"__esModule",{value:!0}),o);var Ee={};re(Ee,{StorviaError:()=>g,StorviaSDK:()=>D,createStorviaSDK:()=>ee,extractFieldValue:()=>te,isRichFieldValue:()=>z,setToastEnabled:()=>W,showToast:()=>U});var g=class extends Error{constructor(e,t){super(t),this.name="StorviaError",this.code=e}};var j="storvia-sdk-toast-style",_="storvia-sdk-toast-stack",de=`
2
- #${_} {
1
+ "use strict";var StorviaSDK=(()=>{var B=Object.defineProperty;var ne=Object.getOwnPropertyDescriptor;var ie=Object.getOwnPropertyNames;var se=Object.prototype.hasOwnProperty;var re=(o,e)=>{for(var t in e)B(o,t,{get:e[t],enumerable:!0})},oe=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ie(e))!se.call(o,i)&&i!==t&&B(o,i,{get:()=>e[i],enumerable:!(n=ne(e,i))||n.enumerable});return o};var ae=o=>oe(B({},"__esModule",{value:!0}),o);var Ee={};re(Ee,{StorviaError:()=>g,StorviaSDK:()=>_,createStorviaSDK:()=>ee,extractFieldValue:()=>te,isRichFieldValue:()=>z,setToastEnabled:()=>W,showToast:()=>U});var g=class extends Error{constructor(e,t){super(t),this.name="StorviaError",this.code=e}};var j="storvia-sdk-toast-style",D="storvia-sdk-toast-stack",de=`
2
+ #${D} {
3
3
  position: fixed;
4
4
  top: max(20px, env(safe-area-inset-top, 0px) + 20px);
5
5
  right: max(20px, env(safe-area-inset-right, 0px) + 20px);
@@ -12,7 +12,7 @@
12
12
  }
13
13
 
14
14
  @media (max-width: 768px) {
15
- #${_} {
15
+ #${D} {
16
16
  top: max(10px, env(safe-area-inset-top, 0px) + 10px);
17
17
  left: 10px;
18
18
  right: 10px;
@@ -76,11 +76,11 @@
76
76
  @media (max-width: 768px) {
77
77
  .storvia-toast { max-width: none; }
78
78
  }
79
- `,le={success:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',error:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" 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>',warning:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',info:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>'},ce={UNAUTHORIZED:"\u767B\u5F55\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55",INSUFFICIENT_CREDITS:"\u82B1\u56ED\u5E01\u4E0D\u8DB3\uFF0C\u8BF7\u5145\u503C\u540E\u518D\u7EE7\u7EED\u6E38\u620F",VIOLATION_WORD_DETECTED:"\u5185\u5BB9\u542B\u6709\u8FDD\u7981\u8BCD\uFF0C\u8BF7\u4FEE\u6539\u540E\u91CD\u8BD5",MESSAGE_TOO_LONG:"\u6D88\u606F\u8FC7\u957F\uFF0C\u8BF7\u7CBE\u7B80\u540E\u518D\u53D1\u9001",CONTENT_FILTERED:"\u5185\u5BB9\u88AB\u5B89\u5168\u7B56\u7565\u62E6\u622A\uFF0C\u8BF7\u8C03\u6574\u540E\u91CD\u8BD5",MODEL_REFUSAL:"\u6A21\u578B\u62D2\u7EDD\u54CD\u5E94\uFF0C\u6362\u4E2A\u8BF4\u6CD5\u8BD5\u8BD5",STREAM_INTERRUPTED:"\u56DE\u590D\u5DF2\u4E2D\u65AD\uFF0C\u8BF7\u91CD\u8BD5",RATE_LIMITED:"\u64CD\u4F5C\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5",MODEL_NOT_FOUND:"\u6240\u9009\u6A21\u578B\u4E0D\u53EF\u7528\uFF0C\u8BF7\u5207\u6362\u5176\u4ED6\u6A21\u578B",GAME_NOT_FOUND:"\u672A\u627E\u5230\u5BF9\u5E94\u6E38\u620F",INVALID_REQUEST:"\u8BF7\u6C42\u65E0\u6548\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",INTERNAL_ERROR:"\u670D\u52A1\u51FA\u4E86\u70B9\u5C0F\u95EE\u9898\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",NOT_INITIALIZED:"SDK \u5C1A\u672A\u521D\u59CB\u5316",NETWORK_ERROR:"\u7F51\u7EDC\u5F02\u5E38\uFF0C\u8BF7\u68C0\u67E5\u8FDE\u63A5"},V=!0;function W(o){V=o}function pe(){if(typeof document>"u")return null;let o=document.getElementById(_);if(!o){if(!document.getElementById(j)){let e=document.createElement("style");e.id=j,e.textContent=de,document.head.appendChild(e)}o=document.createElement("div"),o.id=_,document.body.appendChild(o)}return o}function U(o,e="info",t=3500){if(!V)return;let n=pe();if(!n)return;let i=document.createElement("div");i.className=`storvia-toast ${e}`,i.innerHTML=`
79
+ `,le={success:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',error:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" 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>',warning:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',info:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>'},ce={UNAUTHORIZED:"\u767B\u5F55\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55",INSUFFICIENT_CREDITS:"\u82B1\u56ED\u5E01\u4E0D\u8DB3\uFF0C\u8BF7\u5145\u503C\u540E\u518D\u7EE7\u7EED\u6E38\u620F",VIOLATION_WORD_DETECTED:"\u5185\u5BB9\u542B\u6709\u8FDD\u7981\u8BCD\uFF0C\u8BF7\u4FEE\u6539\u540E\u91CD\u8BD5",MESSAGE_TOO_LONG:"\u6D88\u606F\u8FC7\u957F\uFF0C\u8BF7\u7CBE\u7B80\u540E\u518D\u53D1\u9001",CONTENT_FILTERED:"\u5185\u5BB9\u88AB\u5B89\u5168\u7B56\u7565\u62E6\u622A\uFF0C\u8BF7\u8C03\u6574\u540E\u91CD\u8BD5",MODEL_REFUSAL:"\u6A21\u578B\u62D2\u7EDD\u54CD\u5E94\uFF0C\u6362\u4E2A\u8BF4\u6CD5\u8BD5\u8BD5",STREAM_INTERRUPTED:"\u56DE\u590D\u5DF2\u4E2D\u65AD\uFF0C\u8BF7\u91CD\u8BD5",RATE_LIMITED:"\u64CD\u4F5C\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5",MODEL_NOT_FOUND:"\u6240\u9009\u6A21\u578B\u4E0D\u53EF\u7528\uFF0C\u8BF7\u5207\u6362\u5176\u4ED6\u6A21\u578B",GAME_NOT_FOUND:"\u672A\u627E\u5230\u5BF9\u5E94\u6E38\u620F",INVALID_REQUEST:"\u8BF7\u6C42\u65E0\u6548\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",INTERNAL_ERROR:"\u670D\u52A1\u51FA\u4E86\u70B9\u5C0F\u95EE\u9898\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",NOT_INITIALIZED:"SDK \u5C1A\u672A\u521D\u59CB\u5316",NETWORK_ERROR:"\u7F51\u7EDC\u5F02\u5E38\uFF0C\u8BF7\u68C0\u67E5\u8FDE\u63A5"},V=!0;function W(o){V=o}function pe(){if(typeof document>"u")return null;let o=document.getElementById(D);if(!o){if(!document.getElementById(j)){let e=document.createElement("style");e.id=j,e.textContent=de,document.head.appendChild(e)}o=document.createElement("div"),o.id=D,document.body.appendChild(o)}return o}function U(o,e="info",t=3500){if(!V)return;let n=pe();if(!n)return;let i=document.createElement("div");i.className=`storvia-toast ${e}`,i.innerHTML=`
80
80
  <span class="storvia-toast-icon">${le[e]}</span>
81
81
  <span class="storvia-toast-msg"></span>
82
- `;let r=i.querySelector(".storvia-toast-msg");r&&(r.textContent=o),n.appendChild(i),requestAnimationFrame(()=>i.classList.add("show")),setTimeout(()=>{i.isConnected&&(i.classList.add("leaving"),i.classList.remove("show"),setTimeout(()=>i.remove(),320))},t)}function $(o,e){let t=ce[o]||e||"\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5";U(t,o==="INSUFFICIENT_CREDITS"||o==="RATE_LIMITED"?"warning":"error")}var N=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}maybeShowNetworkToast(e){e instanceof g||$("NETWORK_ERROR")}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){if(!this.debug)return;let{method:t,path:n,body:i,status:r,rawResponse:s,parsedData:a,error:d,durationMs:l,modelName:h}=e,m="%c[Storvia SDK]",c="color: #6366f1; font-weight: bold",p=l!==void 0?` (${l}ms)`:"",u=r!==void 0?` [${r}]`:"",f=h?` [model: ${h}]`:"";d?(console.groupCollapsed(`${m} %c${t} ${n}${u}${f}${p} %c\u2717`,c,"color: #e0e0e0","color: #ef4444"),i!==void 0&&console.log("Request:",i),s!==void 0&&console.log("Response (raw):",s),console.error("Error:",d),console.groupEnd()):(console.groupCollapsed(`${m} %c${t} ${n}${u}${f}${p} %c\u2713`,c,"color: #e0e0e0","color: #22c55e"),i!==void 0&&console.log("Request:",i),s!==void 0&&console.log("Response (raw):",s),a!==void 0&&a!==s&&console.log("Response (data):",a),console.groupEnd())}async get(e,t){let n=new URL(`${this.baseUrl}${e}`);t&&Object.entries(t).forEach(([a,d])=>n.searchParams.set(a,d));let i=Date.now(),r,s;try{let a=await fetch(n.toString(),{method:"GET",headers:this.buildHeaders()});r=a.status;let{raw:d,data:l}=await this.handleResponseWithRaw(a);return s=d,this.log({method:"GET",path:e,body:t,status:r,rawResponse:s,parsedData:l,durationMs:Date.now()-i}),l}catch(a){throw this.log({method:"GET",path:e,body:t,status:r,rawResponse:s,error:a,durationMs:Date.now()-i}),this.maybeShowNetworkToast(a),a}}async post(e,t,n){let i=Date.now(),r,s;try{let a=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0});r=a.status;let{raw:d,data:l}=await this.handleResponseWithRaw(a);return s=d,this.log({method:"POST",path:e,body:t,status:r,rawResponse:s,parsedData:l,durationMs:Date.now()-i,modelName:n?.modelName}),l}catch(a){throw this.log({method:"POST",path:e,body:t,status:r,rawResponse:s,error:a,durationMs:Date.now()-i,modelName:n?.modelName}),this.maybeShowNetworkToast(a),a}}async patch(e,t){let n=Date.now(),i,r;try{let s=await fetch(`${this.baseUrl}${e}`,{method:"PATCH",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0});i=s.status;let{raw:a,data:d}=await this.handleResponseWithRaw(s);return r=a,this.log({method:"PATCH",path:e,body:t,status:i,rawResponse:r,parsedData:d,durationMs:Date.now()-n}),d}catch(s){throw this.log({method:"PATCH",path:e,body:t,status:i,rawResponse:r,error:s,durationMs:Date.now()-n}),this.maybeShowNetworkToast(s),s}}async delete(e){let t=Date.now(),n,i;try{let r=await fetch(`${this.baseUrl}${e}`,{method:"DELETE",headers:this.buildHeaders()});n=r.status;let{raw:s,data:a}=await this.handleResponseWithRaw(r);return i=s,this.log({method:"DELETE",path:e,status:n,rawResponse:i,parsedData:a,durationMs:Date.now()-t}),a}catch(r){throw this.log({method:"DELETE",path:e,status:n,rawResponse:i,error:r,durationMs:Date.now()-t}),this.maybeShowNetworkToast(r),r}}async stream(e,t,n,i,r){let s=Date.now(),a=r?.modelName?` [model: ${r.modelName}]`:"",d=[],l=f=>{this.debug&&d.push({t:Date.now()-s,event:f})},h=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify(t)});if(!h.ok){let f=await h.text().catch(()=>""),v={};try{v=JSON.parse(f)}catch{}let L=v.code||"INTERNAL_ERROR",C=new g(L,v.message||`HTTP ${h.status}`);throw $(L,v.message),this.log({method:"STREAM",path:e,body:t,status:h.status,rawResponse:f,error:C,durationMs:Date.now()-s,modelName:r?.modelName}),C}let m=h.body?.getReader();if(!m)throw new g("INTERNAL_ERROR","No response body for stream");let c=new TextDecoder,p="",u="";try{for(;;){let{done:f,value:v}=await m.read();if(f)break;let C=c.decode(v,{stream:!0}).split(`
83
- `);for(let w of C){if(!w.startsWith("data: "))continue;let A=w.slice(6);if(A==="[DONE]"){l("[DONE]"),this.debug&&(console.groupCollapsed(`%c[Storvia SDK] %cSTREAM ${e} [${h.status}]${a} (${Date.now()-s}ms) %c\u2713`,"color: #6366f1; font-weight: bold","color: #e0e0e0","color: #22c55e"),console.log("Request:",t),console.log(`Accumulated content (${u.length} chars):`,u),console.log("Message ID:",p),console.log(`SSE events (${d.length}):`,d),console.groupEnd()),i(p);return}try{let x=JSON.parse(A);l(x),x.type==="done"&&x.id?p=x.id:x.content&&(u+=x.content,n(x.content))}catch{l({raw:A})}}}}catch(f){throw this.debug&&(console.groupCollapsed(`%c[Storvia SDK] %cSTREAM ${e} [${h.status}]${a} (${Date.now()-s}ms) %c\u2717`,"color: #6366f1; font-weight: bold","color: #e0e0e0","color: #ef4444"),console.log("Request:",t),console.log(`Accumulated content (${u.length} chars):`,u),console.log(`SSE events (${d.length}):`,d),console.error("Stream error:",f),console.groupEnd()),f}p&&i(p)}async handleResponseWithRaw(e){let t=await e.text(),n;try{n=t?JSON.parse(t):null}catch{n=t}if(!e.ok){let i=n&&typeof n=="object"?n:{},r={401:"UNAUTHORIZED",402:"INSUFFICIENT_CREDITS",404:"GAME_NOT_FOUND",429:"RATE_LIMITED"},s=i.code||r[e.status]||"INTERNAL_ERROR",a=new g(s,i.message||`HTTP ${e.status}`);throw $(s,i.message),a}return n&&typeof n=="object"&&"data"in n?{raw:n,data:n.data}:{raw:n,data:n}}};var O=[{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"}],K=[{value:"low",label:"\u7B80\u77ED"},{value:"medium",label:"\u9002\u4E2D"},{value:"high",label:"\u8BE6\u7EC6"}],he="https://cdn.storvia.ai/default/logo.png",ge="https://api.storvia.ai/storage/v1/object/public/storvia/default/credits.png",me=`
82
+ `;let r=i.querySelector(".storvia-toast-msg");r&&(r.textContent=o),n.appendChild(i),requestAnimationFrame(()=>i.classList.add("show")),setTimeout(()=>{i.isConnected&&(i.classList.add("leaving"),i.classList.remove("show"),setTimeout(()=>i.remove(),320))},t)}function $(o,e){let t=ce[o]||e||"\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5";U(t,o==="INSUFFICIENT_CREDITS"||o==="RATE_LIMITED"?"warning":"error")}var L=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}maybeShowNetworkToast(e){e instanceof g||$("NETWORK_ERROR")}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){if(!this.debug)return;let{method:t,path:n,body:i,status:r,rawResponse:s,parsedData:a,error:d,durationMs:l,modelName:h}=e,m="%c[Storvia SDK]",c="color: #6366f1; font-weight: bold",p=l!==void 0?` (${l}ms)`:"",u=r!==void 0?` [${r}]`:"",f=h?` [model: ${h}]`:"";d?(console.groupCollapsed(`${m} %c${t} ${n}${u}${f}${p} %c\u2717`,c,"color: #e0e0e0","color: #ef4444"),i!==void 0&&console.log("Request:",i),s!==void 0&&console.log("Response (raw):",s),console.error("Error:",d),console.groupEnd()):(console.groupCollapsed(`${m} %c${t} ${n}${u}${f}${p} %c\u2713`,c,"color: #e0e0e0","color: #22c55e"),i!==void 0&&console.log("Request:",i),s!==void 0&&console.log("Response (raw):",s),a!==void 0&&a!==s&&console.log("Response (data):",a),console.groupEnd())}async get(e,t){let n=new URL(`${this.baseUrl}${e}`);t&&Object.entries(t).forEach(([a,d])=>n.searchParams.set(a,d));let i=Date.now(),r,s;try{let a=await fetch(n.toString(),{method:"GET",headers:this.buildHeaders()});r=a.status;let{raw:d,data:l}=await this.handleResponseWithRaw(a);return s=d,this.log({method:"GET",path:e,body:t,status:r,rawResponse:s,parsedData:l,durationMs:Date.now()-i}),l}catch(a){throw this.log({method:"GET",path:e,body:t,status:r,rawResponse:s,error:a,durationMs:Date.now()-i}),this.maybeShowNetworkToast(a),a}}async post(e,t,n){let i=Date.now(),r,s;try{let a=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0});r=a.status;let{raw:d,data:l}=await this.handleResponseWithRaw(a);return s=d,this.log({method:"POST",path:e,body:t,status:r,rawResponse:s,parsedData:l,durationMs:Date.now()-i,modelName:n?.modelName}),l}catch(a){throw this.log({method:"POST",path:e,body:t,status:r,rawResponse:s,error:a,durationMs:Date.now()-i,modelName:n?.modelName}),this.maybeShowNetworkToast(a),a}}async patch(e,t){let n=Date.now(),i,r;try{let s=await fetch(`${this.baseUrl}${e}`,{method:"PATCH",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0});i=s.status;let{raw:a,data:d}=await this.handleResponseWithRaw(s);return r=a,this.log({method:"PATCH",path:e,body:t,status:i,rawResponse:r,parsedData:d,durationMs:Date.now()-n}),d}catch(s){throw this.log({method:"PATCH",path:e,body:t,status:i,rawResponse:r,error:s,durationMs:Date.now()-n}),this.maybeShowNetworkToast(s),s}}async delete(e){let t=Date.now(),n,i;try{let r=await fetch(`${this.baseUrl}${e}`,{method:"DELETE",headers:this.buildHeaders()});n=r.status;let{raw:s,data:a}=await this.handleResponseWithRaw(r);return i=s,this.log({method:"DELETE",path:e,status:n,rawResponse:i,parsedData:a,durationMs:Date.now()-t}),a}catch(r){throw this.log({method:"DELETE",path:e,status:n,rawResponse:i,error:r,durationMs:Date.now()-t}),this.maybeShowNetworkToast(r),r}}async stream(e,t,n,i,r){let s=Date.now(),a=r?.modelName?` [model: ${r.modelName}]`:"",d=[],l=f=>{this.debug&&d.push({t:Date.now()-s,event:f})},h=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify(t)});if(!h.ok){let f=await h.text().catch(()=>""),v={};try{v=JSON.parse(f)}catch{}let O=v.code||"INTERNAL_ERROR",C=new g(O,v.message||`HTTP ${h.status}`);throw $(O,v.message),this.log({method:"STREAM",path:e,body:t,status:h.status,rawResponse:f,error:C,durationMs:Date.now()-s,modelName:r?.modelName}),C}let m=h.body?.getReader();if(!m)throw new g("INTERNAL_ERROR","No response body for stream");let c=new TextDecoder,p="",u="";try{for(;;){let{done:f,value:v}=await m.read();if(f)break;let C=c.decode(v,{stream:!0}).split(`
83
+ `);for(let w of C){if(!w.startsWith("data: "))continue;let A=w.slice(6);if(A==="[DONE]"){l("[DONE]"),this.debug&&(console.groupCollapsed(`%c[Storvia SDK] %cSTREAM ${e} [${h.status}]${a} (${Date.now()-s}ms) %c\u2713`,"color: #6366f1; font-weight: bold","color: #e0e0e0","color: #22c55e"),console.log("Request:",t),console.log(`Accumulated content (${u.length} chars):`,u),console.log("Message ID:",p),console.log(`SSE events (${d.length}):`,d),console.groupEnd()),i(p);return}try{let x=JSON.parse(A);l(x),x.type==="done"&&x.id?p=x.id:x.content&&(u+=x.content,n(x.content))}catch{l({raw:A})}}}}catch(f){throw this.debug&&(console.groupCollapsed(`%c[Storvia SDK] %cSTREAM ${e} [${h.status}]${a} (${Date.now()-s}ms) %c\u2717`,"color: #6366f1; font-weight: bold","color: #e0e0e0","color: #ef4444"),console.log("Request:",t),console.log(`Accumulated content (${u.length} chars):`,u),console.log(`SSE events (${d.length}):`,d),console.error("Stream error:",f),console.groupEnd()),f}p&&i(p)}async handleResponseWithRaw(e){let t=await e.text(),n;try{n=t?JSON.parse(t):null}catch{n=t}if(!e.ok){let i=n&&typeof n=="object"?n:{},r={401:"UNAUTHORIZED",402:"INSUFFICIENT_CREDITS",404:"GAME_NOT_FOUND",429:"RATE_LIMITED"},s=i.code||r[e.status]||"INTERNAL_ERROR",a=new g(s,i.message||`HTTP ${e.status}`);throw $(s,i.message),a}return n&&typeof n=="object"&&"data"in n?{raw:n,data:n.data}:{raw:n,data:n}}};var N=[{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"}],K=[{value:"low",label:"\u7B80\u77ED"},{value:"medium",label:"\u9002\u4E2D"},{value:"high",label:"\u8BE6\u7EC6"}],he="https://cdn.storvia.ai/default/logo.png",ge="https://api.storvia.ai/storage/v1/object/public/storvia/default/credits.png",me=`
84
84
  :host {
85
85
  position: fixed;
86
86
  z-index: 2147483647;
@@ -766,5 +766,5 @@
766
766
  <span class="credits-unit">/\u6B21</span>
767
767
  </div>`:""}
768
768
  ${r?`<div class="detail-description">${this.escapeHtml(r)}</div>`:""}
769
- `}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 r=document.createElement("p");r.className="form-hint",r.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(r);let s=document.createElement("input");s.type="range",s.className="slider",s.min="0",s.max="1",s.step="0.1",s.value=String(this.settings.temperature),s.addEventListener("input",()=>{let d=parseFloat(s.value);this.settings.temperature=d,this.tempValueEl&&(this.tempValueEl.textContent=d.toFixed(1))}),e.appendChild(s);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=[],K.forEach(i=>{let r=document.createElement("button");r.className=`segment-button${i.value===this.settings.replyLength?" active":""}`,r.textContent=i.label,r.addEventListener("click",()=>{this.settings.replyLength=i.value,this.segmentBtns.forEach((s,a)=>{s.classList.toggle("active",K[a].value===i.value)})}),this.segmentBtns.push(r),n.appendChild(r)}),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 r=document.createElement("span");r.textContent=O.find(d=>d.value===this.settings.replyLanguage)?.label||"";let s=document.createElement("span");s.className="select-arrow",s.textContent="\u25BE",this.langArrow=s,i.appendChild(r),i.appendChild(s),i.addEventListener("click",d=>{d.stopPropagation(),this.toggleLangDropdown()}),n.appendChild(i);let a=document.createElement("div");return a.className="select-dropdown",this.langDropdown=a,this.langOptions=[],O.forEach(d=>{let l=document.createElement("button");l.className=`select-option${d.value===this.settings.replyLanguage?" active":""}`,l.innerHTML=`<span>${d.label}</span>${d.value===this.settings.replyLanguage?Y:""}`,l.addEventListener("click",()=>{this.settings.replyLanguage=d.value,r.textContent=d.label,this.langOptions.forEach((h,m)=>{h.classList.toggle("active",O[m].value===d.value),h.innerHTML=`<span>${O[m].label}</span>${O[m].value===d.value?Y:""}`}),this.closeLangDropdown()}),this.langOptions.push(l),a.appendChild(l)}),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.playerNote.length}/50`,this.noteCounter=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let r=document.createElement("p");r.className="form-hint",r.textContent="\u5199\u4E0B\u4F60\u5BF9\u8FD9\u4E2A\u6E38\u620F\u7684\u5907\u6CE8\uFF0C\u4F1A\u663E\u793A\u5728\u5B58\u6863\u5217\u8868",e.appendChild(r);let s=document.createElement("textarea");return s.className="player-note-input",s.placeholder="\u5907\u6CE8",s.maxLength=50,s.rows=2,s.value=this.settings.playerNote,s.addEventListener("input",()=>{this.settings.playerNote=s.value,this.noteCounter&&(this.noteCounter.textContent=`${s.value.length}/50`)}),e.appendChild(s),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 r=document.createElement("button");return r.className="btn btn-sync",this.syncBtn=r,this.renderSyncBtn(),r.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(r),e}setSyncState(e){this.syncState=e,this.renderSyncBtn()}renderSyncBtn(){if(!this.syncBtn)return;let e=this.syncState,t={idle:fe,loading:ve,success:be,error:ye},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{if(this.pendingModelId&&this.pendingModelId!==this.selectedModelId){let e=this.models.find(t=>t.id===this.pendingModelId);if(e&&e.is_active!==!1){this.selectedModelId=this.pendingModelId,this.callbacks.onModelChange(this.pendingModelId);try{localStorage.setItem("storvia_model_id",this.pendingModelId)}catch{}}else this.pendingModelId=this.selectedModelId}await this.callbacks.onSettingsChange({temperature:this.settings.temperature,replyLength:this.settings.replyLength,replyLanguage:this.settings.replyLanguage,playerNote:this.settings.playerNote}),this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1),this.closePanel()}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+b/2<window.innerWidth/2,t=380;e?(this.panel.style.left="0",this.panel.style.right="auto"):(this.panel.style.left=`${b-t}px`,this.panel.style.right="auto"),this.fabY>500?(this.panel.style.bottom=`${b+8}px`,this.panel.style.top="auto"):(this.panel.style.top=`${b+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.fabWrap&&(this.fabWrap.style.pointerEvents="none"))}),this.isMobile()&&this.lockBodyScroll()))}closePanel(){if(this.panel&&this.panel.classList.remove("open"),this.fab&&(this.fab.style.visibility="visible"),this.fabDot&&(this.fabDot.style.visibility="visible"),this.fabWrap&&(this.fabWrap.style.pointerEvents=""),this.unlockBodyScroll(),this.pendingModelId!==this.selectedModelId){if(this.pendingModelId=this.selectedModelId,this.modelGrid){let e=this.getFilteredModels();this.modelGrid.querySelectorAll(".model-card").forEach((t,n)=>{t.classList.toggle("selected",e[n].id===this.pendingModelId)})}this.renderModelDetail()}}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 S=class{constructor(e,t,n,i,r=!1,s,a,d){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=i;this.isPreview=r;this.previewConfig=s,this.getSettings=a,this.getModelName=d}reqMeta(){let e=this.getModelName?.();return e?{modelName:e}:void 0}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.sceneKey,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta());return}return this.http.post("/chat",t,this.reqMeta())}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,sceneKey:e.sceneKey,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.sceneKey,stream:e.stream??!1};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta());return}return this.http.post("/generate",t,this.reqMeta())}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.sceneKey,stream:e.stream??!1};if(e.stream){await this.http.stream("/retry",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta());return}return this.http.post("/retry",t,this.reqMeta())}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,scene_key:e.sceneKey,history_messages:[]};this.previewConfig?t.prompt_config=this.previewConfig:t.game_id=this.getGameId();let n=this.getSettings?.();if(n&&(typeof n.temperature=="number"&&(t.temperature=n.temperature),n.replyLength&&(t.reply_length=n.replyLength),n.replyLanguage&&(t.reply_language=n.replyLanguage)),e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta());return}let i="";return await this.http.stream("/preview",t,r=>{i+=r},()=>{},this.reqMeta()),{id:"",content:i}}};var H=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,t){if(this.isPreview){let i=this.mem[e]||{};return t?{...i[t]||{}}:{...i}}let n=t?{group:t}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,n)}async update(e,t,n){if(this.isPreview){let i=this.mem[e]||(this.mem[e]={});i[t]={...i[t]||{},...n};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,{group:t,values:n})}},E=class{constructor(e,t,n=!1,i,r){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];i&&(this.mem=i.map(X)),this.state=new H(e,t,n,r)}setInitial(e,t){this.mem=e?e.map(X):[],this.state.setInitial(t)}async list(){return this.isPreview?this.mem.map(q):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return t?q(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 X(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 q(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 R=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];i&&(this.mem=i.map(r=>({...r})))}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(r=>r.from===e&&r.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)}`)}};function Z(o){let e={count:o.count};return o.desc!==void 0&&(e.desc=o.desc),o.icon_url!==void 0&&(e.iconUrl=o.icon_url),e}function F(o){let e={};if(!o)return e;for(let[t,n]of Object.entries(o)){let i={};for(let[r,s]of Object.entries(n))i[r]=Z(s);e[t]=i}return e}function xe(o){let e={};if(!o)return e;for(let[t,n]of Object.entries(o))e[t]=Z(n);return e}var T=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem=F(i))}setInitial(e){this.mem=e?F(e):{}}async list(e){if(this.isPreview){if(e!==void 0)return{...this.mem[e]||{}};let n={};for(let[i,r]of Object.entries(this.mem))n[i]={...r};return n}if(e!==void 0){let n=await this.http.get(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`);return xe(n)}let t=await this.http.get(`/conversations/${this.getConversationId()}/inventory`);return F(t)}async add(e){let{group:t,name:n,count:i=1,desc:r,iconUrl:s}=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 d={count:i};r!==void 0&&(d.desc=r),s!==void 0&&(d.iconUrl=s),this.mem[t][n]=d;return}let a={group:t,name:n,count:i};r!==void 0&&(a.desc=r),s!==void 0&&(a.icon_url=s),await this.http.post(`/conversations/${this.getConversationId()}/inventory`,a)}async update(e){let{group:t,name:n,count:i,desc:r,iconUrl:s}=e;if(this.isPreview){let d=this.mem[t];if(!d||!(n in d))throw new Error(`Item "${t}/${n}" not found`);let l=d[n];i!==void 0&&(l.count=i),r!==void 0&&(l.desc=r),s!==void 0&&(l.iconUrl=s);return}let a={};i!==void 0&&(a.count=i),r!==void 0&&(a.desc=r),s!==void 0&&(a.icon_url=s),await this.http.patch(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,a)}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:r}=e;if(this.isPreview){let s=this.mem[t];if(!s||!(i in s))throw new Error(`Source item "${t}/${i}" not found`);if(!this.mem[n])throw new Error(`Target group "${n}" does not exist`);let a=r||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]=s[i],delete s[i];return}await this.http.post(`/conversations/${this.getConversationId()}/inventory/move`,{fromGroup:t,toGroup:n,name:i,newName:r})}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 r=this.mem[e];if(r&&Object.keys(r).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 k=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 G=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})}},P=class{constructor(e,t,n=!1,i,r){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};i&&(this.memPersona={...i}),this.state=new G(e,t,n,r)}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 M=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem=J(i))}setInitial(e){this.mem=e?J(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 J(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 Q="/functions/v1/world-engine/v1",Ce="https://api.storvia.ai";function Ie(){return window.__STORVIA__||{}}function Se(o=5e3){let e=Ie();return e.apiBase?Promise.resolve(e):new Promise((t,n)=>{let i=setTimeout(()=>{window.removeEventListener("message",r),n(new g("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},o);function r(s){let a=null;if(s.data?.type==="storvia-init"&&s.data.apiBase?a={apiBase:s.data.apiBase,gameId:s.data.gameId,accessToken:s.data.accessToken}:s.data?.type==="storvia-preview-init"&&s.data.config&&(a=s.data.config),a&&a.apiBase){clearTimeout(i),window.removeEventListener("message",r);let d=window;d.__STORVIA__=a,t(a)}}window.addEventListener("message",r)})}var D=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.models=[];this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){if(this.initialized)return;let e=await Se(),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}${Q}`,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 N(this.baseUrl,this.accessToken,!!e.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let[c,p]=await Promise.all([this.fetchModels(),this.fetchPreviewSnapshot()]);this.models=c;let u=this.getSavedModelId();this.modelId=e.selectedModelId||(u&&c.some(w=>w.id===u)?u:"")||c[0]?.id||"",this.settingsSheet=new I({onModelChange:w=>{this.modelId=w},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),c.length>0&&this.settingsSheet.mount(c,this.modelId,{temperature:1,replyLength:"medium",replyLanguage:"zh-CN",playerNote:""},!1);let f=()=>this.gameId,v=()=>this.conversationId,L=()=>this.modelId,C=()=>this.models.find(w=>w.id===this.modelId)?.name;this.chat=new S(this.http,f,v,L,!0,this.previewConfig,()=>this.settingsSheet?.getSettings()??null,C),this.characters=new E(this.http,v,!0,p?.characters,p?.characterStates),this.relationships=new R(this.http,v,!0,p?.relationships),this.inventory=new T(this.http,v,!0,p?.inventory),this.world=new k(this.http,v,!0,p?.world),this.player=new P(this.http,v,!0,p?.player,p?.playerState),this.custom=new M(this.http,v,!0,p?.custom),this.initialized=!0,this.listenForPreviewMessages();return}let[n,i]=await Promise.all([this.authenticate(),this.fetchModels()]);this.conversationId=n.conversationId,this.models=i;let r=this.getSavedModelId();this.modelId=r&&i.some(c=>c.id===r)?r:i[0]?.id||"";let s=n.settings,a=s?{temperature:s.temperature??1,replyLength:s.reply_length??"medium",replyLanguage:s.reply_language??"zh-CN",playerNote:s.player_note??""}:{temperature:1,replyLength:"medium",replyLanguage:"zh-CN",playerNote:""};this.settingsSheet=new I({onModelChange:c=>{this.modelId=c},onSettingsChange:c=>this.saveSettings(c),onSync:()=>this.syncSettings()}),this.settingsSheet.mount(i,this.modelId,a,n.hasWorldUpdate??!1);let d=()=>this.gameId,l=()=>this.conversationId,h=()=>this.modelId,m=()=>this.models.find(c=>c.id===this.modelId)?.name;this.chat=new S(this.http,d,l,h,!1,void 0,void 0,m),this.characters=new E(this.http,l),this.relationships=new R(this.http,l),this.inventory=new T(this.http,l),this.world=new k(this.http,l),this.player=new P(this.http,l),this.custom=new M(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){let t={conversation_id:this.conversationId};e.temperature!==void 0&&(t.temperature=e.temperature),e.replyLength!==void 0&&(t.reply_length=e.replyLength),e.replyLanguage!==void 0&&(t.reply_language=e.replyLanguage),e.playerNote!==void 0&&(t.player_note=e.playerNote),await this.http.patch("/settings",t)}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=`${Ce}${Q}`,this.gameId=e.gameId,this.isPreview=!0,this.http=new N(this.baseUrl,"",!1,e.apiKey);let[t,n]=await Promise.all([this.fetchModels(),this.fetchPreviewSnapshot()]);this.models=t;let i=this.getSavedModelId();this.modelId=(i&&t.some(l=>l.id===i)?i:"")||t[0]?.id||"",this.conversationId="00000000-0000-0000-0000-000000000000",this.settingsSheet=new I({onModelChange:l=>{this.modelId=l},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),t.length>0&&this.settingsSheet.mount(t,this.modelId,{temperature:1,replyLength:"medium",replyLanguage:"zh-CN",playerNote:""},!1);let r=()=>this.gameId,s=()=>this.conversationId,a=()=>this.modelId,d=()=>this.models.find(l=>l.id===this.modelId)?.name;this.chat=new S(this.http,r,s,a,!0,void 0,()=>this.settingsSheet?.getSettings()??null,d),this.characters=new E(this.http,s,!0,n?.characters,n?.characterStates),this.relationships=new R(this.http,s,!0,n?.relationships),this.inventory=new T(this.http,s,!0,n?.inventory),this.world=new k(this.http,s,!0,n?.world),this.player=new P(this.http,s,!0,n?.player,n?.playerState),this.custom=new M(this.http,s,!0,n?.custom),this.initialized=!0}};async function ee(o){let e=new D;return o?.dev?await e.initDev(o.dev):await e.init(),e}function z(o){return typeof o=="object"&&o!==null&&"value"in o&&"type"in o&&(o.type==="number"||o.type==="text")}function te(o){return z(o)?o.value:o}return ae(Ee);})();
769
+ `}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 r=document.createElement("p");r.className="form-hint",r.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(r);let s=document.createElement("input");s.type="range",s.className="slider",s.min="0",s.max="1",s.step="0.1",s.value=String(this.settings.temperature),s.addEventListener("input",()=>{let d=parseFloat(s.value);this.settings.temperature=d,this.tempValueEl&&(this.tempValueEl.textContent=d.toFixed(1))}),e.appendChild(s);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=[],K.forEach(i=>{let r=document.createElement("button");r.className=`segment-button${i.value===this.settings.replyLength?" active":""}`,r.textContent=i.label,r.addEventListener("click",()=>{this.settings.replyLength=i.value,this.segmentBtns.forEach((s,a)=>{s.classList.toggle("active",K[a].value===i.value)})}),this.segmentBtns.push(r),n.appendChild(r)}),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 r=document.createElement("span");r.textContent=N.find(d=>d.value===this.settings.replyLanguage)?.label||"";let s=document.createElement("span");s.className="select-arrow",s.textContent="\u25BE",this.langArrow=s,i.appendChild(r),i.appendChild(s),i.addEventListener("click",d=>{d.stopPropagation(),this.toggleLangDropdown()}),n.appendChild(i);let a=document.createElement("div");return a.className="select-dropdown",this.langDropdown=a,this.langOptions=[],N.forEach(d=>{let l=document.createElement("button");l.className=`select-option${d.value===this.settings.replyLanguage?" active":""}`,l.innerHTML=`<span>${d.label}</span>${d.value===this.settings.replyLanguage?Y:""}`,l.addEventListener("click",()=>{this.settings.replyLanguage=d.value,r.textContent=d.label,this.langOptions.forEach((h,m)=>{h.classList.toggle("active",N[m].value===d.value),h.innerHTML=`<span>${N[m].label}</span>${N[m].value===d.value?Y:""}`}),this.closeLangDropdown()}),this.langOptions.push(l),a.appendChild(l)}),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.playerNote.length}/50`,this.noteCounter=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let r=document.createElement("p");r.className="form-hint",r.textContent="\u5199\u4E0B\u4F60\u5BF9\u8FD9\u4E2A\u6E38\u620F\u7684\u5907\u6CE8\uFF0C\u4F1A\u663E\u793A\u5728\u5B58\u6863\u5217\u8868",e.appendChild(r);let s=document.createElement("textarea");return s.className="player-note-input",s.placeholder="\u5907\u6CE8",s.maxLength=50,s.rows=2,s.value=this.settings.playerNote,s.addEventListener("input",()=>{this.settings.playerNote=s.value,this.noteCounter&&(this.noteCounter.textContent=`${s.value.length}/50`)}),e.appendChild(s),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 r=document.createElement("button");return r.className="btn btn-sync",this.syncBtn=r,this.renderSyncBtn(),r.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(r),e}setSyncState(e){this.syncState=e,this.renderSyncBtn()}renderSyncBtn(){if(!this.syncBtn)return;let e=this.syncState,t={idle:fe,loading:ve,success:be,error:ye},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{if(this.pendingModelId&&this.pendingModelId!==this.selectedModelId){let e=this.models.find(t=>t.id===this.pendingModelId);if(e&&e.is_active!==!1){this.selectedModelId=this.pendingModelId,this.callbacks.onModelChange(this.pendingModelId);try{localStorage.setItem("storvia_model_id",this.pendingModelId)}catch{}}else this.pendingModelId=this.selectedModelId}await this.callbacks.onSettingsChange({temperature:this.settings.temperature,replyLength:this.settings.replyLength,replyLanguage:this.settings.replyLanguage,playerNote:this.settings.playerNote}),this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1),this.closePanel()}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+b/2<window.innerWidth/2,t=380;e?(this.panel.style.left="0",this.panel.style.right="auto"):(this.panel.style.left=`${b-t}px`,this.panel.style.right="auto"),this.fabY>500?(this.panel.style.bottom=`${b+8}px`,this.panel.style.top="auto"):(this.panel.style.top=`${b+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.fabWrap&&(this.fabWrap.style.pointerEvents="none"))}),this.isMobile()&&this.lockBodyScroll()))}closePanel(){if(this.panel&&this.panel.classList.remove("open"),this.fab&&(this.fab.style.visibility="visible"),this.fabDot&&(this.fabDot.style.visibility="visible"),this.fabWrap&&(this.fabWrap.style.pointerEvents=""),this.unlockBodyScroll(),this.pendingModelId!==this.selectedModelId){if(this.pendingModelId=this.selectedModelId,this.modelGrid){let e=this.getFilteredModels();this.modelGrid.querySelectorAll(".model-card").forEach((t,n)=>{t.classList.toggle("selected",e[n].id===this.pendingModelId)})}this.renderModelDetail()}}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 S=class{constructor(e,t,n,i,r=!1,s,a,d){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=i;this.isPreview=r;this.previewConfig=s,this.getSettings=a,this.getModelName=d}reqMeta(){let e=this.getModelName?.();return e?{modelName:e}:void 0}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.sceneKey,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta());return}return this.http.post("/chat",t,this.reqMeta())}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,sceneKey:e.sceneKey,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.sceneKey,stream:e.stream??!1};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta());return}return this.http.post("/generate",t,this.reqMeta())}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.sceneKey,stream:e.stream??!1};if(e.stream){await this.http.stream("/retry",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta());return}return this.http.post("/retry",t,this.reqMeta())}async messages(e){if(this.isPreview)return{data:[],hasMore:!1,nextCursor:null};let t={conversation_id:this.getConversationId(),order:e.order,limit:String(e.limit??20)};e.topic&&(t.topic=e.topic),e.cursor&&(t.cursor_uuid=e.cursor.uuid,t.cursor_created_at=e.cursor.createdAt);let n=await this.http.get("/messages",t);return{data:n.messages.map(i=>({uuid:i.uuid,role:i.role,content:i.content,topic:i.topic,status:i.status,model:i.model,createdAt:i.created_at})),hasMore:n.has_more,nextCursor:n.next_cursor?{uuid:n.next_cursor.cursor_uuid,createdAt:n.next_cursor.cursor_created_at}:null}}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,scene_key:e.sceneKey,history_messages:[]};this.previewConfig?t.prompt_config=this.previewConfig:t.game_id=this.getGameId();let n=this.getSettings?.();if(n&&(typeof n.temperature=="number"&&(t.temperature=n.temperature),n.replyLength&&(t.reply_length=n.replyLength),n.replyLanguage&&(t.reply_language=n.replyLanguage)),e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta());return}let i="";return await this.http.stream("/preview",t,r=>{i+=r},()=>{},this.reqMeta()),{id:"",content:i}}};var H=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,t){if(this.isPreview){let i=this.mem[e]||{};return t?{...i[t]||{}}:{...i}}let n=t?{group:t}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,n)}async update(e,t,n){if(this.isPreview){let i=this.mem[e]||(this.mem[e]={});i[t]={...i[t]||{},...n};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,{group:t,values:n})}},E=class{constructor(e,t,n=!1,i,r){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];i&&(this.mem=i.map(X)),this.state=new H(e,t,n,r)}setInitial(e,t){this.mem=e?e.map(X):[],this.state.setInitial(t)}async list(){return this.isPreview?this.mem.map(q):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return t?q(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 X(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 q(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 R=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];i&&(this.mem=i.map(r=>({...r})))}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(r=>r.from===e&&r.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)}`)}};function Z(o){let e={count:o.count};return o.desc!==void 0&&(e.desc=o.desc),o.icon_url!==void 0&&(e.iconUrl=o.icon_url),e}function F(o){let e={};if(!o)return e;for(let[t,n]of Object.entries(o)){let i={};for(let[r,s]of Object.entries(n))i[r]=Z(s);e[t]=i}return e}function xe(o){let e={};if(!o)return e;for(let[t,n]of Object.entries(o))e[t]=Z(n);return e}var T=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem=F(i))}setInitial(e){this.mem=e?F(e):{}}async list(e){if(this.isPreview){if(e!==void 0)return{...this.mem[e]||{}};let n={};for(let[i,r]of Object.entries(this.mem))n[i]={...r};return n}if(e!==void 0){let n=await this.http.get(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`);return xe(n)}let t=await this.http.get(`/conversations/${this.getConversationId()}/inventory`);return F(t)}async add(e){let{group:t,name:n,count:i=1,desc:r,iconUrl:s}=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 d={count:i};r!==void 0&&(d.desc=r),s!==void 0&&(d.iconUrl=s),this.mem[t][n]=d;return}let a={group:t,name:n,count:i};r!==void 0&&(a.desc=r),s!==void 0&&(a.icon_url=s),await this.http.post(`/conversations/${this.getConversationId()}/inventory`,a)}async update(e){let{group:t,name:n,count:i,desc:r,iconUrl:s}=e;if(this.isPreview){let d=this.mem[t];if(!d||!(n in d))throw new Error(`Item "${t}/${n}" not found`);let l=d[n];i!==void 0&&(l.count=i),r!==void 0&&(l.desc=r),s!==void 0&&(l.iconUrl=s);return}let a={};i!==void 0&&(a.count=i),r!==void 0&&(a.desc=r),s!==void 0&&(a.icon_url=s),await this.http.patch(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,a)}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:r}=e;if(this.isPreview){let s=this.mem[t];if(!s||!(i in s))throw new Error(`Source item "${t}/${i}" not found`);if(!this.mem[n])throw new Error(`Target group "${n}" does not exist`);let a=r||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]=s[i],delete s[i];return}await this.http.post(`/conversations/${this.getConversationId()}/inventory/move`,{fromGroup:t,toGroup:n,name:i,newName:r})}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 r=this.mem[e];if(r&&Object.keys(r).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 k=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 G=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})}},P=class{constructor(e,t,n=!1,i,r){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};i&&(this.memPersona={...i}),this.state=new G(e,t,n,r)}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 M=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem=J(i))}setInitial(e){this.mem=e?J(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 J(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 Q="/functions/v1/world-engine/v1",Ce="https://api.storvia.ai";function Ie(){return window.__STORVIA__||{}}function Se(o=5e3){let e=Ie();return e.apiBase?Promise.resolve(e):new Promise((t,n)=>{let i=setTimeout(()=>{window.removeEventListener("message",r),n(new g("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},o);function r(s){let a=null;if(s.data?.type==="storvia-init"&&s.data.apiBase?a={apiBase:s.data.apiBase,gameId:s.data.gameId,accessToken:s.data.accessToken}:s.data?.type==="storvia-preview-init"&&s.data.config&&(a=s.data.config),a&&a.apiBase){clearTimeout(i),window.removeEventListener("message",r);let d=window;d.__STORVIA__=a,t(a)}}window.addEventListener("message",r)})}var _=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.models=[];this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){if(this.initialized)return;let e=await Se(),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}${Q}`,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 L(this.baseUrl,this.accessToken,!!e.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let[c,p]=await Promise.all([this.fetchModels(),this.fetchPreviewSnapshot()]);this.models=c;let u=this.getSavedModelId();this.modelId=e.selectedModelId||(u&&c.some(w=>w.id===u)?u:"")||c[0]?.id||"",this.settingsSheet=new I({onModelChange:w=>{this.modelId=w},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),c.length>0&&this.settingsSheet.mount(c,this.modelId,{temperature:1,replyLength:"medium",replyLanguage:"zh-CN",playerNote:""},!1);let f=()=>this.gameId,v=()=>this.conversationId,O=()=>this.modelId,C=()=>this.models.find(w=>w.id===this.modelId)?.name;this.chat=new S(this.http,f,v,O,!0,this.previewConfig,()=>this.settingsSheet?.getSettings()??null,C),this.characters=new E(this.http,v,!0,p?.characters,p?.characterStates),this.relationships=new R(this.http,v,!0,p?.relationships),this.inventory=new T(this.http,v,!0,p?.inventory),this.world=new k(this.http,v,!0,p?.world),this.player=new P(this.http,v,!0,p?.player,p?.playerState),this.custom=new M(this.http,v,!0,p?.custom),this.initialized=!0,this.listenForPreviewMessages();return}let[n,i]=await Promise.all([this.authenticate(),this.fetchModels()]);this.conversationId=n.conversationId,this.models=i;let r=this.getSavedModelId();this.modelId=r&&i.some(c=>c.id===r)?r:i[0]?.id||"";let s=n.settings,a=s?{temperature:s.temperature??1,replyLength:s.reply_length??"medium",replyLanguage:s.reply_language??"zh-CN",playerNote:s.player_note??""}:{temperature:1,replyLength:"medium",replyLanguage:"zh-CN",playerNote:""};this.settingsSheet=new I({onModelChange:c=>{this.modelId=c},onSettingsChange:c=>this.saveSettings(c),onSync:()=>this.syncSettings()}),this.settingsSheet.mount(i,this.modelId,a,n.hasWorldUpdate??!1);let d=()=>this.gameId,l=()=>this.conversationId,h=()=>this.modelId,m=()=>this.models.find(c=>c.id===this.modelId)?.name;this.chat=new S(this.http,d,l,h,!1,void 0,void 0,m),this.characters=new E(this.http,l),this.relationships=new R(this.http,l),this.inventory=new T(this.http,l),this.world=new k(this.http,l),this.player=new P(this.http,l),this.custom=new M(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){let t={conversation_id:this.conversationId};e.temperature!==void 0&&(t.temperature=e.temperature),e.replyLength!==void 0&&(t.reply_length=e.replyLength),e.replyLanguage!==void 0&&(t.reply_language=e.replyLanguage),e.playerNote!==void 0&&(t.player_note=e.playerNote),await this.http.patch("/settings",t)}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=`${Ce}${Q}`,this.gameId=e.gameId,this.isPreview=!0,this.http=new L(this.baseUrl,"",!1,e.apiKey);let[t,n]=await Promise.all([this.fetchModels(),this.fetchPreviewSnapshot()]);this.models=t;let i=this.getSavedModelId();this.modelId=(i&&t.some(l=>l.id===i)?i:"")||t[0]?.id||"",this.conversationId="00000000-0000-0000-0000-000000000000",this.settingsSheet=new I({onModelChange:l=>{this.modelId=l},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),t.length>0&&this.settingsSheet.mount(t,this.modelId,{temperature:1,replyLength:"medium",replyLanguage:"zh-CN",playerNote:""},!1);let r=()=>this.gameId,s=()=>this.conversationId,a=()=>this.modelId,d=()=>this.models.find(l=>l.id===this.modelId)?.name;this.chat=new S(this.http,r,s,a,!0,void 0,()=>this.settingsSheet?.getSettings()??null,d),this.characters=new E(this.http,s,!0,n?.characters,n?.characterStates),this.relationships=new R(this.http,s,!0,n?.relationships),this.inventory=new T(this.http,s,!0,n?.inventory),this.world=new k(this.http,s,!0,n?.world),this.player=new P(this.http,s,!0,n?.player,n?.playerState),this.custom=new M(this.http,s,!0,n?.custom),this.initialized=!0}};async function ee(o){let e=new _;return o?.dev?await e.initDev(o.dev):await e.init(),e}function z(o){return typeof o=="object"&&o!==null&&"value"in o&&"type"in o&&(o.type==="number"||o.type==="text")}function te(o){return z(o)?o.value:o}return ae(Ee);})();
770
770
  if(typeof window!=="undefined"){window.createStorviaSDK=StorviaSDK.createStorviaSDK;}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storvia/sdk",
3
- "version": "0.5.1",
3
+ "version": "0.5.2",
4
4
  "description": "Storvia World SDK - Build interactive text games on the Storvia platform",
5
5
  "main": "dist/index.cjs.js",
6
6
  "module": "dist/index.esm.js",