@storvia/sdk 0.1.5 → 0.1.7
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 +4 -4
- package/dist/index.d.mts +44 -8
- package/dist/index.esm.js +4 -4
- package/dist/index.umd.js +4 -4
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`);for(let P of I){if(!P.startsWith("data: "))continue;let
|
|
1
|
+
"use strict";var R=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var A=Object.prototype.hasOwnProperty;var B=(a,e)=>{for(var t in e)R(a,t,{get:e[t],enumerable:!0})},U=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of H(e))!A.call(a,i)&&i!==t&&R(a,i,{get:()=>e[i],enumerable:!(n=D(e,i))||n.enumerable});return a};var F=a=>U(R({},"__esModule",{value:!0}),a);var Q={};B(Q,{StorviaError:()=>c,StorviaSDK:()=>S,createStorviaSDK:()=>O,extractFieldValue:()=>L,isRichFieldValue:()=>_});module.exports=F(Q);var c=class extends Error{constructor(e,t){super(t),this.name="StorviaError",this.code=e}};var E=class{constructor(e,t,n=!1,i=""){this.baseUrl=e,this.token=t,this.debug=n,this.devApiKey=i}setToken(e){this.token=e}setDebug(e){this.debug=e}buildHeaders(){let e={"Content-Type":"application/json"};return this.token&&(e.Authorization=`Bearer ${this.token}`),this.devApiKey&&(e["x-api-key"]=this.devApiKey),e}log(e,t,n,i,s){if(!this.debug)return;let r="%c[Storvia SDK]",o="color: #6366f1; font-weight: bold";s?(console.groupCollapsed(`${r} %c${e} ${t} %c\u2717`,o,"color: #e0e0e0","color: #ef4444"),n&&console.log("Request:",n),console.error("Error:",s),console.groupEnd()):(console.groupCollapsed(`${r} %c${e} ${t} %c\u2713`,o,"color: #e0e0e0","color: #22c55e"),n&&console.log("Request:",n),i!==void 0&&console.log("Response:",i),console.groupEnd())}async get(e,t){let n=new URL(`${this.baseUrl}${e}`);t&&Object.entries(t).forEach(([i,s])=>n.searchParams.set(i,s));try{let i=await fetch(n.toString(),{method:"GET",headers:this.buildHeaders()}),s=await this.handleResponse(i);return this.log("GET",e,t,s),s}catch(i){throw this.log("GET",e,t,void 0,i),i}}async post(e,t){try{let n=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0}),i=await this.handleResponse(n);return this.log("POST",e,t,i),i}catch(n){throw this.log("POST",e,t,void 0,n),n}}async patch(e,t){try{let n=await fetch(`${this.baseUrl}${e}`,{method:"PATCH",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0}),i=await this.handleResponse(n);return this.log("PATCH",e,t,i),i}catch(n){throw this.log("PATCH",e,t,void 0,n),n}}async delete(e){try{let t=await fetch(`${this.baseUrl}${e}`,{method:"DELETE",headers:this.buildHeaders()}),n=await this.handleResponse(t);return this.log("DELETE",e,void 0,n),n}catch(t){throw this.log("DELETE",e,void 0,void 0,t),t}}async stream(e,t,n,i){this.log("STREAM",e,t);let s=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify(t)});if(!s.ok){let d=await s.json().catch(()=>({})),m=new c(d.code||"INTERNAL_ERROR",d.message||`HTTP ${s.status}`);throw this.log("STREAM",e,t,void 0,m),m}let r=s.body?.getReader();if(!r)throw new c("INTERNAL_ERROR","No response body for stream");let o=new TextDecoder,l="",h="";for(;;){let{done:d,value:m}=await r.read();if(d)break;let I=o.decode(m,{stream:!0}).split(`
|
|
2
|
+
`);for(let P of I){if(!P.startsWith("data: "))continue;let N=P.slice(6);if(N==="[DONE]"){this.debug&&this.log("STREAM",e+" [done]",void 0,{id:l,contentLength:h.length}),i(l);return}try{let g=JSON.parse(N);g.type==="done"&&g.id?l=g.id:g.content&&(h+=g.content,n(g.content))}catch{}}}l&&i(l)}async handleResponse(e){if(!e.ok){let n={};try{n=await e.json()}catch{}let i={401:"UNAUTHORIZED",402:"INSUFFICIENT_BALANCE",404:"GAME_NOT_FOUND",429:"RATE_LIMITED"},s=n.code||i[e.status]||"INTERNAL_ERROR";throw new c(s,n.message||`HTTP ${e.status}`)}let t=await e.json();return t&&typeof t=="object"&&"data"in t?t.data:t}};var j=[{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"}],M=[{value:"low",label:"\u7B80\u77ED"},{value:"medium",label:"\u9002\u4E2D"},{value:"high",label:"\u8BE6\u7EC6"}],V=`
|
|
3
3
|
:host {
|
|
4
4
|
position: fixed;
|
|
5
5
|
bottom: 20px;
|
|
@@ -427,5 +427,5 @@
|
|
|
427
427
|
to { transform: rotate(360deg); }
|
|
428
428
|
}
|
|
429
429
|
.spin { animation: spin 0.8s linear infinite; }
|
|
430
|
-
`,z='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>',G='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>',F='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',V='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',W='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>',u=class{constructor(e){this.selectedModelId="";this.models=[];this.modelPanel=null;this.settings={temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.hasWorldUpdate=!1;this.fabDot=null;this.syncHint=null;this.displayMode="phone";this.displayModeBtns=[];this.tempValueEl=null;this.tempSlider=null;this.segmentBtns=[];this.langSelect=null;this.noteInput=null;this.noteCounter=null;this.saveBtn=null;this.syncBtn=null;this.syncState="idle";this.panel=null;this.callbacks=e,this.host=document.createElement("div"),this.host.id="storvia-settings",this.shadowRoot=this.host.attachShadow({mode:"closed"})}mount(e,t,n,i=!1){this.models=e,this.selectedModelId=t,this.settings={...n},this.hasWorldUpdate=i;try{let s=localStorage.getItem("storvia_display_mode");(s==="phone"||s==="desktop")&&(this.displayMode=s)}catch{}document.body.appendChild(this.host),this.render()}unmount(){this.host.remove()}getSelectedModelId(){return this.selectedModelId}getSettings(){return{...this.settings}}render(){let e=document.createElement("style");e.textContent=j;let t=document.createElement("div"),n=document.createElement("div");n.className="fab-wrap";let i=document.createElement("button");i.className="fab",i.innerHTML=z,i.title="\u6E38\u620F\u8BBE\u7F6E";let s=document.createElement("div");s.className=`fab-dot${this.hasWorldUpdate?" visible":""}`,this.fabDot=s,n.appendChild(i),n.appendChild(s);let a=document.createElement("div");a.className="panel",this.panel=a;let o=document.createElement("div");o.className="panel-header";let l=document.createElement("div");l.className="panel-title",l.textContent="\u6E38\u620F\u8BBE\u7F6E";let h=document.createElement("button");h.className="close-btn",h.innerHTML="\u2715",h.addEventListener("click",()=>a.classList.remove("open")),o.appendChild(l),o.appendChild(h),a.appendChild(o);let r=document.createElement("div");r.className="panel-body",this.models.length>0&&(r.appendChild(this.buildModelSection()),r.appendChild(this.makeDivider())),r.appendChild(this.buildTemperatureSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildReplyLengthSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildReplyLanguageSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildNoteSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildDisplayModeSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildSyncSection());let m=document.createElement("div");m.className="save-row";let p=document.createElement("button");p.className="save-btn",p.textContent="\u4FDD\u5B58",this.saveBtn=p,p.addEventListener("click",()=>this.handleSave()),m.appendChild(p),r.appendChild(m),a.appendChild(r),i.addEventListener("click",()=>a.classList.toggle("open")),document.addEventListener("click",I=>{this.host.contains(I.target)||a.classList.remove("open")}),t.appendChild(a),t.appendChild(n),this.shadowRoot.appendChild(e),this.shadowRoot.appendChild(t)}buildModelSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="AI \u6A21\u578B",e.appendChild(t);let n=document.createElement("div");return n.className="model-list",this.modelPanel=n,this.models.forEach(i=>{let s=document.createElement("button");s.className=`model-option${i.id===this.selectedModelId?" active":""}`,s.innerHTML=`<span class="dot"></span><span>${i.name}</span>`,s.addEventListener("click",()=>{this.selectedModelId=i.id,this.callbacks.onModelChange(i.id);try{localStorage.setItem("storvia_model_id",i.id)}catch{}this.updateModelActive()}),n.appendChild(s)}),e.appendChild(n),e}buildTemperatureSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label";let n=document.createElement("span");n.textContent="\u6E29\u5EA6";let i=document.createElement("span");i.className="value",i.textContent=this.settings.temperature.toFixed(1),this.tempValueEl=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("div");s.className="section-desc",s.textContent="\u66F4\u4F4E\u7684\u6E29\u5EA6\u4F1A\u8BA9 AI \u56DE\u590D\u66F4\u7A33\u5B9A\u3001\u7406\u667A\uFF1B\u66F4\u9AD8\u7684\u6E29\u5EA6\u4F1A\u8BA9 AI \u7684\u56DE\u590D\u66F4\u5177\u591A\u6837\u6027\u548C\u968F\u673A\u6027",e.appendChild(s);let a=document.createElement("div");a.className="slider-wrap";let o=document.createElement("input");o.type="range",o.className="slider",o.min="0",o.max="2",o.step="0.1",o.value=String(this.settings.temperature),this.tempSlider=o,o.addEventListener("input",()=>{let h=parseFloat(o.value);this.settings.temperature=h,this.tempValueEl&&(this.tempValueEl.textContent=h.toFixed(1))}),a.appendChild(o);let l=document.createElement("div");return l.className="slider-labels",l.innerHTML="<span>\u7CBE\u786E</span><span>\u521B\u610F</span>",a.appendChild(l),e.appendChild(a),e}buildReplyLengthSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u56DE\u590D\u957F\u5EA6",e.appendChild(t);let n=document.createElement("div");return n.className="segment",this.segmentBtns=[],M.forEach(i=>{let s=document.createElement("button");s.className=`segment-btn${i.value===this.settings.reply_length?" active":""}`,s.textContent=i.label,s.addEventListener("click",()=>{this.settings.reply_length=i.value,this.segmentBtns.forEach((a,o)=>{a.classList.toggle("active",M[o].value===i.value)})}),this.segmentBtns.push(s),n.appendChild(s)}),e.appendChild(n),e}buildReplyLanguageSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u56DE\u590D\u8BED\u8A00",e.appendChild(t);let n=document.createElement("div");n.className="select-wrap";let i=document.createElement("select");i.className="select",this.langSelect=i,U.forEach(a=>{let o=document.createElement("option");o.value=a.value,o.textContent=a.label,a.value===this.settings.reply_language&&(o.selected=!0),i.appendChild(o)}),i.addEventListener("change",()=>{this.settings.reply_language=i.value});let s=document.createElement("span");return s.className="select-arrow",s.textContent="\u25BE",n.appendChild(i),n.appendChild(s),e.appendChild(n),e}buildNoteSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label";let n=document.createElement("span");n.textContent="\u5907\u6CE8";let i=document.createElement("span");i.textContent=`${this.settings.player_note.length}/50`,this.noteCounter=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("div");s.className="section-desc",s.textContent="\u5199\u4E0B\u4F60\u5BF9\u8FD9\u4E2A\u6E38\u620F\u7684\u5907\u6CE8\uFF0C\u4F1A\u663E\u793A\u5728\u5B58\u6863\u5217\u8868",e.appendChild(s);let a=document.createElement("div");a.className="note-wrap";let o=document.createElement("textarea");return o.className="note-input",o.placeholder="\u5907\u6CE8",o.maxLength=50,o.value=this.settings.player_note,this.noteInput=o,o.addEventListener("input",()=>{this.settings.player_note=o.value,this.noteCounter&&(this.noteCounter.textContent=`${o.value.length}/50`)}),a.appendChild(o),e.appendChild(a),e}buildDisplayModeSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u663E\u793A\u6A21\u5F0F",e.appendChild(t);let n=document.createElement("div");n.className="section-desc",n.textContent="\u7535\u8111\u6A21\u5F0F\u4F1A\u81EA\u52A8\u6A2A\u5C4F\u663E\u793A",e.appendChild(n);let i=document.createElement("div");i.className="segment",this.displayModeBtns=[];let s=[{value:"phone",label:"\u624B\u673A"},{value:"desktop",label:"\u7535\u8111"}];return s.forEach(a=>{let o=document.createElement("button");o.className=`segment-btn${a.value===this.displayMode?" active":""}`,o.textContent=a.label,o.addEventListener("click",()=>{this.displayMode=a.value;try{localStorage.setItem("storvia_display_mode",a.value)}catch{}this.displayModeBtns.forEach((l,h)=>{l.classList.toggle("active",s[h].value===a.value)});try{window.parent.postMessage({type:"storvia-orientation",mode:a.value==="desktop"?"landscape":"portrait"},"*")}catch{}}),this.displayModeBtns.push(o),i.appendChild(o)}),e.appendChild(i),e}buildSyncSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u540C\u6B65\u6E38\u620F\u8BBE\u5B9A",e.appendChild(t);let n=document.createElement("div");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("div");i.className="sync-desc",i.textContent="\u5982\u679C\u6E38\u620F\u4F5C\u8005\u66F4\u65B0\u4E86\u5185\u5BB9\uFF0C\u70B9\u51FB\u6B64\u6309\u94AE\u53EF\u5C06\u6700\u65B0\u7684\u6E38\u620F\u8BBE\u5B9A\u548C\u5F00\u5E55\u5C0F\u5267\u573A\u540C\u6B65\u5230\u5F53\u524D\u5BF9\u8BDD",e.appendChild(i);let s=document.createElement("button");return s.className="sync-btn",this.syncBtn=s,this.renderSyncBtn(),s.addEventListener("click",async()=>{if(this.syncState!=="loading"){this.setSyncState("loading");try{await this.callbacks.onSync(),this.setSyncState("success"),this.hasWorldUpdate=!1,this.fabDot&&this.fabDot.classList.remove("visible"),this.syncHint&&this.syncHint.classList.remove("visible"),setTimeout(()=>this.setSyncState("idle"),3e3)}catch{this.setSyncState("error"),setTimeout(()=>this.setSyncState("idle"),4e3)}}}),e.appendChild(s),e}makeDivider(){let e=document.createElement("div");return e.className="divider",e}updateModelActive(){this.modelPanel&&this.modelPanel.querySelectorAll(".model-option").forEach((e,t)=>{e.classList.toggle("active",this.models[t].id===this.selectedModelId)})}setSyncState(e){this.syncState=e,this.renderSyncBtn()}renderSyncBtn(){if(!this.syncBtn)return;let e=this.syncState,t={idle:G,loading:F,success:V,error:W},n={idle:"\u540C\u6B65\u6700\u65B0\u8BBE\u5B9A",loading:"\u540C\u6B65\u4E2D...",success:"\u5DF2\u540C\u6B65",error:"\u540C\u6B65\u5931\u8D25"};this.syncBtn.className=`sync-btn${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.textContent="\u4FDD\u5B58\u4E2D...";try{await this.callbacks.onSettingsChange({temperature:this.settings.temperature,reply_length:this.settings.reply_length,reply_language:this.settings.reply_language,player_note:this.settings.player_note}),this.saveBtn.textContent="\u5DF2\u4FDD\u5B58",this.saveBtn.classList.add("saved"),setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.classList.remove("saved"),this.saveBtn.disabled=!1)},2e3)}catch{this.saveBtn.textContent="\u4FDD\u5B58\u5931\u8D25",setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1)},2e3)}}}};var v=class{constructor(e,t,n,i,s=!1,a){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=i;this.isPreview=s;this.previewConfig=a}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_context:e.context,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/chat",t)}async save(e){return this.isPreview?{id:`preview-${Date.now()}`}:this.http.post("/messages/save",{conversation_id:this.getConversationId(),role:e.role,content:e.content,topic:e.topic})}async generate(e){if(this.isPreview)return this.sendPreview({message:"",topic:e.topic,context:(e.context||"")+`
|
|
431
|
-
[\u6307\u4EE4] \u8BF7\u76F4\u63A5\u751F\u6210\u56DE\u590D\uFF0C\u65E0\u9700\u7528\u6237\u8F93\u5165`,stream:e.stream,onChunk:e.onChunk,onDone:e.onDone});let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,scene_context:e.context,stream:e.stream??!1,save:e.save??!0};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/generate",t)}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,context:e.context,prompt_config:this.previewConfig||{},history_messages:[]};if(e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}let n="";return await this.http.stream("/preview",t,i=>{n+=i},()=>{}),{id:"",content:n}}};var R=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){return this.isPreview?{...this.mem[e]||{}}:this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,t)}},f=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];this.state=new R(e,t,n)}async list(){return this.isPreview?this.mem.map(e=>({name:e.name,avatar:e.avatar})):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:t?.name||e,avatar:t?.avatar}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async add(e){if(this.isPreview){this.mem.push(e);return}await this.http.post(`/conversations/${this.getConversationId()}/characters`,e)}async update(e,t){if(this.isPreview){let n=this.mem.find(i=>i.name===e);n&&Object.assign(n,t);return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`,t)}async remove(e){if(this.isPreview){this.mem=this.mem.filter(t=>t.name!==e);return}await this.http.delete(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async detail(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:e,avatar:t?.avatar,state:await this.state.get(e)}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/detail`)}};var w=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(){return this.isPreview?[...this.mem]:this.http.get(`/conversations/${this.getConversationId()}/relationships`)}async get(e,t){if(this.isPreview){let n=this.mem.find(i=>i.from===e&&i.to===t);if(n)return{...n};throw new Error("Relationship not found")}return this.http.get(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/relationships`,e)}async update(e,t,n){if(this.isPreview){let i=this.mem.find(s=>s.from===e&&s.to===t);i?Object.assign(i,n):this.mem.push({from:e,to:t,...n});return}await this.http.patch(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,n)}async remove(e,t){if(this.isPreview){this.mem=this.mem.filter(n=>!(n.from===e&&n.to===t));return}await this.http.delete(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var b=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(e){if(this.isPreview)return e?this.mem.filter(n=>n.group===e):[...this.mem];let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/inventory`,t)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/inventory`,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()}/inventory/${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()}/inventory/${encodeURIComponent(e)}`)}};var y=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(){return this.isPreview?{...this.mem}:this.http.get(`/conversations/${this.getConversationId()}/world`)}async update(e){if(this.isPreview){Object.assign(this.mem,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/world`,e)}};var T=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e?{...this.mem[e]||{}}:{...this.mem};let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/player/state`,t)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/player/state`,{group:e,values:t})}},C=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};this.state=new T(e,t,n)}async get(){return this.isPreview?{...this.memPersona}:this.http.get(`/conversations/${this.getConversationId()}/player`)}};var x=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e!==void 0?this.mem[e]:{...this.mem};let t=await this.http.get(`/conversations/${this.getConversationId()}/custom`);return e!==void 0?t[e]:t}async set(e){if(this.isPreview){for(let[t,n]of Object.entries(e))typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof this.mem[t]=="object"&&this.mem[t]!==null?this.mem[t]={...this.mem[t],...n}:this.mem[t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom`,e)}async delete(e){if(this.isPreview){delete this.mem[e];return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}`)}async setGroupField(e,t,n){if(this.isPreview){(!this.mem[e]||typeof this.mem[e]!="object")&&(this.mem[e]={}),this.mem[e][t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{value:n})}async deleteGroupField(e,t){if(this.isPreview){if(typeof this.mem[e]=="object"&&this.mem[e]!==null){let n=this.mem[e];delete n[t],Object.keys(n).length===0&&delete this.mem[e]}return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var N="/functions/v1/world-engine/v1",J="https://api.storvia.ai";function Y(){return window.__STORVIA__||{}}function Z(d=5e3){let e=Y();return e.apiBase?Promise.resolve(e):new Promise((t,n)=>{let i=setTimeout(()=>{window.removeEventListener("message",s),n(new c("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},d);function s(a){let o=null;if(a.data?.type==="storvia-init"&&a.data.apiBase?o={apiBase:a.data.apiBase,gameId:a.data.gameId,accessToken:a.data.accessToken}:a.data?.type==="storvia-preview-init"&&a.data.config&&(o=a.data.config),o&&o.apiBase){clearTimeout(i),window.removeEventListener("message",s);let l=window;l.__STORVIA__=o,t(o)}}window.addEventListener("message",s)})}var E=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){if(this.initialized)return;let e=await Z(),t=e.apiBase;if(!t)throw new c("NOT_INITIALIZED","window.__STORVIA__.apiBase is not set. The platform must inject it before SDK init.");if(this.baseUrl=`${t}${N}`,this.isPreview=!!e.preview,this.previewConfig=e.previewConfig,!e.gameId)throw new c("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 c("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 S(this.baseUrl,this.accessToken,!!e.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let r=await this.fetchModels();this.modelId=e.selectedModelId||r[0]?.id||"",this.settingsSheet=new u({onModelChange:P=>{this.modelId=P},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),r.length>0&&this.settingsSheet.mount(r,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let m=()=>this.gameId,p=()=>this.conversationId,I=()=>this.modelId;this.chat=new v(this.http,m,p,I,!0,this.previewConfig),this.characters=new f(this.http,p,!0),this.relationships=new w(this.http,p,!0),this.inventory=new b(this.http,p,!0),this.world=new y(this.http,p,!0),this.player=new C(this.http,p,!0),this.custom=new x(this.http,p,!0),this.initialized=!0,this.listenForPreviewMessages();return}let[n,i]=await Promise.all([this.authenticate(),this.fetchModels()]);this.conversationId=n.conversationId;let s=this.getSavedModelId();this.modelId=s&&i.some(r=>r.id===s)?s:i[0]?.id||"";let a=n.settings||{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.settingsSheet=new u({onModelChange:r=>{this.modelId=r},onSettingsChange:r=>this.saveSettings(r),onSync:()=>this.syncSettings()}),this.settingsSheet.mount(i,this.modelId,a,n.hasWorldUpdate??!1);let o=()=>this.gameId,l=()=>this.conversationId,h=()=>this.modelId;this.chat=new v(this.http,o,l,h),this.characters=new f(this.http,l),this.relationships=new w(this.http,l),this.inventory=new b(this.http,l),this.world=new y(this.http,l),this.player=new C(this.http,l),this.custom=new x(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)))})}async saveSettings(e){await this.http.patch("/settings",{conversation_id:this.conversationId,...e})}async syncSettings(){await this.http.post("/sync",{conversation_id:this.conversationId})}async fetchModels(){try{return await this.http.get("/models")}catch{}return[]}async authenticate(){let e=await fetch(`${this.baseUrl}/auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.accessToken}`},body:JSON.stringify({game_id:this.gameId})});if(!e.ok)throw e.status===401?new c("UNAUTHORIZED","User not authenticated"):e.status===404?new c("GAME_NOT_FOUND","Game not found or not published"):new c("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=`${J}${N}`,this.gameId=e.gameId,this.isPreview=!0,this.http=new S(this.baseUrl,"",!1,e.apiKey);let t=await this.fetchModels();this.modelId=t[0]?.id||"",this.conversationId="00000000-0000-0000-0000-000000000000",this.settingsSheet=new u({onModelChange:a=>{this.modelId=a},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),t.length>0&&this.settingsSheet.mount(t,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let n=()=>this.gameId,i=()=>this.conversationId,s=()=>this.modelId;this.chat=new v(this.http,n,i,s,!0,void 0),this.characters=new f(this.http,i,!0),this.relationships=new w(this.http,i,!0),this.inventory=new b(this.http,i,!0),this.world=new y(this.http,i,!0),this.player=new C(this.http,i,!0),this.custom=new x(this.http,i,!0),this.initialized=!0}};async function $(d){let e=new E;return d?.dev?await e.initDev(d.dev):await e.init(),e}0&&(module.exports={StorviaError,StorviaSDK,createStorviaSDK});
|
|
430
|
+
`,z='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>',G='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>',W='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',Z='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',J='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>',u=class{constructor(e){this.selectedModelId="";this.models=[];this.modelPanel=null;this.settings={temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.hasWorldUpdate=!1;this.fabDot=null;this.syncHint=null;this.displayMode="phone";this.displayModeBtns=[];this.tempValueEl=null;this.tempSlider=null;this.segmentBtns=[];this.langSelect=null;this.noteInput=null;this.noteCounter=null;this.saveBtn=null;this.syncBtn=null;this.syncState="idle";this.panel=null;this.callbacks=e,this.host=document.createElement("div"),this.host.id="storvia-settings",this.shadowRoot=this.host.attachShadow({mode:"closed"})}mount(e,t,n,i=!1){this.models=e,this.selectedModelId=t,this.settings={...n},this.hasWorldUpdate=i;try{let s=localStorage.getItem("storvia_display_mode");(s==="phone"||s==="desktop")&&(this.displayMode=s)}catch{}document.body.appendChild(this.host),this.render()}unmount(){this.host.remove()}getSelectedModelId(){return this.selectedModelId}getSettings(){return{...this.settings}}render(){let e=document.createElement("style");e.textContent=V;let t=document.createElement("div"),n=document.createElement("div");n.className="fab-wrap";let i=document.createElement("button");i.className="fab",i.innerHTML=z,i.title="\u6E38\u620F\u8BBE\u7F6E";let s=document.createElement("div");s.className=`fab-dot${this.hasWorldUpdate?" visible":""}`,this.fabDot=s,n.appendChild(i),n.appendChild(s);let r=document.createElement("div");r.className="panel",this.panel=r;let o=document.createElement("div");o.className="panel-header";let l=document.createElement("div");l.className="panel-title",l.textContent="\u6E38\u620F\u8BBE\u7F6E";let h=document.createElement("button");h.className="close-btn",h.innerHTML="\u2715",h.addEventListener("click",()=>r.classList.remove("open")),o.appendChild(l),o.appendChild(h),r.appendChild(o);let d=document.createElement("div");d.className="panel-body",this.models.length>0&&(d.appendChild(this.buildModelSection()),d.appendChild(this.makeDivider())),d.appendChild(this.buildTemperatureSection()),d.appendChild(this.makeDivider()),d.appendChild(this.buildReplyLengthSection()),d.appendChild(this.makeDivider()),d.appendChild(this.buildReplyLanguageSection()),d.appendChild(this.makeDivider()),d.appendChild(this.buildNoteSection()),d.appendChild(this.makeDivider()),d.appendChild(this.buildDisplayModeSection()),d.appendChild(this.makeDivider()),d.appendChild(this.buildSyncSection());let m=document.createElement("div");m.className="save-row";let p=document.createElement("button");p.className="save-btn",p.textContent="\u4FDD\u5B58",this.saveBtn=p,p.addEventListener("click",()=>this.handleSave()),m.appendChild(p),d.appendChild(m),r.appendChild(d),i.addEventListener("click",()=>r.classList.toggle("open")),document.addEventListener("click",I=>{this.host.contains(I.target)||r.classList.remove("open")}),t.appendChild(r),t.appendChild(n),this.shadowRoot.appendChild(e),this.shadowRoot.appendChild(t)}buildModelSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="AI \u6A21\u578B",e.appendChild(t);let n=document.createElement("div");return n.className="model-list",this.modelPanel=n,this.models.forEach(i=>{let s=document.createElement("button");s.className=`model-option${i.id===this.selectedModelId?" active":""}`,s.innerHTML=`<span class="dot"></span><span>${i.name}</span>`,s.addEventListener("click",()=>{this.selectedModelId=i.id,this.callbacks.onModelChange(i.id);try{localStorage.setItem("storvia_model_id",i.id)}catch{}this.updateModelActive()}),n.appendChild(s)}),e.appendChild(n),e}buildTemperatureSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label";let n=document.createElement("span");n.textContent="\u6E29\u5EA6";let i=document.createElement("span");i.className="value",i.textContent=this.settings.temperature.toFixed(1),this.tempValueEl=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("div");s.className="section-desc",s.textContent="\u66F4\u4F4E\u7684\u6E29\u5EA6\u4F1A\u8BA9 AI \u56DE\u590D\u66F4\u7A33\u5B9A\u3001\u7406\u667A\uFF1B\u66F4\u9AD8\u7684\u6E29\u5EA6\u4F1A\u8BA9 AI \u7684\u56DE\u590D\u66F4\u5177\u591A\u6837\u6027\u548C\u968F\u673A\u6027",e.appendChild(s);let r=document.createElement("div");r.className="slider-wrap";let o=document.createElement("input");o.type="range",o.className="slider",o.min="0",o.max="2",o.step="0.1",o.value=String(this.settings.temperature),this.tempSlider=o,o.addEventListener("input",()=>{let h=parseFloat(o.value);this.settings.temperature=h,this.tempValueEl&&(this.tempValueEl.textContent=h.toFixed(1))}),r.appendChild(o);let l=document.createElement("div");return l.className="slider-labels",l.innerHTML="<span>\u7CBE\u786E</span><span>\u521B\u610F</span>",r.appendChild(l),e.appendChild(r),e}buildReplyLengthSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u56DE\u590D\u957F\u5EA6",e.appendChild(t);let n=document.createElement("div");return n.className="segment",this.segmentBtns=[],M.forEach(i=>{let s=document.createElement("button");s.className=`segment-btn${i.value===this.settings.reply_length?" active":""}`,s.textContent=i.label,s.addEventListener("click",()=>{this.settings.reply_length=i.value,this.segmentBtns.forEach((r,o)=>{r.classList.toggle("active",M[o].value===i.value)})}),this.segmentBtns.push(s),n.appendChild(s)}),e.appendChild(n),e}buildReplyLanguageSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u56DE\u590D\u8BED\u8A00",e.appendChild(t);let n=document.createElement("div");n.className="select-wrap";let i=document.createElement("select");i.className="select",this.langSelect=i,j.forEach(r=>{let o=document.createElement("option");o.value=r.value,o.textContent=r.label,r.value===this.settings.reply_language&&(o.selected=!0),i.appendChild(o)}),i.addEventListener("change",()=>{this.settings.reply_language=i.value});let s=document.createElement("span");return s.className="select-arrow",s.textContent="\u25BE",n.appendChild(i),n.appendChild(s),e.appendChild(n),e}buildNoteSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label";let n=document.createElement("span");n.textContent="\u5907\u6CE8";let i=document.createElement("span");i.textContent=`${this.settings.player_note.length}/50`,this.noteCounter=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("div");s.className="section-desc",s.textContent="\u5199\u4E0B\u4F60\u5BF9\u8FD9\u4E2A\u6E38\u620F\u7684\u5907\u6CE8\uFF0C\u4F1A\u663E\u793A\u5728\u5B58\u6863\u5217\u8868",e.appendChild(s);let r=document.createElement("div");r.className="note-wrap";let o=document.createElement("textarea");return o.className="note-input",o.placeholder="\u5907\u6CE8",o.maxLength=50,o.value=this.settings.player_note,this.noteInput=o,o.addEventListener("input",()=>{this.settings.player_note=o.value,this.noteCounter&&(this.noteCounter.textContent=`${o.value.length}/50`)}),r.appendChild(o),e.appendChild(r),e}buildDisplayModeSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u663E\u793A\u6A21\u5F0F",e.appendChild(t);let n=document.createElement("div");n.className="section-desc",n.textContent="\u7535\u8111\u6A21\u5F0F\u4F1A\u81EA\u52A8\u6A2A\u5C4F\u663E\u793A",e.appendChild(n);let i=document.createElement("div");i.className="segment",this.displayModeBtns=[];let s=[{value:"phone",label:"\u624B\u673A"},{value:"desktop",label:"\u7535\u8111"}];return s.forEach(r=>{let o=document.createElement("button");o.className=`segment-btn${r.value===this.displayMode?" active":""}`,o.textContent=r.label,o.addEventListener("click",()=>{this.displayMode=r.value;try{localStorage.setItem("storvia_display_mode",r.value)}catch{}this.displayModeBtns.forEach((l,h)=>{l.classList.toggle("active",s[h].value===r.value)});try{window.parent.postMessage({type:"storvia-orientation",mode:r.value==="desktop"?"landscape":"portrait"},"*")}catch{}}),this.displayModeBtns.push(o),i.appendChild(o)}),e.appendChild(i),e}buildSyncSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u540C\u6B65\u6E38\u620F\u8BBE\u5B9A",e.appendChild(t);let n=document.createElement("div");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("div");i.className="sync-desc",i.textContent="\u5982\u679C\u6E38\u620F\u4F5C\u8005\u66F4\u65B0\u4E86\u5185\u5BB9\uFF0C\u70B9\u51FB\u6B64\u6309\u94AE\u53EF\u5C06\u6700\u65B0\u7684\u6E38\u620F\u8BBE\u5B9A\u548C\u5F00\u5E55\u5C0F\u5267\u573A\u540C\u6B65\u5230\u5F53\u524D\u5BF9\u8BDD",e.appendChild(i);let s=document.createElement("button");return s.className="sync-btn",this.syncBtn=s,this.renderSyncBtn(),s.addEventListener("click",async()=>{if(this.syncState!=="loading"){this.setSyncState("loading");try{await this.callbacks.onSync(),this.setSyncState("success"),this.hasWorldUpdate=!1,this.fabDot&&this.fabDot.classList.remove("visible"),this.syncHint&&this.syncHint.classList.remove("visible"),setTimeout(()=>this.setSyncState("idle"),3e3)}catch{this.setSyncState("error"),setTimeout(()=>this.setSyncState("idle"),4e3)}}}),e.appendChild(s),e}makeDivider(){let e=document.createElement("div");return e.className="divider",e}updateModelActive(){this.modelPanel&&this.modelPanel.querySelectorAll(".model-option").forEach((e,t)=>{e.classList.toggle("active",this.models[t].id===this.selectedModelId)})}setSyncState(e){this.syncState=e,this.renderSyncBtn()}renderSyncBtn(){if(!this.syncBtn)return;let e=this.syncState,t={idle:G,loading:W,success:Z,error:J},n={idle:"\u540C\u6B65\u6700\u65B0\u8BBE\u5B9A",loading:"\u540C\u6B65\u4E2D...",success:"\u5DF2\u540C\u6B65",error:"\u540C\u6B65\u5931\u8D25"};this.syncBtn.className=`sync-btn${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.textContent="\u4FDD\u5B58\u4E2D...";try{await this.callbacks.onSettingsChange({temperature:this.settings.temperature,reply_length:this.settings.reply_length,reply_language:this.settings.reply_language,player_note:this.settings.player_note}),this.saveBtn.textContent="\u5DF2\u4FDD\u5B58",this.saveBtn.classList.add("saved"),setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.classList.remove("saved"),this.saveBtn.disabled=!1)},2e3)}catch{this.saveBtn.textContent="\u4FDD\u5B58\u5931\u8D25",setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1)},2e3)}}}};var v=class{constructor(e,t,n,i,s=!1,r){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=i;this.isPreview=s;this.previewConfig=r}updatePreviewConfig(e){this.previewConfig=e}async send(e){if(this.isPreview)return this.sendPreview(e);let t={game_id:this.getGameId(),conversation_id:this.getConversationId(),model_id:this.getModelId(),message:e.message,topic:e.topic,scene_context:e.context,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/chat",t)}async save(e){return this.isPreview?{id:`preview-${Date.now()}`}:this.http.post("/messages/save",{conversation_id:this.getConversationId(),role:e.role,content:e.content,topic:e.topic})}async generate(e){if(this.isPreview)return this.sendPreview({message:"",topic:e.topic,context:(e.context||"")+`
|
|
431
|
+
[\u6307\u4EE4] \u8BF7\u76F4\u63A5\u751F\u6210\u56DE\u590D\uFF0C\u65E0\u9700\u7528\u6237\u8F93\u5165`,stream:e.stream,onChunk:e.onChunk,onDone:e.onDone});let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,scene_context:e.context,stream:e.stream??!1,save:e.save??!0};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/generate",t)}async retry(e={}){if(this.isPreview)throw new Error("Retry is not supported in preview mode");let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,scene_context:e.context,stream:e.stream??!1};if(e.stream){await this.http.stream("/retry",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/retry",t)}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,context:e.context,prompt_config:this.previewConfig||{},history_messages:[]};if(e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}let n="";return await this.http.stream("/preview",t,i=>{n+=i},()=>{}),{id:"",content:n}}};var k=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){return this.isPreview?{...this.mem[e]||{}}:this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,t)}},f=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];this.state=new k(e,t,n)}async list(){return this.isPreview?this.mem.map(e=>({name:e.name,avatar:e.avatar})):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:t?.name||e,avatar:t?.avatar}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async add(e){if(this.isPreview){this.mem.push(e);return}await this.http.post(`/conversations/${this.getConversationId()}/characters`,e)}async update(e,t){if(this.isPreview){let n=this.mem.find(i=>i.name===e);n&&Object.assign(n,t);return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`,t)}async remove(e){if(this.isPreview){this.mem=this.mem.filter(t=>t.name!==e);return}await this.http.delete(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async detail(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:e,avatar:t?.avatar,state:await this.state.get(e)}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/detail`)}};var b=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(){return this.isPreview?[...this.mem]:this.http.get(`/conversations/${this.getConversationId()}/relationships`)}async get(e,t){if(this.isPreview){let n=this.mem.find(i=>i.from===e&&i.to===t);if(n)return{...n};throw new Error("Relationship not found")}return this.http.get(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/relationships`,e)}async update(e,t,n){if(this.isPreview){let i=this.mem.find(s=>s.from===e&&s.to===t);i?Object.assign(i,n):this.mem.push({from:e,to:t,...n});return}await this.http.patch(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,n)}async remove(e,t){if(this.isPreview){this.mem=this.mem.filter(n=>!(n.from===e&&n.to===t));return}await this.http.delete(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var w=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(e){if(this.isPreview)return e?this.mem.filter(n=>n.group===e):[...this.mem];let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/inventory`,t)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/inventory`,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()}/inventory/${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()}/inventory/${encodeURIComponent(e)}`)}};var y=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(){return this.isPreview?{...this.mem}:this.http.get(`/conversations/${this.getConversationId()}/world`)}async update(e){if(this.isPreview){Object.assign(this.mem,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/world`,e)}};var T=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e?{...this.mem[e]||{}}:{...this.mem};let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/player/state`,t)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/player/state`,{group:e,values:t})}},C=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};this.state=new T(e,t,n)}async get(){return this.isPreview?{...this.memPersona}:this.http.get(`/conversations/${this.getConversationId()}/player`)}async update(e){if(this.isPreview){Object.assign(this.memPersona,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/player`,e)}};var x=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e!==void 0?this.mem[e]:{...this.mem};let t=await this.http.get(`/conversations/${this.getConversationId()}/custom`);return e!==void 0?t[e]:t}async set(e){if(this.isPreview){for(let[t,n]of Object.entries(e))typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof this.mem[t]=="object"&&this.mem[t]!==null?this.mem[t]={...this.mem[t],...n}:this.mem[t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom`,e)}async delete(e){if(this.isPreview){delete this.mem[e];return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}`)}async setGroupField(e,t,n){if(this.isPreview){(!this.mem[e]||typeof this.mem[e]!="object")&&(this.mem[e]={}),this.mem[e][t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{value:n})}async deleteGroupField(e,t){if(this.isPreview){if(typeof this.mem[e]=="object"&&this.mem[e]!==null){let n=this.mem[e];delete n[t],Object.keys(n).length===0&&delete this.mem[e]}return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var $="/functions/v1/world-engine/v1",K="https://api.storvia.ai";function Y(){return window.__STORVIA__||{}}function q(a=5e3){let e=Y();return e.apiBase?Promise.resolve(e):new Promise((t,n)=>{let i=setTimeout(()=>{window.removeEventListener("message",s),n(new c("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},a);function s(r){let o=null;if(r.data?.type==="storvia-init"&&r.data.apiBase?o={apiBase:r.data.apiBase,gameId:r.data.gameId,accessToken:r.data.accessToken}:r.data?.type==="storvia-preview-init"&&r.data.config&&(o=r.data.config),o&&o.apiBase){clearTimeout(i),window.removeEventListener("message",s);let l=window;l.__STORVIA__=o,t(o)}}window.addEventListener("message",s)})}var S=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){if(this.initialized)return;let e=await q(),t=e.apiBase;if(!t)throw new c("NOT_INITIALIZED","window.__STORVIA__.apiBase is not set. The platform must inject it before SDK init.");if(this.baseUrl=`${t}${$}`,this.isPreview=!!e.preview,this.previewConfig=e.previewConfig,!e.gameId)throw new c("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 c("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 E(this.baseUrl,this.accessToken,!!e.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let d=await this.fetchModels();this.modelId=e.selectedModelId||d[0]?.id||"",this.settingsSheet=new u({onModelChange:P=>{this.modelId=P},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),d.length>0&&this.settingsSheet.mount(d,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let m=()=>this.gameId,p=()=>this.conversationId,I=()=>this.modelId;this.chat=new v(this.http,m,p,I,!0,this.previewConfig),this.characters=new f(this.http,p,!0),this.relationships=new b(this.http,p,!0),this.inventory=new w(this.http,p,!0),this.world=new y(this.http,p,!0),this.player=new C(this.http,p,!0),this.custom=new x(this.http,p,!0),this.initialized=!0,this.listenForPreviewMessages();return}let[n,i]=await Promise.all([this.authenticate(),this.fetchModels()]);this.conversationId=n.conversationId;let s=this.getSavedModelId();this.modelId=s&&i.some(d=>d.id===s)?s:i[0]?.id||"";let r=n.settings||{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.settingsSheet=new u({onModelChange:d=>{this.modelId=d},onSettingsChange:d=>this.saveSettings(d),onSync:()=>this.syncSettings()}),this.settingsSheet.mount(i,this.modelId,r,n.hasWorldUpdate??!1);let o=()=>this.gameId,l=()=>this.conversationId,h=()=>this.modelId;this.chat=new v(this.http,o,l,h),this.characters=new f(this.http,l),this.relationships=new b(this.http,l),this.inventory=new w(this.http,l),this.world=new y(this.http,l),this.player=new C(this.http,l),this.custom=new x(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)))})}async saveSettings(e){await this.http.patch("/settings",{conversation_id:this.conversationId,...e})}async syncSettings(){await this.http.post("/sync",{conversation_id:this.conversationId})}async fetchModels(){try{return await this.http.get("/models")}catch{}return[]}async authenticate(){let e=await fetch(`${this.baseUrl}/auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.accessToken}`},body:JSON.stringify({game_id:this.gameId})});if(!e.ok)throw e.status===401?new c("UNAUTHORIZED","User not authenticated"):e.status===404?new c("GAME_NOT_FOUND","Game not found or not published"):new c("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=`${K}${$}`,this.gameId=e.gameId,this.isPreview=!0,this.http=new E(this.baseUrl,"",!1,e.apiKey);let t=await this.fetchModels();this.modelId=t[0]?.id||"",this.conversationId="00000000-0000-0000-0000-000000000000",this.settingsSheet=new u({onModelChange:r=>{this.modelId=r},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),t.length>0&&this.settingsSheet.mount(t,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let n=()=>this.gameId,i=()=>this.conversationId,s=()=>this.modelId;this.chat=new v(this.http,n,i,s,!0,void 0),this.characters=new f(this.http,i,!0),this.relationships=new b(this.http,i,!0),this.inventory=new w(this.http,i,!0),this.world=new y(this.http,i,!0),this.player=new C(this.http,i,!0),this.custom=new x(this.http,i,!0),this.initialized=!0}};async function O(a){let e=new S;return a?.dev?await e.initDev(a.dev):await e.init(),e}function _(a){return typeof a=="object"&&a!==null&&"value"in a&&"type"in a&&(a.type==="number"||a.type==="text")}function L(a){return _(a)?a.value:a}0&&(module.exports={StorviaError,StorviaSDK,createStorviaSDK,extractFieldValue,isRichFieldValue});
|
package/dist/index.d.mts
CHANGED
|
@@ -38,18 +38,44 @@ interface ChatGenerateOptions {
|
|
|
38
38
|
onChunk?: (text: string) => void;
|
|
39
39
|
onDone?: (id: string) => void;
|
|
40
40
|
}
|
|
41
|
+
interface ChatRetryOptions {
|
|
42
|
+
topic?: string;
|
|
43
|
+
context?: string;
|
|
44
|
+
stream?: boolean;
|
|
45
|
+
onChunk?: (text: string) => void;
|
|
46
|
+
onDone?: (id: string) => void;
|
|
47
|
+
}
|
|
41
48
|
interface ChatResponse {
|
|
42
49
|
id: string;
|
|
43
50
|
content: string;
|
|
44
51
|
}
|
|
52
|
+
/** 富字段值:携带类型和范围元数据 */
|
|
53
|
+
interface RichFieldValue {
|
|
54
|
+
value: string | number | boolean;
|
|
55
|
+
type: 'number' | 'text';
|
|
56
|
+
min?: number;
|
|
57
|
+
max?: number;
|
|
58
|
+
}
|
|
59
|
+
/** 字段值:简单值或富字段值 */
|
|
60
|
+
type FieldValue = string | number | boolean | RichFieldValue;
|
|
61
|
+
/** 判断是否为 RichFieldValue */
|
|
62
|
+
declare function isRichFieldValue(v: unknown): v is RichFieldValue;
|
|
63
|
+
/** 从 FieldValue 中提取原始值 */
|
|
64
|
+
declare function extractFieldValue(v: FieldValue): string | number | boolean;
|
|
45
65
|
interface CharacterPersona {
|
|
46
66
|
name: string;
|
|
47
67
|
avatar?: string;
|
|
68
|
+
description?: string;
|
|
69
|
+
userDescription?: string;
|
|
70
|
+
isPreset?: boolean;
|
|
48
71
|
}
|
|
49
72
|
interface CharacterDetail {
|
|
50
73
|
name: string;
|
|
51
74
|
avatar?: string;
|
|
52
|
-
|
|
75
|
+
description?: string;
|
|
76
|
+
userDescription?: string;
|
|
77
|
+
isPreset?: boolean;
|
|
78
|
+
state: Record<string, FieldValue>;
|
|
53
79
|
}
|
|
54
80
|
interface Relationship {
|
|
55
81
|
from: string;
|
|
@@ -97,6 +123,11 @@ declare class ChatModule {
|
|
|
97
123
|
* 适用于群聊 NPC 回复、NPC 自动发言、弹幕生成等
|
|
98
124
|
*/
|
|
99
125
|
generate(options: ChatGenerateOptions): Promise<ChatResponse | void>;
|
|
126
|
+
/**
|
|
127
|
+
* 重试最后一条 AI 消息(覆盖原消息重新生成)
|
|
128
|
+
* 适用于 AI 回复出错或不满意时重新生成
|
|
129
|
+
*/
|
|
130
|
+
retry(options?: ChatRetryOptions): Promise<ChatResponse | void>;
|
|
100
131
|
/** 预览模式:发到 /preview 端点 */
|
|
101
132
|
private sendPreview;
|
|
102
133
|
}
|
|
@@ -107,8 +138,8 @@ declare class CharacterStateModule {
|
|
|
107
138
|
private isPreview;
|
|
108
139
|
private mem;
|
|
109
140
|
constructor(http: HttpClient, getConversationId: () => string, isPreview?: boolean);
|
|
110
|
-
get(characterName: string): Promise<Record<string,
|
|
111
|
-
update(characterName: string, values: Record<string, string | number>): Promise<void>;
|
|
141
|
+
get(characterName: string): Promise<Record<string, FieldValue>>;
|
|
142
|
+
update(characterName: string, values: Record<string, string | number | boolean>): Promise<void>;
|
|
112
143
|
}
|
|
113
144
|
declare class CharactersModule {
|
|
114
145
|
private http;
|
|
@@ -124,7 +155,11 @@ declare class CharactersModule {
|
|
|
124
155
|
description?: string;
|
|
125
156
|
avatar?: string;
|
|
126
157
|
}): Promise<void>;
|
|
127
|
-
update(name: string, data:
|
|
158
|
+
update(name: string, data: {
|
|
159
|
+
description?: string;
|
|
160
|
+
userDescription?: string;
|
|
161
|
+
avatar?: string;
|
|
162
|
+
}): Promise<void>;
|
|
128
163
|
remove(name: string): Promise<void>;
|
|
129
164
|
detail(name: string): Promise<CharacterDetail>;
|
|
130
165
|
}
|
|
@@ -170,9 +205,9 @@ declare class PlayerStateModule {
|
|
|
170
205
|
private isPreview;
|
|
171
206
|
private mem;
|
|
172
207
|
constructor(http: HttpClient, getConversationId: () => string, isPreview?: boolean);
|
|
173
|
-
get(): Promise<Record<string, Record<string,
|
|
174
|
-
get(group: string): Promise<Record<string,
|
|
175
|
-
update(group: string, values: Record<string, string | number>): Promise<void>;
|
|
208
|
+
get(): Promise<Record<string, Record<string, FieldValue>>>;
|
|
209
|
+
get(group: string): Promise<Record<string, FieldValue>>;
|
|
210
|
+
update(group: string, values: Record<string, string | number | boolean>): Promise<void>;
|
|
176
211
|
}
|
|
177
212
|
declare class PlayerModule {
|
|
178
213
|
private http;
|
|
@@ -182,6 +217,7 @@ declare class PlayerModule {
|
|
|
182
217
|
private memPersona;
|
|
183
218
|
constructor(http: HttpClient, getConversationId: () => string, isPreview?: boolean);
|
|
184
219
|
get(): Promise<PlayerPersona>;
|
|
220
|
+
update(data: Partial<PlayerPersona>): Promise<void>;
|
|
185
221
|
}
|
|
186
222
|
|
|
187
223
|
declare class CustomModule {
|
|
@@ -241,4 +277,4 @@ declare class StorviaError extends Error {
|
|
|
241
277
|
constructor(code: StorviaErrorCode, message: string);
|
|
242
278
|
}
|
|
243
279
|
|
|
244
|
-
export { type CharacterDetail, type CharacterPersona, type ChatGenerateOptions, type ChatResponse, type ChatSaveOptions, type ChatSendOptions, type InventoryItemData, type PlayerPersona, type Relationship, StorviaError, type StorviaErrorCode, StorviaSDK, createStorviaSDK };
|
|
280
|
+
export { type CharacterDetail, type CharacterPersona, type ChatGenerateOptions, type ChatResponse, type ChatSaveOptions, type ChatSendOptions, type FieldValue, type InventoryItemData, type PlayerPersona, type Relationship, type RichFieldValue, StorviaError, type StorviaErrorCode, StorviaSDK, createStorviaSDK, extractFieldValue, isRichFieldValue };
|
package/dist/index.esm.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var c=class extends Error{constructor(e,t){super(t),this.name="StorviaError",this.code=e}};var
|
|
2
|
-
`);for(let
|
|
1
|
+
var c=class extends Error{constructor(e,t){super(t),this.name="StorviaError",this.code=e}};var E=class{constructor(e,t,n=!1,i=""){this.baseUrl=e,this.token=t,this.debug=n,this.devApiKey=i}setToken(e){this.token=e}setDebug(e){this.debug=e}buildHeaders(){let e={"Content-Type":"application/json"};return this.token&&(e.Authorization=`Bearer ${this.token}`),this.devApiKey&&(e["x-api-key"]=this.devApiKey),e}log(e,t,n,i,s){if(!this.debug)return;let r="%c[Storvia SDK]",o="color: #6366f1; font-weight: bold";s?(console.groupCollapsed(`${r} %c${e} ${t} %c\u2717`,o,"color: #e0e0e0","color: #ef4444"),n&&console.log("Request:",n),console.error("Error:",s),console.groupEnd()):(console.groupCollapsed(`${r} %c${e} ${t} %c\u2713`,o,"color: #e0e0e0","color: #22c55e"),n&&console.log("Request:",n),i!==void 0&&console.log("Response:",i),console.groupEnd())}async get(e,t){let n=new URL(`${this.baseUrl}${e}`);t&&Object.entries(t).forEach(([i,s])=>n.searchParams.set(i,s));try{let i=await fetch(n.toString(),{method:"GET",headers:this.buildHeaders()}),s=await this.handleResponse(i);return this.log("GET",e,t,s),s}catch(i){throw this.log("GET",e,t,void 0,i),i}}async post(e,t){try{let n=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0}),i=await this.handleResponse(n);return this.log("POST",e,t,i),i}catch(n){throw this.log("POST",e,t,void 0,n),n}}async patch(e,t){try{let n=await fetch(`${this.baseUrl}${e}`,{method:"PATCH",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0}),i=await this.handleResponse(n);return this.log("PATCH",e,t,i),i}catch(n){throw this.log("PATCH",e,t,void 0,n),n}}async delete(e){try{let t=await fetch(`${this.baseUrl}${e}`,{method:"DELETE",headers:this.buildHeaders()}),n=await this.handleResponse(t);return this.log("DELETE",e,void 0,n),n}catch(t){throw this.log("DELETE",e,void 0,void 0,t),t}}async stream(e,t,n,i){this.log("STREAM",e,t);let s=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify(t)});if(!s.ok){let a=await s.json().catch(()=>({})),m=new c(a.code||"INTERNAL_ERROR",a.message||`HTTP ${s.status}`);throw this.log("STREAM",e,t,void 0,m),m}let r=s.body?.getReader();if(!r)throw new c("INTERNAL_ERROR","No response body for stream");let o=new TextDecoder,l="",h="";for(;;){let{done:a,value:m}=await r.read();if(a)break;let I=o.decode(m,{stream:!0}).split(`
|
|
2
|
+
`);for(let S of I){if(!S.startsWith("data: "))continue;let T=S.slice(6);if(T==="[DONE]"){this.debug&&this.log("STREAM",e+" [done]",void 0,{id:l,contentLength:h.length}),i(l);return}try{let g=JSON.parse(T);g.type==="done"&&g.id?l=g.id:g.content&&(h+=g.content,n(g.content))}catch{}}}l&&i(l)}async handleResponse(e){if(!e.ok){let n={};try{n=await e.json()}catch{}let i={401:"UNAUTHORIZED",402:"INSUFFICIENT_BALANCE",404:"GAME_NOT_FOUND",429:"RATE_LIMITED"},s=n.code||i[e.status]||"INTERNAL_ERROR";throw new c(s,n.message||`HTTP ${e.status}`)}let t=await e.json();return t&&typeof t=="object"&&"data"in t?t.data:t}};var $=[{value:"zh-CN",label:"\u7B80\u4F53\u4E2D\u6587"},{value:"zh-TW",label:"\u7E41\u9AD4\u4E2D\u6587"},{value:"en",label:"English"},{value:"ja",label:"\u65E5\u672C\u8A9E"},{value:"ko",label:"\uD55C\uAD6D\uC5B4"}],_=[{value:"low",label:"\u7B80\u77ED"},{value:"medium",label:"\u9002\u4E2D"},{value:"high",label:"\u8BE6\u7EC6"}],O=`
|
|
3
3
|
:host {
|
|
4
4
|
position: fixed;
|
|
5
5
|
bottom: 20px;
|
|
@@ -427,5 +427,5 @@ var c=class extends Error{constructor(e,t){super(t),this.name="StorviaError",thi
|
|
|
427
427
|
to { transform: rotate(360deg); }
|
|
428
428
|
}
|
|
429
429
|
.spin { animation: spin 0.8s linear infinite; }
|
|
430
|
-
`,L='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>',H='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>',O='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',B='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',A='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>',u=class{constructor(e){this.selectedModelId="";this.models=[];this.modelPanel=null;this.settings={temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.hasWorldUpdate=!1;this.fabDot=null;this.syncHint=null;this.displayMode="phone";this.displayModeBtns=[];this.tempValueEl=null;this.tempSlider=null;this.segmentBtns=[];this.langSelect=null;this.noteInput=null;this.noteCounter=null;this.saveBtn=null;this.syncBtn=null;this.syncState="idle";this.panel=null;this.callbacks=e,this.host=document.createElement("div"),this.host.id="storvia-settings",this.shadowRoot=this.host.attachShadow({mode:"closed"})}mount(e,t,n,i=!1){this.models=e,this.selectedModelId=t,this.settings={...n},this.hasWorldUpdate=i;try{let s=localStorage.getItem("storvia_display_mode");(s==="phone"||s==="desktop")&&(this.displayMode=s)}catch{}document.body.appendChild(this.host),this.render()}unmount(){this.host.remove()}getSelectedModelId(){return this.selectedModelId}getSettings(){return{...this.settings}}render(){let e=document.createElement("style");e.textContent=$;let t=document.createElement("div"),n=document.createElement("div");n.className="fab-wrap";let i=document.createElement("button");i.className="fab",i.innerHTML=L,i.title="\u6E38\u620F\u8BBE\u7F6E";let s=document.createElement("div");s.className=`fab-dot${this.hasWorldUpdate?" visible":""}`,this.fabDot=s,n.appendChild(i),n.appendChild(s);let a=document.createElement("div");a.className="panel",this.panel=a;let o=document.createElement("div");o.className="panel-header";let d=document.createElement("div");d.className="panel-title",d.textContent="\u6E38\u620F\u8BBE\u7F6E";let h=document.createElement("button");h.className="close-btn",h.innerHTML="\u2715",h.addEventListener("click",()=>a.classList.remove("open")),o.appendChild(d),o.appendChild(h),a.appendChild(o);let r=document.createElement("div");r.className="panel-body",this.models.length>0&&(r.appendChild(this.buildModelSection()),r.appendChild(this.makeDivider())),r.appendChild(this.buildTemperatureSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildReplyLengthSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildReplyLanguageSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildNoteSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildDisplayModeSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildSyncSection());let m=document.createElement("div");m.className="save-row";let p=document.createElement("button");p.className="save-btn",p.textContent="\u4FDD\u5B58",this.saveBtn=p,p.addEventListener("click",()=>this.handleSave()),m.appendChild(p),r.appendChild(m),a.appendChild(r),i.addEventListener("click",()=>a.classList.toggle("open")),document.addEventListener("click",I=>{this.host.contains(I.target)||a.classList.remove("open")}),t.appendChild(a),t.appendChild(n),this.shadowRoot.appendChild(e),this.shadowRoot.appendChild(t)}buildModelSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="AI \u6A21\u578B",e.appendChild(t);let n=document.createElement("div");return n.className="model-list",this.modelPanel=n,this.models.forEach(i=>{let s=document.createElement("button");s.className=`model-option${i.id===this.selectedModelId?" active":""}`,s.innerHTML=`<span class="dot"></span><span>${i.name}</span>`,s.addEventListener("click",()=>{this.selectedModelId=i.id,this.callbacks.onModelChange(i.id);try{localStorage.setItem("storvia_model_id",i.id)}catch{}this.updateModelActive()}),n.appendChild(s)}),e.appendChild(n),e}buildTemperatureSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label";let n=document.createElement("span");n.textContent="\u6E29\u5EA6";let i=document.createElement("span");i.className="value",i.textContent=this.settings.temperature.toFixed(1),this.tempValueEl=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("div");s.className="section-desc",s.textContent="\u66F4\u4F4E\u7684\u6E29\u5EA6\u4F1A\u8BA9 AI \u56DE\u590D\u66F4\u7A33\u5B9A\u3001\u7406\u667A\uFF1B\u66F4\u9AD8\u7684\u6E29\u5EA6\u4F1A\u8BA9 AI \u7684\u56DE\u590D\u66F4\u5177\u591A\u6837\u6027\u548C\u968F\u673A\u6027",e.appendChild(s);let a=document.createElement("div");a.className="slider-wrap";let o=document.createElement("input");o.type="range",o.className="slider",o.min="0",o.max="2",o.step="0.1",o.value=String(this.settings.temperature),this.tempSlider=o,o.addEventListener("input",()=>{let h=parseFloat(o.value);this.settings.temperature=h,this.tempValueEl&&(this.tempValueEl.textContent=h.toFixed(1))}),a.appendChild(o);let d=document.createElement("div");return d.className="slider-labels",d.innerHTML="<span>\u7CBE\u786E</span><span>\u521B\u610F</span>",a.appendChild(d),e.appendChild(a),e}buildReplyLengthSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u56DE\u590D\u957F\u5EA6",e.appendChild(t);let n=document.createElement("div");return n.className="segment",this.segmentBtns=[],_.forEach(i=>{let s=document.createElement("button");s.className=`segment-btn${i.value===this.settings.reply_length?" active":""}`,s.textContent=i.label,s.addEventListener("click",()=>{this.settings.reply_length=i.value,this.segmentBtns.forEach((a,o)=>{a.classList.toggle("active",_[o].value===i.value)})}),this.segmentBtns.push(s),n.appendChild(s)}),e.appendChild(n),e}buildReplyLanguageSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u56DE\u590D\u8BED\u8A00",e.appendChild(t);let n=document.createElement("div");n.className="select-wrap";let i=document.createElement("select");i.className="select",this.langSelect=i,N.forEach(a=>{let o=document.createElement("option");o.value=a.value,o.textContent=a.label,a.value===this.settings.reply_language&&(o.selected=!0),i.appendChild(o)}),i.addEventListener("change",()=>{this.settings.reply_language=i.value});let s=document.createElement("span");return s.className="select-arrow",s.textContent="\u25BE",n.appendChild(i),n.appendChild(s),e.appendChild(n),e}buildNoteSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label";let n=document.createElement("span");n.textContent="\u5907\u6CE8";let i=document.createElement("span");i.textContent=`${this.settings.player_note.length}/50`,this.noteCounter=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("div");s.className="section-desc",s.textContent="\u5199\u4E0B\u4F60\u5BF9\u8FD9\u4E2A\u6E38\u620F\u7684\u5907\u6CE8\uFF0C\u4F1A\u663E\u793A\u5728\u5B58\u6863\u5217\u8868",e.appendChild(s);let a=document.createElement("div");a.className="note-wrap";let o=document.createElement("textarea");return o.className="note-input",o.placeholder="\u5907\u6CE8",o.maxLength=50,o.value=this.settings.player_note,this.noteInput=o,o.addEventListener("input",()=>{this.settings.player_note=o.value,this.noteCounter&&(this.noteCounter.textContent=`${o.value.length}/50`)}),a.appendChild(o),e.appendChild(a),e}buildDisplayModeSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u663E\u793A\u6A21\u5F0F",e.appendChild(t);let n=document.createElement("div");n.className="section-desc",n.textContent="\u7535\u8111\u6A21\u5F0F\u4F1A\u81EA\u52A8\u6A2A\u5C4F\u663E\u793A",e.appendChild(n);let i=document.createElement("div");i.className="segment",this.displayModeBtns=[];let s=[{value:"phone",label:"\u624B\u673A"},{value:"desktop",label:"\u7535\u8111"}];return s.forEach(a=>{let o=document.createElement("button");o.className=`segment-btn${a.value===this.displayMode?" active":""}`,o.textContent=a.label,o.addEventListener("click",()=>{this.displayMode=a.value;try{localStorage.setItem("storvia_display_mode",a.value)}catch{}this.displayModeBtns.forEach((d,h)=>{d.classList.toggle("active",s[h].value===a.value)});try{window.parent.postMessage({type:"storvia-orientation",mode:a.value==="desktop"?"landscape":"portrait"},"*")}catch{}}),this.displayModeBtns.push(o),i.appendChild(o)}),e.appendChild(i),e}buildSyncSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u540C\u6B65\u6E38\u620F\u8BBE\u5B9A",e.appendChild(t);let n=document.createElement("div");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("div");i.className="sync-desc",i.textContent="\u5982\u679C\u6E38\u620F\u4F5C\u8005\u66F4\u65B0\u4E86\u5185\u5BB9\uFF0C\u70B9\u51FB\u6B64\u6309\u94AE\u53EF\u5C06\u6700\u65B0\u7684\u6E38\u620F\u8BBE\u5B9A\u548C\u5F00\u5E55\u5C0F\u5267\u573A\u540C\u6B65\u5230\u5F53\u524D\u5BF9\u8BDD",e.appendChild(i);let s=document.createElement("button");return s.className="sync-btn",this.syncBtn=s,this.renderSyncBtn(),s.addEventListener("click",async()=>{if(this.syncState!=="loading"){this.setSyncState("loading");try{await this.callbacks.onSync(),this.setSyncState("success"),this.hasWorldUpdate=!1,this.fabDot&&this.fabDot.classList.remove("visible"),this.syncHint&&this.syncHint.classList.remove("visible"),setTimeout(()=>this.setSyncState("idle"),3e3)}catch{this.setSyncState("error"),setTimeout(()=>this.setSyncState("idle"),4e3)}}}),e.appendChild(s),e}makeDivider(){let e=document.createElement("div");return e.className="divider",e}updateModelActive(){this.modelPanel&&this.modelPanel.querySelectorAll(".model-option").forEach((e,t)=>{e.classList.toggle("active",this.models[t].id===this.selectedModelId)})}setSyncState(e){this.syncState=e,this.renderSyncBtn()}renderSyncBtn(){if(!this.syncBtn)return;let e=this.syncState,t={idle:H,loading:O,success:B,error:A},n={idle:"\u540C\u6B65\u6700\u65B0\u8BBE\u5B9A",loading:"\u540C\u6B65\u4E2D...",success:"\u5DF2\u540C\u6B65",error:"\u540C\u6B65\u5931\u8D25"};this.syncBtn.className=`sync-btn${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.textContent="\u4FDD\u5B58\u4E2D...";try{await this.callbacks.onSettingsChange({temperature:this.settings.temperature,reply_length:this.settings.reply_length,reply_language:this.settings.reply_language,player_note:this.settings.player_note}),this.saveBtn.textContent="\u5DF2\u4FDD\u5B58",this.saveBtn.classList.add("saved"),setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.classList.remove("saved"),this.saveBtn.disabled=!1)},2e3)}catch{this.saveBtn.textContent="\u4FDD\u5B58\u5931\u8D25",setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1)},2e3)}}}};var v=class{constructor(e,t,n,i,s=!1,a){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=i;this.isPreview=s;this.previewConfig=a}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_context:e.context,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/chat",t)}async save(e){return this.isPreview?{id:`preview-${Date.now()}`}:this.http.post("/messages/save",{conversation_id:this.getConversationId(),role:e.role,content:e.content,topic:e.topic})}async generate(e){if(this.isPreview)return this.sendPreview({message:"",topic:e.topic,context:(e.context||"")+`
|
|
431
|
-
[\u6307\u4EE4] \u8BF7\u76F4\u63A5\u751F\u6210\u56DE\u590D\uFF0C\u65E0\u9700\u7528\u6237\u8F93\u5165`,stream:e.stream,onChunk:e.onChunk,onDone:e.onDone});let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,scene_context:e.context,stream:e.stream??!1,save:e.save??!0};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/generate",t)}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,context:e.context,prompt_config:this.previewConfig||{},history_messages:[]};if(e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}let n="";return await this.http.stream("/preview",t,i=>{n+=i},()=>{}),{id:"",content:n}}};var k=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){return this.isPreview?{...this.mem[e]||{}}:this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,t)}},f=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];this.state=new k(e,t,n)}async list(){return this.isPreview?this.mem.map(e=>({name:e.name,avatar:e.avatar})):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:t?.name||e,avatar:t?.avatar}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async add(e){if(this.isPreview){this.mem.push(e);return}await this.http.post(`/conversations/${this.getConversationId()}/characters`,e)}async update(e,t){if(this.isPreview){let n=this.mem.find(i=>i.name===e);n&&Object.assign(n,t);return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`,t)}async remove(e){if(this.isPreview){this.mem=this.mem.filter(t=>t.name!==e);return}await this.http.delete(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async detail(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:e,avatar:t?.avatar,state:await this.state.get(e)}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/detail`)}};var w=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(){return this.isPreview?[...this.mem]:this.http.get(`/conversations/${this.getConversationId()}/relationships`)}async get(e,t){if(this.isPreview){let n=this.mem.find(i=>i.from===e&&i.to===t);if(n)return{...n};throw new Error("Relationship not found")}return this.http.get(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/relationships`,e)}async update(e,t,n){if(this.isPreview){let i=this.mem.find(s=>s.from===e&&s.to===t);i?Object.assign(i,n):this.mem.push({from:e,to:t,...n});return}await this.http.patch(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,n)}async remove(e,t){if(this.isPreview){this.mem=this.mem.filter(n=>!(n.from===e&&n.to===t));return}await this.http.delete(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var b=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(e){if(this.isPreview)return e?this.mem.filter(n=>n.group===e):[...this.mem];let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/inventory`,t)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/inventory`,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()}/inventory/${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()}/inventory/${encodeURIComponent(e)}`)}};var y=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(){return this.isPreview?{...this.mem}:this.http.get(`/conversations/${this.getConversationId()}/world`)}async update(e){if(this.isPreview){Object.assign(this.mem,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/world`,e)}};var R=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e?{...this.mem[e]||{}}:{...this.mem};let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/player/state`,t)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/player/state`,{group:e,values:t})}},C=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};this.state=new R(e,t,n)}async get(){return this.isPreview?{...this.memPersona}:this.http.get(`/conversations/${this.getConversationId()}/player`)}};var x=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e!==void 0?this.mem[e]:{...this.mem};let t=await this.http.get(`/conversations/${this.getConversationId()}/custom`);return e!==void 0?t[e]:t}async set(e){if(this.isPreview){for(let[t,n]of Object.entries(e))typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof this.mem[t]=="object"&&this.mem[t]!==null?this.mem[t]={...this.mem[t],...n}:this.mem[t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom`,e)}async delete(e){if(this.isPreview){delete this.mem[e];return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}`)}async setGroupField(e,t,n){if(this.isPreview){(!this.mem[e]||typeof this.mem[e]!="object")&&(this.mem[e]={}),this.mem[e][t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{value:n})}async deleteGroupField(e,t){if(this.isPreview){if(typeof this.mem[e]=="object"&&this.mem[e]!==null){let n=this.mem[e];delete n[t],Object.keys(n).length===0&&delete this.mem[e]}return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var M="/functions/v1/world-engine/v1",D="https://api.storvia.ai";function U(){return window.__STORVIA__||{}}function j(l=5e3){let e=U();return e.apiBase?Promise.resolve(e):new Promise((t,n)=>{let i=setTimeout(()=>{window.removeEventListener("message",s),n(new c("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},l);function s(a){let o=null;if(a.data?.type==="storvia-init"&&a.data.apiBase?o={apiBase:a.data.apiBase,gameId:a.data.gameId,accessToken:a.data.accessToken}:a.data?.type==="storvia-preview-init"&&a.data.config&&(o=a.data.config),o&&o.apiBase){clearTimeout(i),window.removeEventListener("message",s);let d=window;d.__STORVIA__=o,t(o)}}window.addEventListener("message",s)})}var P=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){if(this.initialized)return;let e=await j(),t=e.apiBase;if(!t)throw new c("NOT_INITIALIZED","window.__STORVIA__.apiBase is not set. The platform must inject it before SDK init.");if(this.baseUrl=`${t}${M}`,this.isPreview=!!e.preview,this.previewConfig=e.previewConfig,!e.gameId)throw new c("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 c("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 S(this.baseUrl,this.accessToken,!!e.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let r=await this.fetchModels();this.modelId=e.selectedModelId||r[0]?.id||"",this.settingsSheet=new u({onModelChange:E=>{this.modelId=E},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),r.length>0&&this.settingsSheet.mount(r,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let m=()=>this.gameId,p=()=>this.conversationId,I=()=>this.modelId;this.chat=new v(this.http,m,p,I,!0,this.previewConfig),this.characters=new f(this.http,p,!0),this.relationships=new w(this.http,p,!0),this.inventory=new b(this.http,p,!0),this.world=new y(this.http,p,!0),this.player=new C(this.http,p,!0),this.custom=new x(this.http,p,!0),this.initialized=!0,this.listenForPreviewMessages();return}let[n,i]=await Promise.all([this.authenticate(),this.fetchModels()]);this.conversationId=n.conversationId;let s=this.getSavedModelId();this.modelId=s&&i.some(r=>r.id===s)?s:i[0]?.id||"";let a=n.settings||{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.settingsSheet=new u({onModelChange:r=>{this.modelId=r},onSettingsChange:r=>this.saveSettings(r),onSync:()=>this.syncSettings()}),this.settingsSheet.mount(i,this.modelId,a,n.hasWorldUpdate??!1);let o=()=>this.gameId,d=()=>this.conversationId,h=()=>this.modelId;this.chat=new v(this.http,o,d,h),this.characters=new f(this.http,d),this.relationships=new w(this.http,d),this.inventory=new b(this.http,d),this.world=new y(this.http,d),this.player=new C(this.http,d),this.custom=new x(this.http,d),this.initialized=!0}listenForPreviewMessages(){window.addEventListener("message",e=>{!e.data||e.data.type!=="storvia-preview"||(e.data.action==="set-model"&&(this.modelId=e.data.modelId||""),e.data.action==="update-config"&&(this.previewConfig=e.data.previewConfig,this.chat&&this.chat.updatePreviewConfig(this.previewConfig)))})}async saveSettings(e){await this.http.patch("/settings",{conversation_id:this.conversationId,...e})}async syncSettings(){await this.http.post("/sync",{conversation_id:this.conversationId})}async fetchModels(){try{return await this.http.get("/models")}catch{}return[]}async authenticate(){let e=await fetch(`${this.baseUrl}/auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.accessToken}`},body:JSON.stringify({game_id:this.gameId})});if(!e.ok)throw e.status===401?new c("UNAUTHORIZED","User not authenticated"):e.status===404?new c("GAME_NOT_FOUND","Game not found or not published"):new c("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=`${D}${M}`,this.gameId=e.gameId,this.isPreview=!0,this.http=new S(this.baseUrl,"",!1,e.apiKey);let t=await this.fetchModels();this.modelId=t[0]?.id||"",this.conversationId="00000000-0000-0000-0000-000000000000",this.settingsSheet=new u({onModelChange:a=>{this.modelId=a},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),t.length>0&&this.settingsSheet.mount(t,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let n=()=>this.gameId,i=()=>this.conversationId,s=()=>this.modelId;this.chat=new v(this.http,n,i,s,!0,void 0),this.characters=new f(this.http,i,!0),this.relationships=new w(this.http,i,!0),this.inventory=new b(this.http,i,!0),this.world=new y(this.http,i,!0),this.player=new C(this.http,i,!0),this.custom=new x(this.http,i,!0),this.initialized=!0}};async function z(l){let e=new P;return l?.dev?await e.initDev(l.dev):await e.init(),e}export{c as StorviaError,P as StorviaSDK,z as createStorviaSDK};
|
|
430
|
+
`,L='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>',D='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>',H='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',A='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',B='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>',u=class{constructor(e){this.selectedModelId="";this.models=[];this.modelPanel=null;this.settings={temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.hasWorldUpdate=!1;this.fabDot=null;this.syncHint=null;this.displayMode="phone";this.displayModeBtns=[];this.tempValueEl=null;this.tempSlider=null;this.segmentBtns=[];this.langSelect=null;this.noteInput=null;this.noteCounter=null;this.saveBtn=null;this.syncBtn=null;this.syncState="idle";this.panel=null;this.callbacks=e,this.host=document.createElement("div"),this.host.id="storvia-settings",this.shadowRoot=this.host.attachShadow({mode:"closed"})}mount(e,t,n,i=!1){this.models=e,this.selectedModelId=t,this.settings={...n},this.hasWorldUpdate=i;try{let s=localStorage.getItem("storvia_display_mode");(s==="phone"||s==="desktop")&&(this.displayMode=s)}catch{}document.body.appendChild(this.host),this.render()}unmount(){this.host.remove()}getSelectedModelId(){return this.selectedModelId}getSettings(){return{...this.settings}}render(){let e=document.createElement("style");e.textContent=O;let t=document.createElement("div"),n=document.createElement("div");n.className="fab-wrap";let i=document.createElement("button");i.className="fab",i.innerHTML=L,i.title="\u6E38\u620F\u8BBE\u7F6E";let s=document.createElement("div");s.className=`fab-dot${this.hasWorldUpdate?" visible":""}`,this.fabDot=s,n.appendChild(i),n.appendChild(s);let r=document.createElement("div");r.className="panel",this.panel=r;let o=document.createElement("div");o.className="panel-header";let l=document.createElement("div");l.className="panel-title",l.textContent="\u6E38\u620F\u8BBE\u7F6E";let h=document.createElement("button");h.className="close-btn",h.innerHTML="\u2715",h.addEventListener("click",()=>r.classList.remove("open")),o.appendChild(l),o.appendChild(h),r.appendChild(o);let a=document.createElement("div");a.className="panel-body",this.models.length>0&&(a.appendChild(this.buildModelSection()),a.appendChild(this.makeDivider())),a.appendChild(this.buildTemperatureSection()),a.appendChild(this.makeDivider()),a.appendChild(this.buildReplyLengthSection()),a.appendChild(this.makeDivider()),a.appendChild(this.buildReplyLanguageSection()),a.appendChild(this.makeDivider()),a.appendChild(this.buildNoteSection()),a.appendChild(this.makeDivider()),a.appendChild(this.buildDisplayModeSection()),a.appendChild(this.makeDivider()),a.appendChild(this.buildSyncSection());let m=document.createElement("div");m.className="save-row";let p=document.createElement("button");p.className="save-btn",p.textContent="\u4FDD\u5B58",this.saveBtn=p,p.addEventListener("click",()=>this.handleSave()),m.appendChild(p),a.appendChild(m),r.appendChild(a),i.addEventListener("click",()=>r.classList.toggle("open")),document.addEventListener("click",I=>{this.host.contains(I.target)||r.classList.remove("open")}),t.appendChild(r),t.appendChild(n),this.shadowRoot.appendChild(e),this.shadowRoot.appendChild(t)}buildModelSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="AI \u6A21\u578B",e.appendChild(t);let n=document.createElement("div");return n.className="model-list",this.modelPanel=n,this.models.forEach(i=>{let s=document.createElement("button");s.className=`model-option${i.id===this.selectedModelId?" active":""}`,s.innerHTML=`<span class="dot"></span><span>${i.name}</span>`,s.addEventListener("click",()=>{this.selectedModelId=i.id,this.callbacks.onModelChange(i.id);try{localStorage.setItem("storvia_model_id",i.id)}catch{}this.updateModelActive()}),n.appendChild(s)}),e.appendChild(n),e}buildTemperatureSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label";let n=document.createElement("span");n.textContent="\u6E29\u5EA6";let i=document.createElement("span");i.className="value",i.textContent=this.settings.temperature.toFixed(1),this.tempValueEl=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("div");s.className="section-desc",s.textContent="\u66F4\u4F4E\u7684\u6E29\u5EA6\u4F1A\u8BA9 AI \u56DE\u590D\u66F4\u7A33\u5B9A\u3001\u7406\u667A\uFF1B\u66F4\u9AD8\u7684\u6E29\u5EA6\u4F1A\u8BA9 AI \u7684\u56DE\u590D\u66F4\u5177\u591A\u6837\u6027\u548C\u968F\u673A\u6027",e.appendChild(s);let r=document.createElement("div");r.className="slider-wrap";let o=document.createElement("input");o.type="range",o.className="slider",o.min="0",o.max="2",o.step="0.1",o.value=String(this.settings.temperature),this.tempSlider=o,o.addEventListener("input",()=>{let h=parseFloat(o.value);this.settings.temperature=h,this.tempValueEl&&(this.tempValueEl.textContent=h.toFixed(1))}),r.appendChild(o);let l=document.createElement("div");return l.className="slider-labels",l.innerHTML="<span>\u7CBE\u786E</span><span>\u521B\u610F</span>",r.appendChild(l),e.appendChild(r),e}buildReplyLengthSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u56DE\u590D\u957F\u5EA6",e.appendChild(t);let n=document.createElement("div");return n.className="segment",this.segmentBtns=[],_.forEach(i=>{let s=document.createElement("button");s.className=`segment-btn${i.value===this.settings.reply_length?" active":""}`,s.textContent=i.label,s.addEventListener("click",()=>{this.settings.reply_length=i.value,this.segmentBtns.forEach((r,o)=>{r.classList.toggle("active",_[o].value===i.value)})}),this.segmentBtns.push(s),n.appendChild(s)}),e.appendChild(n),e}buildReplyLanguageSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u56DE\u590D\u8BED\u8A00",e.appendChild(t);let n=document.createElement("div");n.className="select-wrap";let i=document.createElement("select");i.className="select",this.langSelect=i,$.forEach(r=>{let o=document.createElement("option");o.value=r.value,o.textContent=r.label,r.value===this.settings.reply_language&&(o.selected=!0),i.appendChild(o)}),i.addEventListener("change",()=>{this.settings.reply_language=i.value});let s=document.createElement("span");return s.className="select-arrow",s.textContent="\u25BE",n.appendChild(i),n.appendChild(s),e.appendChild(n),e}buildNoteSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label";let n=document.createElement("span");n.textContent="\u5907\u6CE8";let i=document.createElement("span");i.textContent=`${this.settings.player_note.length}/50`,this.noteCounter=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("div");s.className="section-desc",s.textContent="\u5199\u4E0B\u4F60\u5BF9\u8FD9\u4E2A\u6E38\u620F\u7684\u5907\u6CE8\uFF0C\u4F1A\u663E\u793A\u5728\u5B58\u6863\u5217\u8868",e.appendChild(s);let r=document.createElement("div");r.className="note-wrap";let o=document.createElement("textarea");return o.className="note-input",o.placeholder="\u5907\u6CE8",o.maxLength=50,o.value=this.settings.player_note,this.noteInput=o,o.addEventListener("input",()=>{this.settings.player_note=o.value,this.noteCounter&&(this.noteCounter.textContent=`${o.value.length}/50`)}),r.appendChild(o),e.appendChild(r),e}buildDisplayModeSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u663E\u793A\u6A21\u5F0F",e.appendChild(t);let n=document.createElement("div");n.className="section-desc",n.textContent="\u7535\u8111\u6A21\u5F0F\u4F1A\u81EA\u52A8\u6A2A\u5C4F\u663E\u793A",e.appendChild(n);let i=document.createElement("div");i.className="segment",this.displayModeBtns=[];let s=[{value:"phone",label:"\u624B\u673A"},{value:"desktop",label:"\u7535\u8111"}];return s.forEach(r=>{let o=document.createElement("button");o.className=`segment-btn${r.value===this.displayMode?" active":""}`,o.textContent=r.label,o.addEventListener("click",()=>{this.displayMode=r.value;try{localStorage.setItem("storvia_display_mode",r.value)}catch{}this.displayModeBtns.forEach((l,h)=>{l.classList.toggle("active",s[h].value===r.value)});try{window.parent.postMessage({type:"storvia-orientation",mode:r.value==="desktop"?"landscape":"portrait"},"*")}catch{}}),this.displayModeBtns.push(o),i.appendChild(o)}),e.appendChild(i),e}buildSyncSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u540C\u6B65\u6E38\u620F\u8BBE\u5B9A",e.appendChild(t);let n=document.createElement("div");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("div");i.className="sync-desc",i.textContent="\u5982\u679C\u6E38\u620F\u4F5C\u8005\u66F4\u65B0\u4E86\u5185\u5BB9\uFF0C\u70B9\u51FB\u6B64\u6309\u94AE\u53EF\u5C06\u6700\u65B0\u7684\u6E38\u620F\u8BBE\u5B9A\u548C\u5F00\u5E55\u5C0F\u5267\u573A\u540C\u6B65\u5230\u5F53\u524D\u5BF9\u8BDD",e.appendChild(i);let s=document.createElement("button");return s.className="sync-btn",this.syncBtn=s,this.renderSyncBtn(),s.addEventListener("click",async()=>{if(this.syncState!=="loading"){this.setSyncState("loading");try{await this.callbacks.onSync(),this.setSyncState("success"),this.hasWorldUpdate=!1,this.fabDot&&this.fabDot.classList.remove("visible"),this.syncHint&&this.syncHint.classList.remove("visible"),setTimeout(()=>this.setSyncState("idle"),3e3)}catch{this.setSyncState("error"),setTimeout(()=>this.setSyncState("idle"),4e3)}}}),e.appendChild(s),e}makeDivider(){let e=document.createElement("div");return e.className="divider",e}updateModelActive(){this.modelPanel&&this.modelPanel.querySelectorAll(".model-option").forEach((e,t)=>{e.classList.toggle("active",this.models[t].id===this.selectedModelId)})}setSyncState(e){this.syncState=e,this.renderSyncBtn()}renderSyncBtn(){if(!this.syncBtn)return;let e=this.syncState,t={idle:D,loading:H,success:A,error:B},n={idle:"\u540C\u6B65\u6700\u65B0\u8BBE\u5B9A",loading:"\u540C\u6B65\u4E2D...",success:"\u5DF2\u540C\u6B65",error:"\u540C\u6B65\u5931\u8D25"};this.syncBtn.className=`sync-btn${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.textContent="\u4FDD\u5B58\u4E2D...";try{await this.callbacks.onSettingsChange({temperature:this.settings.temperature,reply_length:this.settings.reply_length,reply_language:this.settings.reply_language,player_note:this.settings.player_note}),this.saveBtn.textContent="\u5DF2\u4FDD\u5B58",this.saveBtn.classList.add("saved"),setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.classList.remove("saved"),this.saveBtn.disabled=!1)},2e3)}catch{this.saveBtn.textContent="\u4FDD\u5B58\u5931\u8D25",setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1)},2e3)}}}};var v=class{constructor(e,t,n,i,s=!1,r){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=i;this.isPreview=s;this.previewConfig=r}updatePreviewConfig(e){this.previewConfig=e}async send(e){if(this.isPreview)return this.sendPreview(e);let t={game_id:this.getGameId(),conversation_id:this.getConversationId(),model_id:this.getModelId(),message:e.message,topic:e.topic,scene_context:e.context,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/chat",t)}async save(e){return this.isPreview?{id:`preview-${Date.now()}`}:this.http.post("/messages/save",{conversation_id:this.getConversationId(),role:e.role,content:e.content,topic:e.topic})}async generate(e){if(this.isPreview)return this.sendPreview({message:"",topic:e.topic,context:(e.context||"")+`
|
|
431
|
+
[\u6307\u4EE4] \u8BF7\u76F4\u63A5\u751F\u6210\u56DE\u590D\uFF0C\u65E0\u9700\u7528\u6237\u8F93\u5165`,stream:e.stream,onChunk:e.onChunk,onDone:e.onDone});let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,scene_context:e.context,stream:e.stream??!1,save:e.save??!0};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/generate",t)}async retry(e={}){if(this.isPreview)throw new Error("Retry is not supported in preview mode");let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,scene_context:e.context,stream:e.stream??!1};if(e.stream){await this.http.stream("/retry",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/retry",t)}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,context:e.context,prompt_config:this.previewConfig||{},history_messages:[]};if(e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}let n="";return await this.http.stream("/preview",t,i=>{n+=i},()=>{}),{id:"",content:n}}};var R=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){return this.isPreview?{...this.mem[e]||{}}:this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,t)}},f=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];this.state=new R(e,t,n)}async list(){return this.isPreview?this.mem.map(e=>({name:e.name,avatar:e.avatar})):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:t?.name||e,avatar:t?.avatar}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async add(e){if(this.isPreview){this.mem.push(e);return}await this.http.post(`/conversations/${this.getConversationId()}/characters`,e)}async update(e,t){if(this.isPreview){let n=this.mem.find(i=>i.name===e);n&&Object.assign(n,t);return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`,t)}async remove(e){if(this.isPreview){this.mem=this.mem.filter(t=>t.name!==e);return}await this.http.delete(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async detail(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:e,avatar:t?.avatar,state:await this.state.get(e)}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/detail`)}};var b=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(){return this.isPreview?[...this.mem]:this.http.get(`/conversations/${this.getConversationId()}/relationships`)}async get(e,t){if(this.isPreview){let n=this.mem.find(i=>i.from===e&&i.to===t);if(n)return{...n};throw new Error("Relationship not found")}return this.http.get(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/relationships`,e)}async update(e,t,n){if(this.isPreview){let i=this.mem.find(s=>s.from===e&&s.to===t);i?Object.assign(i,n):this.mem.push({from:e,to:t,...n});return}await this.http.patch(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,n)}async remove(e,t){if(this.isPreview){this.mem=this.mem.filter(n=>!(n.from===e&&n.to===t));return}await this.http.delete(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var w=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(e){if(this.isPreview)return e?this.mem.filter(n=>n.group===e):[...this.mem];let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/inventory`,t)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/inventory`,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()}/inventory/${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()}/inventory/${encodeURIComponent(e)}`)}};var y=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(){return this.isPreview?{...this.mem}:this.http.get(`/conversations/${this.getConversationId()}/world`)}async update(e){if(this.isPreview){Object.assign(this.mem,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/world`,e)}};var k=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e?{...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})}},C=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};this.state=new k(e,t,n)}async get(){return this.isPreview?{...this.memPersona}:this.http.get(`/conversations/${this.getConversationId()}/player`)}async update(e){if(this.isPreview){Object.assign(this.memPersona,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/player`,e)}};var x=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e!==void 0?this.mem[e]:{...this.mem};let t=await this.http.get(`/conversations/${this.getConversationId()}/custom`);return e!==void 0?t[e]:t}async set(e){if(this.isPreview){for(let[t,n]of Object.entries(e))typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof this.mem[t]=="object"&&this.mem[t]!==null?this.mem[t]={...this.mem[t],...n}:this.mem[t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom`,e)}async delete(e){if(this.isPreview){delete this.mem[e];return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}`)}async setGroupField(e,t,n){if(this.isPreview){(!this.mem[e]||typeof this.mem[e]!="object")&&(this.mem[e]={}),this.mem[e][t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{value:n})}async deleteGroupField(e,t){if(this.isPreview){if(typeof this.mem[e]=="object"&&this.mem[e]!==null){let n=this.mem[e];delete n[t],Object.keys(n).length===0&&delete this.mem[e]}return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var N="/functions/v1/world-engine/v1",U="https://api.storvia.ai";function F(){return window.__STORVIA__||{}}function j(d=5e3){let e=F();return e.apiBase?Promise.resolve(e):new Promise((t,n)=>{let i=setTimeout(()=>{window.removeEventListener("message",s),n(new c("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},d);function s(r){let o=null;if(r.data?.type==="storvia-init"&&r.data.apiBase?o={apiBase:r.data.apiBase,gameId:r.data.gameId,accessToken:r.data.accessToken}:r.data?.type==="storvia-preview-init"&&r.data.config&&(o=r.data.config),o&&o.apiBase){clearTimeout(i),window.removeEventListener("message",s);let l=window;l.__STORVIA__=o,t(o)}}window.addEventListener("message",s)})}var P=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){if(this.initialized)return;let e=await j(),t=e.apiBase;if(!t)throw new c("NOT_INITIALIZED","window.__STORVIA__.apiBase is not set. The platform must inject it before SDK init.");if(this.baseUrl=`${t}${N}`,this.isPreview=!!e.preview,this.previewConfig=e.previewConfig,!e.gameId)throw new c("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 c("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 E(this.baseUrl,this.accessToken,!!e.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let a=await this.fetchModels();this.modelId=e.selectedModelId||a[0]?.id||"",this.settingsSheet=new u({onModelChange:S=>{this.modelId=S},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),a.length>0&&this.settingsSheet.mount(a,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let m=()=>this.gameId,p=()=>this.conversationId,I=()=>this.modelId;this.chat=new v(this.http,m,p,I,!0,this.previewConfig),this.characters=new f(this.http,p,!0),this.relationships=new b(this.http,p,!0),this.inventory=new w(this.http,p,!0),this.world=new y(this.http,p,!0),this.player=new C(this.http,p,!0),this.custom=new x(this.http,p,!0),this.initialized=!0,this.listenForPreviewMessages();return}let[n,i]=await Promise.all([this.authenticate(),this.fetchModels()]);this.conversationId=n.conversationId;let s=this.getSavedModelId();this.modelId=s&&i.some(a=>a.id===s)?s:i[0]?.id||"";let r=n.settings||{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.settingsSheet=new u({onModelChange:a=>{this.modelId=a},onSettingsChange:a=>this.saveSettings(a),onSync:()=>this.syncSettings()}),this.settingsSheet.mount(i,this.modelId,r,n.hasWorldUpdate??!1);let o=()=>this.gameId,l=()=>this.conversationId,h=()=>this.modelId;this.chat=new v(this.http,o,l,h),this.characters=new f(this.http,l),this.relationships=new b(this.http,l),this.inventory=new w(this.http,l),this.world=new y(this.http,l),this.player=new C(this.http,l),this.custom=new x(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)))})}async saveSettings(e){await this.http.patch("/settings",{conversation_id:this.conversationId,...e})}async syncSettings(){await this.http.post("/sync",{conversation_id:this.conversationId})}async fetchModels(){try{return await this.http.get("/models")}catch{}return[]}async authenticate(){let e=await fetch(`${this.baseUrl}/auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.accessToken}`},body:JSON.stringify({game_id:this.gameId})});if(!e.ok)throw e.status===401?new c("UNAUTHORIZED","User not authenticated"):e.status===404?new c("GAME_NOT_FOUND","Game not found or not published"):new c("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=`${U}${N}`,this.gameId=e.gameId,this.isPreview=!0,this.http=new E(this.baseUrl,"",!1,e.apiKey);let t=await this.fetchModels();this.modelId=t[0]?.id||"",this.conversationId="00000000-0000-0000-0000-000000000000",this.settingsSheet=new u({onModelChange:r=>{this.modelId=r},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),t.length>0&&this.settingsSheet.mount(t,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let n=()=>this.gameId,i=()=>this.conversationId,s=()=>this.modelId;this.chat=new v(this.http,n,i,s,!0,void 0),this.characters=new f(this.http,i,!0),this.relationships=new b(this.http,i,!0),this.inventory=new w(this.http,i,!0),this.world=new y(this.http,i,!0),this.player=new C(this.http,i,!0),this.custom=new x(this.http,i,!0),this.initialized=!0}};async function V(d){let e=new P;return d?.dev?await e.initDev(d.dev):await e.init(),e}function M(d){return typeof d=="object"&&d!==null&&"value"in d&&"type"in d&&(d.type==="number"||d.type==="text")}function z(d){return M(d)?d.value:d}export{c as StorviaError,P as StorviaSDK,V as createStorviaSDK,z as extractFieldValue,M as isRichFieldValue};
|
package/dist/index.umd.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var StorviaSDK=(()=>{var
|
|
2
|
-
`);for(let P of I){if(!P.startsWith("data: "))continue;let
|
|
1
|
+
"use strict";var StorviaSDK=(()=>{var R=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var A=Object.prototype.hasOwnProperty;var B=(a,e)=>{for(var t in e)R(a,t,{get:e[t],enumerable:!0})},U=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of H(e))!A.call(a,i)&&i!==t&&R(a,i,{get:()=>e[i],enumerable:!(n=D(e,i))||n.enumerable});return a};var F=a=>U(R({},"__esModule",{value:!0}),a);var Q={};B(Q,{StorviaError:()=>c,StorviaSDK:()=>S,createStorviaSDK:()=>O,extractFieldValue:()=>L,isRichFieldValue:()=>_});var c=class extends Error{constructor(e,t){super(t),this.name="StorviaError",this.code=e}};var E=class{constructor(e,t,n=!1,i=""){this.baseUrl=e,this.token=t,this.debug=n,this.devApiKey=i}setToken(e){this.token=e}setDebug(e){this.debug=e}buildHeaders(){let e={"Content-Type":"application/json"};return this.token&&(e.Authorization=`Bearer ${this.token}`),this.devApiKey&&(e["x-api-key"]=this.devApiKey),e}log(e,t,n,i,s){if(!this.debug)return;let r="%c[Storvia SDK]",o="color: #6366f1; font-weight: bold";s?(console.groupCollapsed(`${r} %c${e} ${t} %c\u2717`,o,"color: #e0e0e0","color: #ef4444"),n&&console.log("Request:",n),console.error("Error:",s),console.groupEnd()):(console.groupCollapsed(`${r} %c${e} ${t} %c\u2713`,o,"color: #e0e0e0","color: #22c55e"),n&&console.log("Request:",n),i!==void 0&&console.log("Response:",i),console.groupEnd())}async get(e,t){let n=new URL(`${this.baseUrl}${e}`);t&&Object.entries(t).forEach(([i,s])=>n.searchParams.set(i,s));try{let i=await fetch(n.toString(),{method:"GET",headers:this.buildHeaders()}),s=await this.handleResponse(i);return this.log("GET",e,t,s),s}catch(i){throw this.log("GET",e,t,void 0,i),i}}async post(e,t){try{let n=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0}),i=await this.handleResponse(n);return this.log("POST",e,t,i),i}catch(n){throw this.log("POST",e,t,void 0,n),n}}async patch(e,t){try{let n=await fetch(`${this.baseUrl}${e}`,{method:"PATCH",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0}),i=await this.handleResponse(n);return this.log("PATCH",e,t,i),i}catch(n){throw this.log("PATCH",e,t,void 0,n),n}}async delete(e){try{let t=await fetch(`${this.baseUrl}${e}`,{method:"DELETE",headers:this.buildHeaders()}),n=await this.handleResponse(t);return this.log("DELETE",e,void 0,n),n}catch(t){throw this.log("DELETE",e,void 0,void 0,t),t}}async stream(e,t,n,i){this.log("STREAM",e,t);let s=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify(t)});if(!s.ok){let d=await s.json().catch(()=>({})),m=new c(d.code||"INTERNAL_ERROR",d.message||`HTTP ${s.status}`);throw this.log("STREAM",e,t,void 0,m),m}let r=s.body?.getReader();if(!r)throw new c("INTERNAL_ERROR","No response body for stream");let o=new TextDecoder,l="",h="";for(;;){let{done:d,value:m}=await r.read();if(d)break;let I=o.decode(m,{stream:!0}).split(`
|
|
2
|
+
`);for(let P of I){if(!P.startsWith("data: "))continue;let N=P.slice(6);if(N==="[DONE]"){this.debug&&this.log("STREAM",e+" [done]",void 0,{id:l,contentLength:h.length}),i(l);return}try{let g=JSON.parse(N);g.type==="done"&&g.id?l=g.id:g.content&&(h+=g.content,n(g.content))}catch{}}}l&&i(l)}async handleResponse(e){if(!e.ok){let n={};try{n=await e.json()}catch{}let i={401:"UNAUTHORIZED",402:"INSUFFICIENT_BALANCE",404:"GAME_NOT_FOUND",429:"RATE_LIMITED"},s=n.code||i[e.status]||"INTERNAL_ERROR";throw new c(s,n.message||`HTTP ${e.status}`)}let t=await e.json();return t&&typeof t=="object"&&"data"in t?t.data:t}};var j=[{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"}],M=[{value:"low",label:"\u7B80\u77ED"},{value:"medium",label:"\u9002\u4E2D"},{value:"high",label:"\u8BE6\u7EC6"}],V=`
|
|
3
3
|
:host {
|
|
4
4
|
position: fixed;
|
|
5
5
|
bottom: 20px;
|
|
@@ -427,6 +427,6 @@
|
|
|
427
427
|
to { transform: rotate(360deg); }
|
|
428
428
|
}
|
|
429
429
|
.spin { animation: spin 0.8s linear infinite; }
|
|
430
|
-
`,z='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>',G='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>',F='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',V='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',W='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>',u=class{constructor(e){this.selectedModelId="";this.models=[];this.modelPanel=null;this.settings={temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.hasWorldUpdate=!1;this.fabDot=null;this.syncHint=null;this.displayMode="phone";this.displayModeBtns=[];this.tempValueEl=null;this.tempSlider=null;this.segmentBtns=[];this.langSelect=null;this.noteInput=null;this.noteCounter=null;this.saveBtn=null;this.syncBtn=null;this.syncState="idle";this.panel=null;this.callbacks=e,this.host=document.createElement("div"),this.host.id="storvia-settings",this.shadowRoot=this.host.attachShadow({mode:"closed"})}mount(e,t,n,i=!1){this.models=e,this.selectedModelId=t,this.settings={...n},this.hasWorldUpdate=i;try{let s=localStorage.getItem("storvia_display_mode");(s==="phone"||s==="desktop")&&(this.displayMode=s)}catch{}document.body.appendChild(this.host),this.render()}unmount(){this.host.remove()}getSelectedModelId(){return this.selectedModelId}getSettings(){return{...this.settings}}render(){let e=document.createElement("style");e.textContent=j;let t=document.createElement("div"),n=document.createElement("div");n.className="fab-wrap";let i=document.createElement("button");i.className="fab",i.innerHTML=z,i.title="\u6E38\u620F\u8BBE\u7F6E";let s=document.createElement("div");s.className=`fab-dot${this.hasWorldUpdate?" visible":""}`,this.fabDot=s,n.appendChild(i),n.appendChild(s);let a=document.createElement("div");a.className="panel",this.panel=a;let o=document.createElement("div");o.className="panel-header";let l=document.createElement("div");l.className="panel-title",l.textContent="\u6E38\u620F\u8BBE\u7F6E";let h=document.createElement("button");h.className="close-btn",h.innerHTML="\u2715",h.addEventListener("click",()=>a.classList.remove("open")),o.appendChild(l),o.appendChild(h),a.appendChild(o);let r=document.createElement("div");r.className="panel-body",this.models.length>0&&(r.appendChild(this.buildModelSection()),r.appendChild(this.makeDivider())),r.appendChild(this.buildTemperatureSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildReplyLengthSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildReplyLanguageSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildNoteSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildDisplayModeSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildSyncSection());let m=document.createElement("div");m.className="save-row";let p=document.createElement("button");p.className="save-btn",p.textContent="\u4FDD\u5B58",this.saveBtn=p,p.addEventListener("click",()=>this.handleSave()),m.appendChild(p),r.appendChild(m),a.appendChild(r),i.addEventListener("click",()=>a.classList.toggle("open")),document.addEventListener("click",I=>{this.host.contains(I.target)||a.classList.remove("open")}),t.appendChild(a),t.appendChild(n),this.shadowRoot.appendChild(e),this.shadowRoot.appendChild(t)}buildModelSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="AI \u6A21\u578B",e.appendChild(t);let n=document.createElement("div");return n.className="model-list",this.modelPanel=n,this.models.forEach(i=>{let s=document.createElement("button");s.className=`model-option${i.id===this.selectedModelId?" active":""}`,s.innerHTML=`<span class="dot"></span><span>${i.name}</span>`,s.addEventListener("click",()=>{this.selectedModelId=i.id,this.callbacks.onModelChange(i.id);try{localStorage.setItem("storvia_model_id",i.id)}catch{}this.updateModelActive()}),n.appendChild(s)}),e.appendChild(n),e}buildTemperatureSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label";let n=document.createElement("span");n.textContent="\u6E29\u5EA6";let i=document.createElement("span");i.className="value",i.textContent=this.settings.temperature.toFixed(1),this.tempValueEl=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("div");s.className="section-desc",s.textContent="\u66F4\u4F4E\u7684\u6E29\u5EA6\u4F1A\u8BA9 AI \u56DE\u590D\u66F4\u7A33\u5B9A\u3001\u7406\u667A\uFF1B\u66F4\u9AD8\u7684\u6E29\u5EA6\u4F1A\u8BA9 AI \u7684\u56DE\u590D\u66F4\u5177\u591A\u6837\u6027\u548C\u968F\u673A\u6027",e.appendChild(s);let a=document.createElement("div");a.className="slider-wrap";let o=document.createElement("input");o.type="range",o.className="slider",o.min="0",o.max="2",o.step="0.1",o.value=String(this.settings.temperature),this.tempSlider=o,o.addEventListener("input",()=>{let h=parseFloat(o.value);this.settings.temperature=h,this.tempValueEl&&(this.tempValueEl.textContent=h.toFixed(1))}),a.appendChild(o);let l=document.createElement("div");return l.className="slider-labels",l.innerHTML="<span>\u7CBE\u786E</span><span>\u521B\u610F</span>",a.appendChild(l),e.appendChild(a),e}buildReplyLengthSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u56DE\u590D\u957F\u5EA6",e.appendChild(t);let n=document.createElement("div");return n.className="segment",this.segmentBtns=[],M.forEach(i=>{let s=document.createElement("button");s.className=`segment-btn${i.value===this.settings.reply_length?" active":""}`,s.textContent=i.label,s.addEventListener("click",()=>{this.settings.reply_length=i.value,this.segmentBtns.forEach((a,o)=>{a.classList.toggle("active",M[o].value===i.value)})}),this.segmentBtns.push(s),n.appendChild(s)}),e.appendChild(n),e}buildReplyLanguageSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u56DE\u590D\u8BED\u8A00",e.appendChild(t);let n=document.createElement("div");n.className="select-wrap";let i=document.createElement("select");i.className="select",this.langSelect=i,U.forEach(a=>{let o=document.createElement("option");o.value=a.value,o.textContent=a.label,a.value===this.settings.reply_language&&(o.selected=!0),i.appendChild(o)}),i.addEventListener("change",()=>{this.settings.reply_language=i.value});let s=document.createElement("span");return s.className="select-arrow",s.textContent="\u25BE",n.appendChild(i),n.appendChild(s),e.appendChild(n),e}buildNoteSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label";let n=document.createElement("span");n.textContent="\u5907\u6CE8";let i=document.createElement("span");i.textContent=`${this.settings.player_note.length}/50`,this.noteCounter=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("div");s.className="section-desc",s.textContent="\u5199\u4E0B\u4F60\u5BF9\u8FD9\u4E2A\u6E38\u620F\u7684\u5907\u6CE8\uFF0C\u4F1A\u663E\u793A\u5728\u5B58\u6863\u5217\u8868",e.appendChild(s);let a=document.createElement("div");a.className="note-wrap";let o=document.createElement("textarea");return o.className="note-input",o.placeholder="\u5907\u6CE8",o.maxLength=50,o.value=this.settings.player_note,this.noteInput=o,o.addEventListener("input",()=>{this.settings.player_note=o.value,this.noteCounter&&(this.noteCounter.textContent=`${o.value.length}/50`)}),a.appendChild(o),e.appendChild(a),e}buildDisplayModeSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u663E\u793A\u6A21\u5F0F",e.appendChild(t);let n=document.createElement("div");n.className="section-desc",n.textContent="\u7535\u8111\u6A21\u5F0F\u4F1A\u81EA\u52A8\u6A2A\u5C4F\u663E\u793A",e.appendChild(n);let i=document.createElement("div");i.className="segment",this.displayModeBtns=[];let s=[{value:"phone",label:"\u624B\u673A"},{value:"desktop",label:"\u7535\u8111"}];return s.forEach(a=>{let o=document.createElement("button");o.className=`segment-btn${a.value===this.displayMode?" active":""}`,o.textContent=a.label,o.addEventListener("click",()=>{this.displayMode=a.value;try{localStorage.setItem("storvia_display_mode",a.value)}catch{}this.displayModeBtns.forEach((l,h)=>{l.classList.toggle("active",s[h].value===a.value)});try{window.parent.postMessage({type:"storvia-orientation",mode:a.value==="desktop"?"landscape":"portrait"},"*")}catch{}}),this.displayModeBtns.push(o),i.appendChild(o)}),e.appendChild(i),e}buildSyncSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u540C\u6B65\u6E38\u620F\u8BBE\u5B9A",e.appendChild(t);let n=document.createElement("div");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("div");i.className="sync-desc",i.textContent="\u5982\u679C\u6E38\u620F\u4F5C\u8005\u66F4\u65B0\u4E86\u5185\u5BB9\uFF0C\u70B9\u51FB\u6B64\u6309\u94AE\u53EF\u5C06\u6700\u65B0\u7684\u6E38\u620F\u8BBE\u5B9A\u548C\u5F00\u5E55\u5C0F\u5267\u573A\u540C\u6B65\u5230\u5F53\u524D\u5BF9\u8BDD",e.appendChild(i);let s=document.createElement("button");return s.className="sync-btn",this.syncBtn=s,this.renderSyncBtn(),s.addEventListener("click",async()=>{if(this.syncState!=="loading"){this.setSyncState("loading");try{await this.callbacks.onSync(),this.setSyncState("success"),this.hasWorldUpdate=!1,this.fabDot&&this.fabDot.classList.remove("visible"),this.syncHint&&this.syncHint.classList.remove("visible"),setTimeout(()=>this.setSyncState("idle"),3e3)}catch{this.setSyncState("error"),setTimeout(()=>this.setSyncState("idle"),4e3)}}}),e.appendChild(s),e}makeDivider(){let e=document.createElement("div");return e.className="divider",e}updateModelActive(){this.modelPanel&&this.modelPanel.querySelectorAll(".model-option").forEach((e,t)=>{e.classList.toggle("active",this.models[t].id===this.selectedModelId)})}setSyncState(e){this.syncState=e,this.renderSyncBtn()}renderSyncBtn(){if(!this.syncBtn)return;let e=this.syncState,t={idle:G,loading:F,success:V,error:W},n={idle:"\u540C\u6B65\u6700\u65B0\u8BBE\u5B9A",loading:"\u540C\u6B65\u4E2D...",success:"\u5DF2\u540C\u6B65",error:"\u540C\u6B65\u5931\u8D25"};this.syncBtn.className=`sync-btn${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.textContent="\u4FDD\u5B58\u4E2D...";try{await this.callbacks.onSettingsChange({temperature:this.settings.temperature,reply_length:this.settings.reply_length,reply_language:this.settings.reply_language,player_note:this.settings.player_note}),this.saveBtn.textContent="\u5DF2\u4FDD\u5B58",this.saveBtn.classList.add("saved"),setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.classList.remove("saved"),this.saveBtn.disabled=!1)},2e3)}catch{this.saveBtn.textContent="\u4FDD\u5B58\u5931\u8D25",setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1)},2e3)}}}};var v=class{constructor(e,t,n,i,s=!1,a){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=i;this.isPreview=s;this.previewConfig=a}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_context:e.context,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/chat",t)}async save(e){return this.isPreview?{id:`preview-${Date.now()}`}:this.http.post("/messages/save",{conversation_id:this.getConversationId(),role:e.role,content:e.content,topic:e.topic})}async generate(e){if(this.isPreview)return this.sendPreview({message:"",topic:e.topic,context:(e.context||"")+`
|
|
431
|
-
[\u6307\u4EE4] \u8BF7\u76F4\u63A5\u751F\u6210\u56DE\u590D\uFF0C\u65E0\u9700\u7528\u6237\u8F93\u5165`,stream:e.stream,onChunk:e.onChunk,onDone:e.onDone});let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,scene_context:e.context,stream:e.stream??!1,save:e.save??!0};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/generate",t)}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,context:e.context,prompt_config:this.previewConfig||{},history_messages:[]};if(e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}let n="";return await this.http.stream("/preview",t,i=>{n+=i},()=>{}),{id:"",content:n}}};var R=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){return this.isPreview?{...this.mem[e]||{}}:this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,t)}},f=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];this.state=new R(e,t,n)}async list(){return this.isPreview?this.mem.map(e=>({name:e.name,avatar:e.avatar})):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:t?.name||e,avatar:t?.avatar}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async add(e){if(this.isPreview){this.mem.push(e);return}await this.http.post(`/conversations/${this.getConversationId()}/characters`,e)}async update(e,t){if(this.isPreview){let n=this.mem.find(i=>i.name===e);n&&Object.assign(n,t);return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`,t)}async remove(e){if(this.isPreview){this.mem=this.mem.filter(t=>t.name!==e);return}await this.http.delete(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async detail(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:e,avatar:t?.avatar,state:await this.state.get(e)}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/detail`)}};var w=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(){return this.isPreview?[...this.mem]:this.http.get(`/conversations/${this.getConversationId()}/relationships`)}async get(e,t){if(this.isPreview){let n=this.mem.find(i=>i.from===e&&i.to===t);if(n)return{...n};throw new Error("Relationship not found")}return this.http.get(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/relationships`,e)}async update(e,t,n){if(this.isPreview){let i=this.mem.find(s=>s.from===e&&s.to===t);i?Object.assign(i,n):this.mem.push({from:e,to:t,...n});return}await this.http.patch(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,n)}async remove(e,t){if(this.isPreview){this.mem=this.mem.filter(n=>!(n.from===e&&n.to===t));return}await this.http.delete(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var b=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(e){if(this.isPreview)return e?this.mem.filter(n=>n.group===e):[...this.mem];let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/inventory`,t)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/inventory`,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()}/inventory/${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()}/inventory/${encodeURIComponent(e)}`)}};var y=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(){return this.isPreview?{...this.mem}:this.http.get(`/conversations/${this.getConversationId()}/world`)}async update(e){if(this.isPreview){Object.assign(this.mem,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/world`,e)}};var T=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e?{...this.mem[e]||{}}:{...this.mem};let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/player/state`,t)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/player/state`,{group:e,values:t})}},C=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};this.state=new T(e,t,n)}async get(){return this.isPreview?{...this.memPersona}:this.http.get(`/conversations/${this.getConversationId()}/player`)}};var x=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e!==void 0?this.mem[e]:{...this.mem};let t=await this.http.get(`/conversations/${this.getConversationId()}/custom`);return e!==void 0?t[e]:t}async set(e){if(this.isPreview){for(let[t,n]of Object.entries(e))typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof this.mem[t]=="object"&&this.mem[t]!==null?this.mem[t]={...this.mem[t],...n}:this.mem[t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom`,e)}async delete(e){if(this.isPreview){delete this.mem[e];return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}`)}async setGroupField(e,t,n){if(this.isPreview){(!this.mem[e]||typeof this.mem[e]!="object")&&(this.mem[e]={}),this.mem[e][t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{value:n})}async deleteGroupField(e,t){if(this.isPreview){if(typeof this.mem[e]=="object"&&this.mem[e]!==null){let n=this.mem[e];delete n[t],Object.keys(n).length===0&&delete this.mem[e]}return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var N="/functions/v1/world-engine/v1",J="https://api.storvia.ai";function Y(){return window.__STORVIA__||{}}function Z(d=5e3){let e=Y();return e.apiBase?Promise.resolve(e):new Promise((t,n)=>{let i=setTimeout(()=>{window.removeEventListener("message",s),n(new c("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},d);function s(a){let o=null;if(a.data?.type==="storvia-init"&&a.data.apiBase?o={apiBase:a.data.apiBase,gameId:a.data.gameId,accessToken:a.data.accessToken}:a.data?.type==="storvia-preview-init"&&a.data.config&&(o=a.data.config),o&&o.apiBase){clearTimeout(i),window.removeEventListener("message",s);let l=window;l.__STORVIA__=o,t(o)}}window.addEventListener("message",s)})}var E=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){if(this.initialized)return;let e=await Z(),t=e.apiBase;if(!t)throw new c("NOT_INITIALIZED","window.__STORVIA__.apiBase is not set. The platform must inject it before SDK init.");if(this.baseUrl=`${t}${N}`,this.isPreview=!!e.preview,this.previewConfig=e.previewConfig,!e.gameId)throw new c("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 c("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 S(this.baseUrl,this.accessToken,!!e.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let r=await this.fetchModels();this.modelId=e.selectedModelId||r[0]?.id||"",this.settingsSheet=new u({onModelChange:P=>{this.modelId=P},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),r.length>0&&this.settingsSheet.mount(r,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let m=()=>this.gameId,p=()=>this.conversationId,I=()=>this.modelId;this.chat=new v(this.http,m,p,I,!0,this.previewConfig),this.characters=new f(this.http,p,!0),this.relationships=new w(this.http,p,!0),this.inventory=new b(this.http,p,!0),this.world=new y(this.http,p,!0),this.player=new C(this.http,p,!0),this.custom=new x(this.http,p,!0),this.initialized=!0,this.listenForPreviewMessages();return}let[n,i]=await Promise.all([this.authenticate(),this.fetchModels()]);this.conversationId=n.conversationId;let s=this.getSavedModelId();this.modelId=s&&i.some(r=>r.id===s)?s:i[0]?.id||"";let a=n.settings||{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.settingsSheet=new u({onModelChange:r=>{this.modelId=r},onSettingsChange:r=>this.saveSettings(r),onSync:()=>this.syncSettings()}),this.settingsSheet.mount(i,this.modelId,a,n.hasWorldUpdate??!1);let o=()=>this.gameId,l=()=>this.conversationId,h=()=>this.modelId;this.chat=new v(this.http,o,l,h),this.characters=new f(this.http,l),this.relationships=new w(this.http,l),this.inventory=new b(this.http,l),this.world=new y(this.http,l),this.player=new C(this.http,l),this.custom=new x(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)))})}async saveSettings(e){await this.http.patch("/settings",{conversation_id:this.conversationId,...e})}async syncSettings(){await this.http.post("/sync",{conversation_id:this.conversationId})}async fetchModels(){try{return await this.http.get("/models")}catch{}return[]}async authenticate(){let e=await fetch(`${this.baseUrl}/auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.accessToken}`},body:JSON.stringify({game_id:this.gameId})});if(!e.ok)throw e.status===401?new c("UNAUTHORIZED","User not authenticated"):e.status===404?new c("GAME_NOT_FOUND","Game not found or not published"):new c("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=`${J}${N}`,this.gameId=e.gameId,this.isPreview=!0,this.http=new S(this.baseUrl,"",!1,e.apiKey);let t=await this.fetchModels();this.modelId=t[0]?.id||"",this.conversationId="00000000-0000-0000-0000-000000000000",this.settingsSheet=new u({onModelChange:a=>{this.modelId=a},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),t.length>0&&this.settingsSheet.mount(t,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let n=()=>this.gameId,i=()=>this.conversationId,s=()=>this.modelId;this.chat=new v(this.http,n,i,s,!0,void 0),this.characters=new f(this.http,i,!0),this.relationships=new w(this.http,i,!0),this.inventory=new b(this.http,i,!0),this.world=new y(this.http,i,!0),this.player=new C(this.http,i,!0),this.custom=new x(this.http,i,!0),this.initialized=!0}};async function $(d){let e=new E;return d?.dev?await e.initDev(d.dev):await e.init(),e}return D(K);})();
|
|
430
|
+
`,z='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>',G='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>',W='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',Z='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',J='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>',u=class{constructor(e){this.selectedModelId="";this.models=[];this.modelPanel=null;this.settings={temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.hasWorldUpdate=!1;this.fabDot=null;this.syncHint=null;this.displayMode="phone";this.displayModeBtns=[];this.tempValueEl=null;this.tempSlider=null;this.segmentBtns=[];this.langSelect=null;this.noteInput=null;this.noteCounter=null;this.saveBtn=null;this.syncBtn=null;this.syncState="idle";this.panel=null;this.callbacks=e,this.host=document.createElement("div"),this.host.id="storvia-settings",this.shadowRoot=this.host.attachShadow({mode:"closed"})}mount(e,t,n,i=!1){this.models=e,this.selectedModelId=t,this.settings={...n},this.hasWorldUpdate=i;try{let s=localStorage.getItem("storvia_display_mode");(s==="phone"||s==="desktop")&&(this.displayMode=s)}catch{}document.body.appendChild(this.host),this.render()}unmount(){this.host.remove()}getSelectedModelId(){return this.selectedModelId}getSettings(){return{...this.settings}}render(){let e=document.createElement("style");e.textContent=V;let t=document.createElement("div"),n=document.createElement("div");n.className="fab-wrap";let i=document.createElement("button");i.className="fab",i.innerHTML=z,i.title="\u6E38\u620F\u8BBE\u7F6E";let s=document.createElement("div");s.className=`fab-dot${this.hasWorldUpdate?" visible":""}`,this.fabDot=s,n.appendChild(i),n.appendChild(s);let r=document.createElement("div");r.className="panel",this.panel=r;let o=document.createElement("div");o.className="panel-header";let l=document.createElement("div");l.className="panel-title",l.textContent="\u6E38\u620F\u8BBE\u7F6E";let h=document.createElement("button");h.className="close-btn",h.innerHTML="\u2715",h.addEventListener("click",()=>r.classList.remove("open")),o.appendChild(l),o.appendChild(h),r.appendChild(o);let d=document.createElement("div");d.className="panel-body",this.models.length>0&&(d.appendChild(this.buildModelSection()),d.appendChild(this.makeDivider())),d.appendChild(this.buildTemperatureSection()),d.appendChild(this.makeDivider()),d.appendChild(this.buildReplyLengthSection()),d.appendChild(this.makeDivider()),d.appendChild(this.buildReplyLanguageSection()),d.appendChild(this.makeDivider()),d.appendChild(this.buildNoteSection()),d.appendChild(this.makeDivider()),d.appendChild(this.buildDisplayModeSection()),d.appendChild(this.makeDivider()),d.appendChild(this.buildSyncSection());let m=document.createElement("div");m.className="save-row";let p=document.createElement("button");p.className="save-btn",p.textContent="\u4FDD\u5B58",this.saveBtn=p,p.addEventListener("click",()=>this.handleSave()),m.appendChild(p),d.appendChild(m),r.appendChild(d),i.addEventListener("click",()=>r.classList.toggle("open")),document.addEventListener("click",I=>{this.host.contains(I.target)||r.classList.remove("open")}),t.appendChild(r),t.appendChild(n),this.shadowRoot.appendChild(e),this.shadowRoot.appendChild(t)}buildModelSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="AI \u6A21\u578B",e.appendChild(t);let n=document.createElement("div");return n.className="model-list",this.modelPanel=n,this.models.forEach(i=>{let s=document.createElement("button");s.className=`model-option${i.id===this.selectedModelId?" active":""}`,s.innerHTML=`<span class="dot"></span><span>${i.name}</span>`,s.addEventListener("click",()=>{this.selectedModelId=i.id,this.callbacks.onModelChange(i.id);try{localStorage.setItem("storvia_model_id",i.id)}catch{}this.updateModelActive()}),n.appendChild(s)}),e.appendChild(n),e}buildTemperatureSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label";let n=document.createElement("span");n.textContent="\u6E29\u5EA6";let i=document.createElement("span");i.className="value",i.textContent=this.settings.temperature.toFixed(1),this.tempValueEl=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("div");s.className="section-desc",s.textContent="\u66F4\u4F4E\u7684\u6E29\u5EA6\u4F1A\u8BA9 AI \u56DE\u590D\u66F4\u7A33\u5B9A\u3001\u7406\u667A\uFF1B\u66F4\u9AD8\u7684\u6E29\u5EA6\u4F1A\u8BA9 AI \u7684\u56DE\u590D\u66F4\u5177\u591A\u6837\u6027\u548C\u968F\u673A\u6027",e.appendChild(s);let r=document.createElement("div");r.className="slider-wrap";let o=document.createElement("input");o.type="range",o.className="slider",o.min="0",o.max="2",o.step="0.1",o.value=String(this.settings.temperature),this.tempSlider=o,o.addEventListener("input",()=>{let h=parseFloat(o.value);this.settings.temperature=h,this.tempValueEl&&(this.tempValueEl.textContent=h.toFixed(1))}),r.appendChild(o);let l=document.createElement("div");return l.className="slider-labels",l.innerHTML="<span>\u7CBE\u786E</span><span>\u521B\u610F</span>",r.appendChild(l),e.appendChild(r),e}buildReplyLengthSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u56DE\u590D\u957F\u5EA6",e.appendChild(t);let n=document.createElement("div");return n.className="segment",this.segmentBtns=[],M.forEach(i=>{let s=document.createElement("button");s.className=`segment-btn${i.value===this.settings.reply_length?" active":""}`,s.textContent=i.label,s.addEventListener("click",()=>{this.settings.reply_length=i.value,this.segmentBtns.forEach((r,o)=>{r.classList.toggle("active",M[o].value===i.value)})}),this.segmentBtns.push(s),n.appendChild(s)}),e.appendChild(n),e}buildReplyLanguageSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u56DE\u590D\u8BED\u8A00",e.appendChild(t);let n=document.createElement("div");n.className="select-wrap";let i=document.createElement("select");i.className="select",this.langSelect=i,j.forEach(r=>{let o=document.createElement("option");o.value=r.value,o.textContent=r.label,r.value===this.settings.reply_language&&(o.selected=!0),i.appendChild(o)}),i.addEventListener("change",()=>{this.settings.reply_language=i.value});let s=document.createElement("span");return s.className="select-arrow",s.textContent="\u25BE",n.appendChild(i),n.appendChild(s),e.appendChild(n),e}buildNoteSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label";let n=document.createElement("span");n.textContent="\u5907\u6CE8";let i=document.createElement("span");i.textContent=`${this.settings.player_note.length}/50`,this.noteCounter=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("div");s.className="section-desc",s.textContent="\u5199\u4E0B\u4F60\u5BF9\u8FD9\u4E2A\u6E38\u620F\u7684\u5907\u6CE8\uFF0C\u4F1A\u663E\u793A\u5728\u5B58\u6863\u5217\u8868",e.appendChild(s);let r=document.createElement("div");r.className="note-wrap";let o=document.createElement("textarea");return o.className="note-input",o.placeholder="\u5907\u6CE8",o.maxLength=50,o.value=this.settings.player_note,this.noteInput=o,o.addEventListener("input",()=>{this.settings.player_note=o.value,this.noteCounter&&(this.noteCounter.textContent=`${o.value.length}/50`)}),r.appendChild(o),e.appendChild(r),e}buildDisplayModeSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u663E\u793A\u6A21\u5F0F",e.appendChild(t);let n=document.createElement("div");n.className="section-desc",n.textContent="\u7535\u8111\u6A21\u5F0F\u4F1A\u81EA\u52A8\u6A2A\u5C4F\u663E\u793A",e.appendChild(n);let i=document.createElement("div");i.className="segment",this.displayModeBtns=[];let s=[{value:"phone",label:"\u624B\u673A"},{value:"desktop",label:"\u7535\u8111"}];return s.forEach(r=>{let o=document.createElement("button");o.className=`segment-btn${r.value===this.displayMode?" active":""}`,o.textContent=r.label,o.addEventListener("click",()=>{this.displayMode=r.value;try{localStorage.setItem("storvia_display_mode",r.value)}catch{}this.displayModeBtns.forEach((l,h)=>{l.classList.toggle("active",s[h].value===r.value)});try{window.parent.postMessage({type:"storvia-orientation",mode:r.value==="desktop"?"landscape":"portrait"},"*")}catch{}}),this.displayModeBtns.push(o),i.appendChild(o)}),e.appendChild(i),e}buildSyncSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u540C\u6B65\u6E38\u620F\u8BBE\u5B9A",e.appendChild(t);let n=document.createElement("div");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("div");i.className="sync-desc",i.textContent="\u5982\u679C\u6E38\u620F\u4F5C\u8005\u66F4\u65B0\u4E86\u5185\u5BB9\uFF0C\u70B9\u51FB\u6B64\u6309\u94AE\u53EF\u5C06\u6700\u65B0\u7684\u6E38\u620F\u8BBE\u5B9A\u548C\u5F00\u5E55\u5C0F\u5267\u573A\u540C\u6B65\u5230\u5F53\u524D\u5BF9\u8BDD",e.appendChild(i);let s=document.createElement("button");return s.className="sync-btn",this.syncBtn=s,this.renderSyncBtn(),s.addEventListener("click",async()=>{if(this.syncState!=="loading"){this.setSyncState("loading");try{await this.callbacks.onSync(),this.setSyncState("success"),this.hasWorldUpdate=!1,this.fabDot&&this.fabDot.classList.remove("visible"),this.syncHint&&this.syncHint.classList.remove("visible"),setTimeout(()=>this.setSyncState("idle"),3e3)}catch{this.setSyncState("error"),setTimeout(()=>this.setSyncState("idle"),4e3)}}}),e.appendChild(s),e}makeDivider(){let e=document.createElement("div");return e.className="divider",e}updateModelActive(){this.modelPanel&&this.modelPanel.querySelectorAll(".model-option").forEach((e,t)=>{e.classList.toggle("active",this.models[t].id===this.selectedModelId)})}setSyncState(e){this.syncState=e,this.renderSyncBtn()}renderSyncBtn(){if(!this.syncBtn)return;let e=this.syncState,t={idle:G,loading:W,success:Z,error:J},n={idle:"\u540C\u6B65\u6700\u65B0\u8BBE\u5B9A",loading:"\u540C\u6B65\u4E2D...",success:"\u5DF2\u540C\u6B65",error:"\u540C\u6B65\u5931\u8D25"};this.syncBtn.className=`sync-btn${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.textContent="\u4FDD\u5B58\u4E2D...";try{await this.callbacks.onSettingsChange({temperature:this.settings.temperature,reply_length:this.settings.reply_length,reply_language:this.settings.reply_language,player_note:this.settings.player_note}),this.saveBtn.textContent="\u5DF2\u4FDD\u5B58",this.saveBtn.classList.add("saved"),setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.classList.remove("saved"),this.saveBtn.disabled=!1)},2e3)}catch{this.saveBtn.textContent="\u4FDD\u5B58\u5931\u8D25",setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1)},2e3)}}}};var v=class{constructor(e,t,n,i,s=!1,r){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=i;this.isPreview=s;this.previewConfig=r}updatePreviewConfig(e){this.previewConfig=e}async send(e){if(this.isPreview)return this.sendPreview(e);let t={game_id:this.getGameId(),conversation_id:this.getConversationId(),model_id:this.getModelId(),message:e.message,topic:e.topic,scene_context:e.context,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/chat",t)}async save(e){return this.isPreview?{id:`preview-${Date.now()}`}:this.http.post("/messages/save",{conversation_id:this.getConversationId(),role:e.role,content:e.content,topic:e.topic})}async generate(e){if(this.isPreview)return this.sendPreview({message:"",topic:e.topic,context:(e.context||"")+`
|
|
431
|
+
[\u6307\u4EE4] \u8BF7\u76F4\u63A5\u751F\u6210\u56DE\u590D\uFF0C\u65E0\u9700\u7528\u6237\u8F93\u5165`,stream:e.stream,onChunk:e.onChunk,onDone:e.onDone});let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,scene_context:e.context,stream:e.stream??!1,save:e.save??!0};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/generate",t)}async retry(e={}){if(this.isPreview)throw new Error("Retry is not supported in preview mode");let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,scene_context:e.context,stream:e.stream??!1};if(e.stream){await this.http.stream("/retry",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/retry",t)}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,context:e.context,prompt_config:this.previewConfig||{},history_messages:[]};if(e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}let n="";return await this.http.stream("/preview",t,i=>{n+=i},()=>{}),{id:"",content:n}}};var k=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){return this.isPreview?{...this.mem[e]||{}}:this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,t)}},f=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];this.state=new k(e,t,n)}async list(){return this.isPreview?this.mem.map(e=>({name:e.name,avatar:e.avatar})):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:t?.name||e,avatar:t?.avatar}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async add(e){if(this.isPreview){this.mem.push(e);return}await this.http.post(`/conversations/${this.getConversationId()}/characters`,e)}async update(e,t){if(this.isPreview){let n=this.mem.find(i=>i.name===e);n&&Object.assign(n,t);return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`,t)}async remove(e){if(this.isPreview){this.mem=this.mem.filter(t=>t.name!==e);return}await this.http.delete(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async detail(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:e,avatar:t?.avatar,state:await this.state.get(e)}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/detail`)}};var b=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(){return this.isPreview?[...this.mem]:this.http.get(`/conversations/${this.getConversationId()}/relationships`)}async get(e,t){if(this.isPreview){let n=this.mem.find(i=>i.from===e&&i.to===t);if(n)return{...n};throw new Error("Relationship not found")}return this.http.get(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/relationships`,e)}async update(e,t,n){if(this.isPreview){let i=this.mem.find(s=>s.from===e&&s.to===t);i?Object.assign(i,n):this.mem.push({from:e,to:t,...n});return}await this.http.patch(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,n)}async remove(e,t){if(this.isPreview){this.mem=this.mem.filter(n=>!(n.from===e&&n.to===t));return}await this.http.delete(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var w=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(e){if(this.isPreview)return e?this.mem.filter(n=>n.group===e):[...this.mem];let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/inventory`,t)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/inventory`,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()}/inventory/${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()}/inventory/${encodeURIComponent(e)}`)}};var y=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(){return this.isPreview?{...this.mem}:this.http.get(`/conversations/${this.getConversationId()}/world`)}async update(e){if(this.isPreview){Object.assign(this.mem,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/world`,e)}};var T=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e?{...this.mem[e]||{}}:{...this.mem};let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/player/state`,t)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/player/state`,{group:e,values:t})}},C=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};this.state=new T(e,t,n)}async get(){return this.isPreview?{...this.memPersona}:this.http.get(`/conversations/${this.getConversationId()}/player`)}async update(e){if(this.isPreview){Object.assign(this.memPersona,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/player`,e)}};var x=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e!==void 0?this.mem[e]:{...this.mem};let t=await this.http.get(`/conversations/${this.getConversationId()}/custom`);return e!==void 0?t[e]:t}async set(e){if(this.isPreview){for(let[t,n]of Object.entries(e))typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof this.mem[t]=="object"&&this.mem[t]!==null?this.mem[t]={...this.mem[t],...n}:this.mem[t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom`,e)}async delete(e){if(this.isPreview){delete this.mem[e];return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}`)}async setGroupField(e,t,n){if(this.isPreview){(!this.mem[e]||typeof this.mem[e]!="object")&&(this.mem[e]={}),this.mem[e][t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{value:n})}async deleteGroupField(e,t){if(this.isPreview){if(typeof this.mem[e]=="object"&&this.mem[e]!==null){let n=this.mem[e];delete n[t],Object.keys(n).length===0&&delete this.mem[e]}return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var $="/functions/v1/world-engine/v1",K="https://api.storvia.ai";function Y(){return window.__STORVIA__||{}}function q(a=5e3){let e=Y();return e.apiBase?Promise.resolve(e):new Promise((t,n)=>{let i=setTimeout(()=>{window.removeEventListener("message",s),n(new c("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},a);function s(r){let o=null;if(r.data?.type==="storvia-init"&&r.data.apiBase?o={apiBase:r.data.apiBase,gameId:r.data.gameId,accessToken:r.data.accessToken}:r.data?.type==="storvia-preview-init"&&r.data.config&&(o=r.data.config),o&&o.apiBase){clearTimeout(i),window.removeEventListener("message",s);let l=window;l.__STORVIA__=o,t(o)}}window.addEventListener("message",s)})}var S=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){if(this.initialized)return;let e=await q(),t=e.apiBase;if(!t)throw new c("NOT_INITIALIZED","window.__STORVIA__.apiBase is not set. The platform must inject it before SDK init.");if(this.baseUrl=`${t}${$}`,this.isPreview=!!e.preview,this.previewConfig=e.previewConfig,!e.gameId)throw new c("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 c("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 E(this.baseUrl,this.accessToken,!!e.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let d=await this.fetchModels();this.modelId=e.selectedModelId||d[0]?.id||"",this.settingsSheet=new u({onModelChange:P=>{this.modelId=P},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),d.length>0&&this.settingsSheet.mount(d,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let m=()=>this.gameId,p=()=>this.conversationId,I=()=>this.modelId;this.chat=new v(this.http,m,p,I,!0,this.previewConfig),this.characters=new f(this.http,p,!0),this.relationships=new b(this.http,p,!0),this.inventory=new w(this.http,p,!0),this.world=new y(this.http,p,!0),this.player=new C(this.http,p,!0),this.custom=new x(this.http,p,!0),this.initialized=!0,this.listenForPreviewMessages();return}let[n,i]=await Promise.all([this.authenticate(),this.fetchModels()]);this.conversationId=n.conversationId;let s=this.getSavedModelId();this.modelId=s&&i.some(d=>d.id===s)?s:i[0]?.id||"";let r=n.settings||{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.settingsSheet=new u({onModelChange:d=>{this.modelId=d},onSettingsChange:d=>this.saveSettings(d),onSync:()=>this.syncSettings()}),this.settingsSheet.mount(i,this.modelId,r,n.hasWorldUpdate??!1);let o=()=>this.gameId,l=()=>this.conversationId,h=()=>this.modelId;this.chat=new v(this.http,o,l,h),this.characters=new f(this.http,l),this.relationships=new b(this.http,l),this.inventory=new w(this.http,l),this.world=new y(this.http,l),this.player=new C(this.http,l),this.custom=new x(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)))})}async saveSettings(e){await this.http.patch("/settings",{conversation_id:this.conversationId,...e})}async syncSettings(){await this.http.post("/sync",{conversation_id:this.conversationId})}async fetchModels(){try{return await this.http.get("/models")}catch{}return[]}async authenticate(){let e=await fetch(`${this.baseUrl}/auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.accessToken}`},body:JSON.stringify({game_id:this.gameId})});if(!e.ok)throw e.status===401?new c("UNAUTHORIZED","User not authenticated"):e.status===404?new c("GAME_NOT_FOUND","Game not found or not published"):new c("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=`${K}${$}`,this.gameId=e.gameId,this.isPreview=!0,this.http=new E(this.baseUrl,"",!1,e.apiKey);let t=await this.fetchModels();this.modelId=t[0]?.id||"",this.conversationId="00000000-0000-0000-0000-000000000000",this.settingsSheet=new u({onModelChange:r=>{this.modelId=r},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),t.length>0&&this.settingsSheet.mount(t,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let n=()=>this.gameId,i=()=>this.conversationId,s=()=>this.modelId;this.chat=new v(this.http,n,i,s,!0,void 0),this.characters=new f(this.http,i,!0),this.relationships=new b(this.http,i,!0),this.inventory=new w(this.http,i,!0),this.world=new y(this.http,i,!0),this.player=new C(this.http,i,!0),this.custom=new x(this.http,i,!0),this.initialized=!0}};async function O(a){let e=new S;return a?.dev?await e.initDev(a.dev):await e.init(),e}function _(a){return typeof a=="object"&&a!==null&&"value"in a&&"type"in a&&(a.type==="number"||a.type==="text")}function L(a){return _(a)?a.value:a}return F(Q);})();
|
|
432
432
|
if(typeof window!=="undefined"){window.createStorviaSDK=StorviaSDK.createStorviaSDK;}
|