@pageops/sdk 0.1.3 → 0.1.4
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/pageops-sdk.es.js +13 -13
- package/dist/pageops-sdk.umd.cjs +4 -4
- package/package.json +1 -1
package/dist/pageops-sdk.es.js
CHANGED
|
@@ -23,16 +23,16 @@ class S {
|
|
|
23
23
|
});
|
|
24
24
|
}
|
|
25
25
|
async listConversations() {
|
|
26
|
-
return (await this.request(
|
|
26
|
+
return (await this.request(`/conversations?app_id=${encodeURIComponent(this.options.appId)}`)).conversations;
|
|
27
27
|
}
|
|
28
28
|
async createConversation(t, e) {
|
|
29
29
|
return this.request("/conversations", {
|
|
30
30
|
method: "POST",
|
|
31
|
-
body: JSON.stringify({ context_session_id: t, title: e })
|
|
31
|
+
body: JSON.stringify({ app_id: this.options.appId, context_session_id: t, title: e })
|
|
32
32
|
});
|
|
33
33
|
}
|
|
34
34
|
async listMessages(t) {
|
|
35
|
-
return (await this.request(`/conversations/${encodeURIComponent(t)}/messages`)).messages;
|
|
35
|
+
return (await this.request(`/conversations/${encodeURIComponent(t)}/messages?app_id=${encodeURIComponent(this.options.appId)}`)).messages;
|
|
36
36
|
}
|
|
37
37
|
async listSources() {
|
|
38
38
|
return (await this.request(`/sources?project_id=${encodeURIComponent(this.options.appId)}`)).sources;
|
|
@@ -45,7 +45,7 @@ class S {
|
|
|
45
45
|
return fetch(`${this.base()}/question/stream`, {
|
|
46
46
|
method: "POST",
|
|
47
47
|
headers: { "content-type": "application/json" },
|
|
48
|
-
body: JSON.stringify({ thread_id: t, question: e })
|
|
48
|
+
body: JSON.stringify({ app_id: this.options.appId, thread_id: t, question: e })
|
|
49
49
|
});
|
|
50
50
|
}
|
|
51
51
|
async request(t, e) {
|
|
@@ -65,7 +65,7 @@ function E(r) {
|
|
|
65
65
|
function f(r) {
|
|
66
66
|
return E(r).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
|
|
67
67
|
}
|
|
68
|
-
function
|
|
68
|
+
function U(r, t) {
|
|
69
69
|
const e = r[t], s = r[t + 1];
|
|
70
70
|
if (!(e != null && e.includes("|")) || !/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s != null ? s : "")) return null;
|
|
71
71
|
const o = [];
|
|
@@ -79,7 +79,7 @@ function b(r) {
|
|
|
79
79
|
const t = r.split(`
|
|
80
80
|
`), e = [];
|
|
81
81
|
for (let s = 0; s < t.length; s += 1) {
|
|
82
|
-
const o =
|
|
82
|
+
const o = U(t, s);
|
|
83
83
|
if (o) {
|
|
84
84
|
e.push(o.html), s = o.next - 1;
|
|
85
85
|
continue;
|
|
@@ -89,7 +89,7 @@ function b(r) {
|
|
|
89
89
|
}
|
|
90
90
|
return e.join("");
|
|
91
91
|
}
|
|
92
|
-
async function
|
|
92
|
+
async function C(r, t) {
|
|
93
93
|
var n, c, h;
|
|
94
94
|
const e = r.getReader(), s = new TextDecoder();
|
|
95
95
|
let o = "";
|
|
@@ -107,7 +107,7 @@ async function T(r, t) {
|
|
|
107
107
|
}
|
|
108
108
|
}
|
|
109
109
|
}
|
|
110
|
-
class
|
|
110
|
+
class P {
|
|
111
111
|
constructor() {
|
|
112
112
|
a(this, "client", null);
|
|
113
113
|
a(this, "options", null);
|
|
@@ -193,7 +193,7 @@ class U {
|
|
|
193
193
|
this.messages.push({ id: `local-${Date.now()}`, role: "user", content: t, metadata_json: {} }), this.steps = [], this.streaming = "", this.renderPanel();
|
|
194
194
|
const e = await this.client.streamQuestion(this.currentThread.id, t);
|
|
195
195
|
if (!e.ok || !e.body) throw new Error("PageOps 流式问答失败");
|
|
196
|
-
await
|
|
196
|
+
await C(e.body, (s, o) => {
|
|
197
197
|
var n;
|
|
198
198
|
s === "step" && this.upsertStep(o), s === "delta" && (this.streaming += String((n = o.content) != null ? n : "")), s === "done" && this.selectThread(this.currentThread), s === "error" && this.upsertStep({ id: "error", title: "执行失败", status: "failed", details: o }), this.renderPanel();
|
|
199
199
|
});
|
|
@@ -243,7 +243,7 @@ class U {
|
|
|
243
243
|
`;
|
|
244
244
|
}
|
|
245
245
|
renderSourceItem(t) {
|
|
246
|
-
const e = t.filename || "未命名代码包", s = t.created_at ? y(t.created_at) : "刚刚上传", o =
|
|
246
|
+
const e = t.filename || "未命名代码包", s = t.created_at ? y(t.created_at) : "刚刚上传", o = T(t.archive_bytes || t.total_bytes || 0);
|
|
247
247
|
return `<article class="po-source-item"><strong>${u(e)}</strong><span>${u(s)} · ${u(o)}</span></article>`;
|
|
248
248
|
}
|
|
249
249
|
renderSteps() {
|
|
@@ -281,7 +281,7 @@ function u(r) {
|
|
|
281
281
|
function y(r) {
|
|
282
282
|
return new Intl.DateTimeFormat("zh-CN", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }).format(new Date(r));
|
|
283
283
|
}
|
|
284
|
-
function
|
|
284
|
+
function T(r) {
|
|
285
285
|
if (!r) return "0 B";
|
|
286
286
|
const t = ["B", "KB", "MB", "GB"];
|
|
287
287
|
let e = r, s = 0;
|
|
@@ -289,7 +289,7 @@ function C(r) {
|
|
|
289
289
|
e /= 1024, s += 1;
|
|
290
290
|
return `${e >= 10 || s === 0 ? e.toFixed(0) : e.toFixed(1)} ${t[s]}`;
|
|
291
291
|
}
|
|
292
|
-
const
|
|
292
|
+
const _ = new P();
|
|
293
293
|
export {
|
|
294
|
-
|
|
294
|
+
_ as PageOpsSDK
|
|
295
295
|
};
|
package/dist/pageops-sdk.umd.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
(function(
|
|
2
|
-
`),e=[];for(let s=0;s<t.length;s+=1){const
|
|
1
|
+
(function(d,c){typeof exports=="object"&&typeof module!="undefined"?c(exports):typeof define=="function"&&define.amd?define(["exports"],c):(d=typeof globalThis!="undefined"?globalThis:d||self,c(d.PageOpsSDK={}))})(this,(function(d){"use strict";var O=Object.defineProperty;var _=(d,c,v)=>c in d?O(d,c,{enumerable:!0,configurable:!0,writable:!0,value:v}):d[c]=v;var a=(d,c,v)=>_(d,typeof c!="symbol"?c+"":c,v);class c{constructor(t){this.options=t}async createContext(){var e,s,o,n,l;const t=(o=(s=(e=this.options).getPageContext)==null?void 0:s.call(e))!=null?o:{};return this.request("/context/session",{method:"POST",body:JSON.stringify({app_id:this.options.appId,env:this.options.env,route:t.route,url:(n=t.url)!=null?n:location.href,title:(l=t.title)!=null?l:document.title,tenant_id:t.tenantId,user_role:t.userRole,build_version:t.buildVersion})})}async listConversations(){return(await this.request(`/conversations?app_id=${encodeURIComponent(this.options.appId)}`)).conversations}async createConversation(t,e){return this.request("/conversations",{method:"POST",body:JSON.stringify({app_id:this.options.appId,context_session_id:t,title:e})})}async listMessages(t){return(await this.request(`/conversations/${encodeURIComponent(t)}/messages?app_id=${encodeURIComponent(this.options.appId)}`)).messages}async listSources(){return(await this.request(`/sources?project_id=${encodeURIComponent(this.options.appId)}`)).sources}uploadSource(t){const e=new FormData;return e.append("file",t),this.request(`/sources/upload?project_id=${encodeURIComponent(this.options.appId)}`,{method:"POST",body:e,headers:{}})}streamQuestion(t,e){return fetch(`${this.base()}/question/stream`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:this.options.appId,thread_id:t,question:e})})}async request(t,e){var l,u;const s=(e==null?void 0:e.body)instanceof FormData?e.headers:{"content-type":"application/json",...(l=e==null?void 0:e.headers)!=null?l:{}},o=await fetch(`${this.base()}${t}`,{...e,headers:s}),n=await o.json();if(!o.ok)throw new Error((u=n.message)!=null?u:"PageOps 请求失败");return n}base(){const t=this.options.apiBase.replace(/\/$/,"");return t.endsWith("/api")?t:`${t}/api`}}function v(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function S(i){return v(i).replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>")}function E(i,t){const e=i[t],s=i[t+1];if(!(e!=null&&e.includes("|"))||!/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s!=null?s:""))return null;const o=[];let n=t;for(;n<i.length&&i[n].includes("|")&&i[n].trim();)o.push(i[n]),n+=1;const l=m=>m.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(g=>S(g.trim())),u=l(o[0]).map(m=>`<th>${m}</th>`).join(""),$=o.slice(2).map(m=>`<tr>${l(m).map(g=>`<td>${g}</td>`).join("")}</tr>`).join("");return{html:`<table><thead><tr>${u}</tr></thead><tbody>${$}</tbody></table>`,next:n}}function w(i){const t=i.split(`
|
|
2
|
+
`),e=[];for(let s=0;s<t.length;s+=1){const o=E(t,s);if(o){e.push(o.html),s=o.next-1;continue}const n=t[s];n.startsWith("### ")?e.push(`<h4>${S(n.slice(4))}</h4>`):n.startsWith("## ")?e.push(`<h3>${S(n.slice(3))}</h3>`):n.startsWith("# ")?e.push(`<h2>${S(n.slice(2))}</h2>`):n.startsWith("- ")?e.push(`<li>${S(n.slice(2))}</li>`):n.trim()?e.push(`<p>${S(n)}</p>`):e.push("<br>")}return e.join("")}async function P(i,t){var n,l,u;const e=i.getReader(),s=new TextDecoder;let o="";for(;;){const{done:$,value:m}=await e.read();if($)break;o+=s.decode(m,{stream:!0});const g=o.split(`
|
|
3
3
|
|
|
4
|
-
`);
|
|
4
|
+
`);o=(n=g.pop())!=null?n:"";for(const y of g){const h=(l=y.match(/^event: (.+)$/m))==null?void 0:l[1],r=(u=y.match(/^data: (.+)$/m))==null?void 0:u[1];h&&r&&t(h,JSON.parse(r))}}}class T{constructor(){a(this,"client",null);a(this,"options",null);a(this,"root",null);a(this,"panel",null);a(this,"context",null);a(this,"currentThread",null);a(this,"conversations",[]);a(this,"messages",[]);a(this,"steps",[]);a(this,"sourceSnapshots",[]);a(this,"sourceUploadStatus","");a(this,"sourceUploadError","");a(this,"sourceUploading",!1);a(this,"streaming","")}mount(t){var e;this.unmount(),this.options=t,this.client=new c(t),this.root=document.createElement("div"),this.root.className="pageops-sdk",((e=t.container)!=null?e:document.body).appendChild(this.root),this.renderClosed()}unmount(){var t;(t=this.root)==null||t.remove(),this.root=null,this.panel=null,this.context=null,this.currentThread=null,this.conversations=[],this.messages=[],this.steps=[],this.sourceSnapshots=[],this.sourceUploadStatus="",this.sourceUploadError="",this.sourceUploading=!1,this.streaming=""}open(){this.root&&(this.root.innerHTML="",this.panel=document.createElement("div"),this.panel.className="po-panel",this.root.appendChild(this.panel),this.loadSources(),this.loadConversations(),this.renderPanel())}close(){this.renderClosed()}updateContext(t){this.options&&(this.options={...this.options,...t},this.client=new c(this.options))}renderClosed(){var t;this.root&&(this.root.innerHTML='<button class="po-fab" type="button">多轮问答</button>',(t=this.root.querySelector("button"))==null||t.addEventListener("click",()=>this.open()))}async ensureContext(){if(this.context)return this.context;if(!this.client)throw new Error("PageOps SDK 未初始化");return this.context=await this.client.createContext(),this.context}async loadSources(){if(this.client){try{this.sourceSnapshots=await this.client.listSources(),this.sourceUploadError=""}catch(t){this.sourceUploadError=t instanceof Error?t.message:"源码包状态加载失败"}this.renderPanel()}}async loadConversations(){this.client&&(this.conversations=await this.client.listConversations(),this.renderPanel())}async newConversation(){if(!this.client)return;const t=await this.ensureContext();this.currentThread=await this.client.createConversation(t.id,t.route||document.title||"新的问答"),this.conversations=[this.currentThread,...this.conversations],this.messages=[],this.steps=[],this.streaming="",this.renderPanel()}async selectThread(t){this.client&&(this.currentThread=t,this.messages=await this.client.listMessages(t.id),this.steps=[],this.streaming="",this.renderPanel())}async uploadSource(t){if(this.client){this.sourceUploading=!0,this.sourceUploadStatus="上传中...",this.sourceUploadError="",this.renderPanel();try{await this.client.uploadSource(t),this.sourceSnapshots=await this.client.listSources(),this.sourceUploadStatus="上传完成"}catch(e){this.sourceUploadError=e instanceof Error?e.message:"源码包上传失败",this.sourceUploadStatus=""}finally{this.sourceUploading=!1,this.renderPanel()}}}async ask(t){if(!this.client)return;if(!this.sourceSnapshots.length){this.sourceUploadError="请先上传代码包后再提问。",this.renderPanel();return}if(this.currentThread||await this.newConversation(),!this.currentThread)return;this.messages.push({id:`local-${Date.now()}`,role:"user",content:t,metadata_json:{}}),this.steps=[],this.streaming="",this.renderPanel();const e=await this.client.streamQuestion(this.currentThread.id,t);if(!e.ok||!e.body)throw new Error("PageOps 流式问答失败");await P(e.body,(s,o)=>{var n;s==="step"&&this.upsertStep(o),s==="delta"&&(this.streaming+=String((n=o.content)!=null?n:"")),s==="done"&&this.selectThread(this.currentThread),s==="error"&&this.upsertStep({id:"error",title:"执行失败",status:"failed",details:o}),this.renderPanel()})}upsertStep(t){const e=this.steps.findIndex(s=>s.id===t.id);this.steps=e===-1?[...this.steps,t]:this.steps.map(s=>s.id===t.id?{...s,...t}:s)}renderPanel(){this.panel&&(this.panel.innerHTML=`
|
|
5
5
|
<aside class="po-sidebar">
|
|
6
6
|
<div class="po-brand"><div class="po-logo"></div><div><strong>PageOps 问答</strong><span>页面工程专家</span></div></div>
|
|
7
7
|
<button class="po-new" data-action="new">+ 新建问答</button>
|
|
@@ -32,4 +32,4 @@
|
|
|
32
32
|
${this.sourceSnapshots.length?`<div class="po-source-list">${this.sourceSnapshots.map(t=>this.renderSourceItem(t)).join("")}</div>`:'<p class="po-upload-empty">当前系统暂无代码包,请先上传后再提问。</p>'}
|
|
33
33
|
${this.sourceUploadError?`<p class="po-upload-error">${p(this.sourceUploadError)}</p>`:""}
|
|
34
34
|
</div>
|
|
35
|
-
`}renderSourceItem(t){const e=t.filename||"未命名代码包",s=t.created_at?x(t.created_at):"刚刚上传",
|
|
35
|
+
`}renderSourceItem(t){const e=t.filename||"未命名代码包",s=t.created_at?x(t.created_at):"刚刚上传",o=U(t.archive_bytes||t.total_bytes||0);return`<article class="po-source-item"><strong>${p(e)}</strong><span>${p(s)} · ${p(o)}</span></article>`}renderSteps(){return(this.steps.length?this.steps:[{id:"idle",title:"等待任务",status:"pending",details:{message:"发送消息后展示执行过程。"}}]).map(e=>{var s;return`<details class="po-step ${e.status}" ${e.status==="running"||e.status==="failed"?"open":""}><summary><strong>${p(e.title)}</strong><span>${e.status}</span></summary><pre>${p(JSON.stringify((s=e.details)!=null?s:{},null,2))}</pre></details>`}).join("")}bindPanelEvents(){var t,e,s,o,n,l,u,$,m,g,y;(e=(t=this.panel)==null?void 0:t.querySelector('[data-action="new"]'))==null||e.addEventListener("click",()=>void this.newConversation()),(o=(s=this.panel)==null?void 0:s.querySelector('[data-action="close"]'))==null||o.addEventListener("click",()=>this.close()),(l=(n=this.panel)==null?void 0:n.querySelector('[data-action="upload-source"]'))==null||l.addEventListener("change",h=>{var f;const r=(f=h.target.files)==null?void 0:f[0];r&&this.uploadSource(r)}),(u=this.panel)==null||u.querySelectorAll("[data-thread]").forEach(h=>{h.addEventListener("click",()=>{const r=this.conversations.find(f=>f.id===h.dataset.thread);r&&this.selectThread(r)})}),(m=($=this.panel)==null?void 0:$.querySelector("form"))==null||m.addEventListener("submit",h=>{var b;h.preventDefault();const r=(b=this.panel)==null?void 0:b.querySelector("textarea"),f=r==null?void 0:r.value.trim();f&&(r.value="",this.ask(f))}),(y=(g=this.panel)==null?void 0:g.querySelector("textarea"))==null||y.addEventListener("keydown",h=>{var f,b;const r=h;r.key==="Enter"&&!r.shiftKey&&(r.preventDefault(),(b=(f=this.panel)==null?void 0:f.querySelector("form"))==null||b.requestSubmit())})}}function p(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function x(i){return new Intl.DateTimeFormat("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).format(new Date(i))}function U(i){if(!i)return"0 B";const t=["B","KB","MB","GB"];let e=i,s=0;for(;e>=1024&&s<t.length-1;)e/=1024,s+=1;return`${e>=10||s===0?e.toFixed(0):e.toFixed(1)} ${t[s]}`}const C=new T;d.PageOpsSDK=C,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"})}));
|