@pageops/sdk 0.1.6 → 0.1.8

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/client.d.ts CHANGED
@@ -12,3 +12,4 @@ export declare class PageOpsClient {
12
12
  private request;
13
13
  private base;
14
14
  }
15
+ export declare function responseErrorMessage(response: Response, fallback: string): Promise<string>;
package/dist/index.d.ts CHANGED
@@ -16,7 +16,14 @@ declare class PageOpsSDKController {
16
16
  private sourceUploadStatus;
17
17
  private sourceUploadError;
18
18
  private sourceUploading;
19
+ private sourceRefreshTimer;
19
20
  private streaming;
21
+ private asking;
22
+ private waitingForFirstContent;
23
+ private answerError;
24
+ private streamFailure;
25
+ private streamDone;
26
+ private typewriter;
20
27
  mount(options: PageOpsMountOptions): void;
21
28
  unmount(): void;
22
29
  open(): void;
@@ -32,8 +39,17 @@ declare class PageOpsSDKController {
32
39
  private selectThread;
33
40
  private uploadSource;
34
41
  private ask;
42
+ private handleStreamEvent;
43
+ private updateStreamingMessage;
44
+ private resetAnswerState;
35
45
  private upsertStep;
46
+ private latestAnalysisStatus;
47
+ private isProjectMemoryUpdating;
48
+ private questionUnavailableReason;
49
+ private scheduleSourceRefresh;
50
+ private stopSourceRefresh;
36
51
  private renderPanel;
52
+ private renderAnswerState;
37
53
  private renderSourceUploader;
38
54
  private renderSourceItem;
39
55
  private renderSteps;
@@ -1 +1 @@
1
- .pageops-sdk{--po-text: #172033;--po-muted: #64748b;--po-border: #dbe5f5;--po-soft-border: #e2e8f0;--po-surface: #ffffff;--po-soft: #f8fafc;--po-panel: #fbfdff;--po-primary: #2563eb;--po-primary-dark: #1d4ed8;--po-shadow: 0 24px 70px rgb(15 23 42 / 18%);color:var(--po-text);font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif}.pageops-sdk *,.pageops-sdk *:before,.pageops-sdk *:after{box-sizing:border-box}.pageops-sdk button,.pageops-sdk input,.pageops-sdk textarea{font:inherit}.pageops-sdk button{cursor:pointer}.po-fab{position:fixed;right:24px;bottom:24px;z-index:2147483000;border:0;border-radius:999px;padding:12px 18px;background:linear-gradient(135deg,#2563eb,#14b8a6);color:#fff;font-weight:800;box-shadow:0 18px 42px #2563eb47}.po-panel{position:fixed;inset:40px;z-index:2147483000;display:grid;grid-template-columns:250px minmax(0,1fr) 340px;min-height:520px;overflow:hidden;border:1px solid var(--po-border);border-radius:24px;background:var(--po-surface);box-shadow:var(--po-shadow)}.po-sidebar{display:flex;min-width:0;min-height:0;flex-direction:column;gap:12px;overflow:hidden;border-right:1px solid #dbeafe;background:#eef5ff;padding:16px}.po-brand{display:flex;align-items:center;gap:10px}.po-brand strong,.po-brand span{display:block}.po-brand span{margin-top:2px;color:var(--po-muted);font-size:12px}.po-logo{width:34px;height:34px;flex:0 0 auto;border-radius:12px;background:linear-gradient(135deg,#5eead4,#2563eb)}.po-new,.po-composer button{border:0;border-radius:10px;background:var(--po-primary);color:#fff;font-weight:750}.po-new{width:100%;padding:10px 12px}.po-search,.po-composer textarea{width:100%;border:1px solid #cbd5e1;border-radius:10px;background:#fff;color:var(--po-text);outline:none}.po-search{padding:9px 10px}.po-thread-list{display:grid;align-content:start;gap:8px;min-height:0;overflow:auto}.po-thread{display:grid;gap:4px;width:100%;border:1px solid transparent;border-radius:10px;background:transparent;color:#334155;padding:9px 10px;text-align:left}.po-thread.active{border-color:#bfdbfe;background:#fff;color:var(--po-text)}.po-thread span{color:#94a3b8;font-size:12px}.po-chat{display:flex;min-width:0;min-height:0;flex-direction:column;background:linear-gradient(180deg,#fff,var(--po-panel));padding:22px 26px}.po-chat header,.po-trace header{display:flex;align-items:center;justify-content:space-between;gap:12px;border-bottom:1px solid var(--po-soft-border);padding-bottom:14px}.po-chat header p,.po-chat header h2,.po-trace header h2{margin:0}.po-chat header p,.po-chat header span{color:var(--po-muted);font-size:12px}.po-chat header h2,.po-trace header h2{font-size:20px;letter-spacing:-.02em}.po-messages{display:grid;align-content:start;gap:14px;min-height:0;flex:1;overflow:auto;padding:18px 4px 18px 0}.po-message{display:grid;max-width:82%;gap:6px;border:1px solid var(--po-soft-border);border-radius:14px;padding:11px 13px;line-height:1.55;white-space:pre-wrap;word-break:break-word}.po-message b{font-size:12px;opacity:.78}.po-message.user{justify-self:end;border-color:var(--po-primary);background:var(--po-primary);color:#fff}.po-message.assistant{justify-self:start;background:var(--po-soft)}.po-message.streaming{border-color:#bfdbfe;background:#eff6ff}.po-message code{border-radius:5px;background:#eaf0ff;color:var(--po-primary-dark);padding:1px 5px}.po-message pre{max-width:100%;margin:8px 0;overflow:auto;border:1px solid var(--po-border);border-radius:6px;background:#f8fafc;padding:10px 12px;white-space:pre}.po-message pre code{border-radius:0;background:transparent;color:#1f2937;padding:0}.po-message h2,.po-message h3,.po-message h4,.po-message p{margin:8px 0}.po-message table{width:100%;margin:12px 0;border-collapse:collapse;border-radius:10px;font-size:14px}.po-message th,.po-message td{border:1px solid var(--po-border);padding:8px 10px;text-align:left;vertical-align:top}.po-message th{background:#eef5ff;color:#334155;font-weight:800}.po-composer{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:end;gap:10px;border-top:1px solid var(--po-soft-border);padding-top:12px}.po-composer textarea{min-height:88px;resize:vertical;padding:10px}.po-composer button{min-height:44px;padding:0 16px}.po-trace{display:flex;min-height:0;flex-direction:column;border-left:1px solid var(--po-soft-border);background:#fafbff}.po-trace header{padding:18px}.po-trace header button{width:32px;height:32px;border:1px solid #cbd5e1;border-radius:10px;background:#fff;color:#334155;font-size:20px;line-height:1}.po-trace section{display:grid;align-content:start;gap:12px;min-height:0;overflow:auto;padding:16px}.po-source-uploader{display:grid;gap:8px;border:1px solid var(--po-soft-border);border-radius:14px;background:#fff;padding:12px}.po-source-uploader p{margin:0;color:var(--po-muted);font-size:12px;line-height:1.5}.po-upload-button{display:inline-flex;justify-content:center;border:1px solid #bfdbfe;border-radius:10px;background:#eff6ff;color:var(--po-primary-dark);padding:8px 10px;font-weight:750;cursor:pointer}.po-upload-button input{display:none}.po-upload-status{color:#166534!important}.po-upload-empty{color:#92400e!important}.po-source-list{display:grid;gap:6px}.po-source-item{display:grid;gap:3px;border:1px solid #dbeafe;border-radius:10px;background:#f8fbff;padding:8px}.po-source-item strong{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.po-source-item span{color:var(--po-muted);font-size:12px}.po-composer textarea:disabled,.po-composer button:disabled{cursor:not-allowed;opacity:.62}.po-upload-error{color:#b91c1c!important}.po-step{border:1px solid var(--po-soft-border);border-radius:14px;background:#fff;padding:12px}.po-step.running{border-color:#bfdbfe;background:#eff6ff}.po-step.completed{border-color:#bbf7d0}.po-step.failed{border-color:#fecaca;background:#fff1f2}.po-step summary{display:flex;justify-content:space-between;gap:8px;cursor:pointer}.po-step summary::marker{color:var(--po-muted)}.po-step pre{overflow:auto;margin:10px 0 0;border-radius:12px;background:#0f172a;color:#e2e8f0;padding:12px;font-size:12px;white-space:pre-wrap}@media(max-width:900px){.po-panel{inset:12px;grid-template-columns:1fr;overflow:auto}.po-sidebar,.po-trace{min-height:220px;border:0}.po-chat{min-height:520px}.po-message{max-width:94%}}
1
+ .pageops-sdk{--po-text: #172033;--po-muted: #64748b;--po-border: #dbe5f5;--po-soft-border: #e2e8f0;--po-surface: #ffffff;--po-soft: #f8fafc;--po-panel: #fbfdff;--po-primary: #2563eb;--po-primary-dark: #1d4ed8;--po-shadow: 0 24px 70px rgb(15 23 42 / 18%);color:var(--po-text);font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif}.pageops-sdk *,.pageops-sdk *:before,.pageops-sdk *:after{box-sizing:border-box}.pageops-sdk button,.pageops-sdk input,.pageops-sdk textarea{font:inherit}.pageops-sdk button{cursor:pointer}.po-fab{position:fixed;right:24px;bottom:24px;z-index:2147483000;border:0;border-radius:999px;padding:12px 18px;background:linear-gradient(135deg,#2563eb,#14b8a6);color:#fff;font-weight:800;box-shadow:0 18px 42px #2563eb47}.po-panel{position:fixed;inset:40px;z-index:2147483000;display:grid;grid-template-columns:250px minmax(0,1fr) 340px;min-height:520px;overflow:hidden;border:1px solid var(--po-border);border-radius:24px;background:var(--po-surface);box-shadow:var(--po-shadow)}.po-sidebar{display:flex;min-width:0;min-height:0;flex-direction:column;gap:12px;overflow:hidden;border-right:1px solid #dbeafe;background:#eef5ff;padding:16px}.po-brand{display:flex;align-items:center;gap:10px}.po-brand strong,.po-brand span{display:block}.po-brand span{margin-top:2px;color:var(--po-muted);font-size:12px}.po-logo{width:34px;height:34px;flex:0 0 auto;border-radius:12px;background:linear-gradient(135deg,#5eead4,#2563eb)}.po-new,.po-composer button{border:0;border-radius:10px;background:var(--po-primary);color:#fff;font-weight:750}.po-new{width:100%;padding:10px 12px}.po-search,.po-composer textarea{width:100%;border:1px solid #cbd5e1;border-radius:10px;background:#fff;color:var(--po-text);outline:none}.po-search{padding:9px 10px}.po-thread-list{display:grid;align-content:start;gap:8px;min-height:0;overflow:auto}.po-thread{display:grid;gap:4px;width:100%;border:1px solid transparent;border-radius:10px;background:transparent;color:#334155;padding:9px 10px;text-align:left}.po-thread.active{border-color:#bfdbfe;background:#fff;color:var(--po-text)}.po-thread span{color:#94a3b8;font-size:12px}.po-chat{display:flex;min-width:0;min-height:0;flex-direction:column;background:linear-gradient(180deg,#fff,var(--po-panel));padding:22px 26px}.po-chat header,.po-trace header{display:flex;align-items:center;justify-content:space-between;gap:12px;border-bottom:1px solid var(--po-soft-border);padding-bottom:14px}.po-chat header p,.po-chat header h2,.po-trace header h2{margin:0}.po-chat header p,.po-chat header span{color:var(--po-muted);font-size:12px}.po-chat header h2,.po-trace header h2{font-size:20px;letter-spacing:-.02em}.po-messages{display:grid;align-content:start;gap:14px;min-height:0;flex:1;overflow:auto;padding:18px 4px 18px 0}.po-message{display:grid;max-width:82%;gap:6px;border:1px solid var(--po-soft-border);border-radius:14px;padding:11px 13px;line-height:1.55;white-space:pre-wrap;word-break:break-word}.po-message b{font-size:12px;opacity:.78}.po-message.user{justify-self:end;border-color:var(--po-primary);background:var(--po-primary);color:#fff}.po-message.assistant{justify-self:start;background:var(--po-soft)}.po-message.streaming{border-color:#bfdbfe;background:#eff6ff}.po-message.answer-error{border-color:#fecaca;background:#fff7f7;color:#991b1b}.po-message.answer-error>strong{color:#7f1d1d}.po-ai-waiting{display:inline-flex;align-items:center;gap:9px;min-height:24px;color:#475569}.po-ai-spinner{width:16px;height:16px;flex:0 0 auto;border:2px solid #bfdbfe;border-top-color:var(--po-primary);border-radius:50%;animation:po-ai-spin .7s linear infinite}.po-typing-cursor{display:inline-block;width:2px;height:1em;margin-left:3px;background:var(--po-primary);vertical-align:-.12em;animation:po-typing-cursor .8s steps(1,end) infinite}@keyframes po-ai-spin{to{transform:rotate(360deg)}}@keyframes po-typing-cursor{50%{opacity:0}}.po-message code{border-radius:5px;background:#eaf0ff;color:var(--po-primary-dark);padding:1px 5px}.po-message pre{max-width:100%;margin:8px 0;overflow:auto;border:1px solid var(--po-border);border-radius:6px;background:#f8fafc;padding:10px 12px;white-space:pre}.po-message pre code{border-radius:0;background:transparent;color:#1f2937;padding:0}.po-message h2,.po-message h3,.po-message h4,.po-message p{margin:8px 0}.po-message table{width:100%;margin:12px 0;border-collapse:collapse;border-radius:10px;font-size:14px}.po-message th,.po-message td{border:1px solid var(--po-border);padding:8px 10px;text-align:left;vertical-align:top}.po-message th{background:#eef5ff;color:#334155;font-weight:800}.po-composer{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:end;gap:10px;border-top:1px solid var(--po-soft-border);padding-top:12px}.po-composer textarea{min-height:88px;resize:vertical;padding:10px}.po-composer button{min-height:44px;padding:0 16px}.po-trace{display:flex;min-height:0;flex-direction:column;border-left:1px solid var(--po-soft-border);background:#fafbff}.po-trace header{padding:18px}.po-trace header button{width:32px;height:32px;border:1px solid #cbd5e1;border-radius:10px;background:#fff;color:#334155;font-size:20px;line-height:1}.po-trace section{display:grid;align-content:start;gap:12px;min-height:0;overflow:auto;padding:16px}.po-source-uploader{display:grid;gap:8px;border:1px solid var(--po-soft-border);border-radius:14px;background:#fff;padding:12px}.po-source-uploader p{margin:0;color:var(--po-muted);font-size:12px;line-height:1.5}.po-upload-button{display:inline-flex;justify-content:center;border:1px solid #bfdbfe;border-radius:10px;background:#eff6ff;color:var(--po-primary-dark);padding:8px 10px;font-weight:750;cursor:pointer}.po-upload-button input{display:none}.po-upload-status{color:#166534!important}.po-upload-empty{color:#92400e!important}.po-source-list{display:grid;gap:6px}.po-source-item{display:grid;gap:3px;border:1px solid #dbeafe;border-radius:10px;background:#f8fbff;padding:8px}.po-source-item strong{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.po-source-item span{color:var(--po-muted);font-size:12px}.po-composer textarea:disabled,.po-composer button:disabled{cursor:not-allowed;opacity:.62}.po-upload-error{color:#b91c1c!important}.po-step{border:1px solid var(--po-soft-border);border-radius:14px;background:#fff;padding:12px}.po-step.running{border-color:#bfdbfe;background:#eff6ff}.po-step.completed{border-color:#bbf7d0}.po-step.failed{border-color:#fecaca;background:#fff1f2}.po-step summary{display:flex;justify-content:space-between;gap:8px;cursor:pointer}.po-step summary::marker{color:var(--po-muted)}.po-step pre{overflow:auto;margin:10px 0 0;border-radius:12px;background:#0f172a;color:#e2e8f0;padding:12px;font-size:12px;white-space:pre-wrap}@media(max-width:900px){.po-panel{inset:12px;grid-template-columns:1fr;overflow:auto}.po-sidebar,.po-trace{min-height:220px;border:0}.po-chat{min-height:520px}.po-message{max-width:94%}}@media(prefers-reduced-motion:reduce){.po-ai-spinner,.po-typing-cursor{animation:none}}
@@ -1,20 +1,20 @@
1
- var w = Object.defineProperty;
2
- var x = (i, t, e) => t in i ? w(i, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : i[t] = e;
3
- var c = (i, t, e) => x(i, typeof t != "symbol" ? t + "" : t, e);
4
- class $ {
1
+ var E = Object.defineProperty;
2
+ var C = (n, t, e) => t in n ? E(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
3
+ var a = (n, t, e) => C(n, typeof t != "symbol" ? t + "" : t, e);
4
+ class S {
5
5
  constructor(t) {
6
6
  this.options = t;
7
7
  }
8
- async createContext(t = ((n) => (n = ((e) => ((s) => (s = (e = this.options).getPageContext) == null ? void 0 : s.call(e))())()) != null ? n : {})()) {
9
- var o, r, l;
8
+ async createContext(t = ((i) => (i = ((e) => ((s) => (s = (e = this.options).getPageContext) == null ? void 0 : s.call(e))())()) != null ? i : {})()) {
9
+ var r, o, l;
10
10
  return this.request("/context/session", {
11
11
  method: "POST",
12
12
  body: JSON.stringify({
13
13
  app_id: this.options.appId,
14
14
  env: this.options.env,
15
15
  route: t.route,
16
- url: (o = t.url) != null ? o : location.href,
17
- title: (r = t.title) != null ? r : document.title,
16
+ url: (r = t.url) != null ? r : location.href,
17
+ title: (o = t.title) != null ? o : document.title,
18
18
  menu_path: (l = t.menuPath) != null ? l : [],
19
19
  tenant_id: t.tenantId,
20
20
  user_role: t.userRole,
@@ -49,107 +49,152 @@ class $ {
49
49
  });
50
50
  }
51
51
  async request(t, e) {
52
- var r, l;
53
- const s = (e == null ? void 0 : e.body) instanceof FormData ? e.headers : { "content-type": "application/json", ...(r = e == null ? void 0 : e.headers) != null ? r : {} }, n = await fetch(`${this.base()}${t}`, { ...e, headers: s }), o = await n.json();
54
- if (!n.ok) throw new Error((l = o.message) != null ? l : "PageOps 请求失败");
55
- return o;
52
+ var o, l;
53
+ const s = (e == null ? void 0 : e.body) instanceof FormData ? e.headers : { "content-type": "application/json", ...(o = e == null ? void 0 : e.headers) != null ? o : {} }, i = await fetch(`${this.base()}${t}`, { ...e, headers: s }), r = await i.json();
54
+ if (!i.ok) throw new Error((l = r.message) != null ? l : "PageOps 请求失败");
55
+ return r;
56
56
  }
57
57
  base() {
58
58
  const t = this.options.apiBase.replace(/\/$/, "");
59
59
  return t.endsWith("/api") ? t : `${t}/api`;
60
60
  }
61
61
  }
62
- function P(i) {
63
- return i.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
62
+ async function T(n, t) {
63
+ const e = await n.json().catch(() => null);
64
+ return typeof (e == null ? void 0 : e.message) == "string" && e.message.trim() ? e.message : t;
64
65
  }
65
- function f(i) {
66
- return P(i).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
66
+ function P(n) {
67
+ return n.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
67
68
  }
68
- function C(i, t) {
69
- const e = i[t], s = i[t + 1];
69
+ function f(n) {
70
+ return P(n).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
71
+ }
72
+ function x(n, t) {
73
+ const e = n[t], s = n[t + 1];
70
74
  if (!(e != null && e.includes("|")) || !/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s != null ? s : "")) return null;
71
- const n = [];
72
- let o = t;
73
- for (; o < i.length && i[o].includes("|") && i[o].trim(); )
74
- n.push(i[o]), o += 1;
75
- const r = (d) => d.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((g) => f(g.trim())), l = r(n[0]).map((d) => `<th>${d}</th>`).join(""), m = n.slice(2).map((d) => `<tr>${r(d).map((g) => `<td>${g}</td>`).join("")}</tr>`).join("");
76
- return { html: `<table><thead><tr>${l}</tr></thead><tbody>${m}</tbody></table>`, next: o };
75
+ const i = [];
76
+ let r = t;
77
+ for (; r < n.length && n[r].includes("|") && n[r].trim(); )
78
+ i.push(n[r]), r += 1;
79
+ const o = (c) => c.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((m) => f(m.trim())), l = o(i[0]).map((c) => `<th>${c}</th>`).join(""), d = i.slice(2).map((c) => `<tr>${o(c).map((m) => `<td>${m}</td>`).join("")}</tr>`).join("");
80
+ return { html: `<table><thead><tr>${l}</tr></thead><tbody>${d}</tbody></table>`, next: r };
77
81
  }
78
- function S(i) {
79
- const t = i.split(`
82
+ function w(n) {
83
+ const t = n.split(`
80
84
  `), e = [];
81
85
  for (let s = 0; s < t.length; s += 1) {
82
- const n = t[s];
83
- if (n.trim().startsWith("```")) {
84
- const r = [];
86
+ const i = t[s];
87
+ if (i.trim().startsWith("```")) {
88
+ const o = [];
85
89
  for (s += 1; s < t.length && !t[s].trim().startsWith("```"); )
86
- r.push(t[s]), s += 1;
87
- e.push(`<pre><code>${P(r.join(`
90
+ o.push(t[s]), s += 1;
91
+ e.push(`<pre><code>${P(o.join(`
88
92
  `))}</code></pre>`);
89
93
  continue;
90
94
  }
91
- const o = C(t, s);
92
- if (o) {
93
- e.push(o.html), s = o.next - 1;
95
+ const r = x(t, s);
96
+ if (r) {
97
+ e.push(r.html), s = r.next - 1;
94
98
  continue;
95
99
  }
96
- n.startsWith("### ") ? e.push(`<h4>${f(n.slice(4))}</h4>`) : n.startsWith("## ") ? e.push(`<h3>${f(n.slice(3))}</h3>`) : n.startsWith("# ") ? e.push(`<h2>${f(n.slice(2))}</h2>`) : n.startsWith("- ") ? e.push(`<li>${f(n.slice(2))}</li>`) : n.trim() ? e.push(`<p>${f(n)}</p>`) : e.push("<br>");
100
+ i.startsWith("### ") ? e.push(`<h4>${f(i.slice(4))}</h4>`) : i.startsWith("## ") ? e.push(`<h3>${f(i.slice(3))}</h3>`) : i.startsWith("# ") ? e.push(`<h2>${f(i.slice(2))}</h2>`) : i.startsWith("- ") ? e.push(`<li>${f(i.slice(2))}</li>`) : i.trim() ? e.push(`<p>${f(i)}</p>`) : e.push("<br>");
97
101
  }
98
102
  return e.join("");
99
103
  }
100
- async function E(i, t) {
101
- var o, r, l;
102
- const e = i.getReader(), s = new TextDecoder();
103
- let n = "";
104
+ async function k(n, t) {
105
+ var r;
106
+ const e = n.getReader(), s = new TextDecoder();
107
+ let i = "";
104
108
  for (; ; ) {
105
- const { done: m, value: d } = await e.read();
106
- if (m) break;
107
- n += s.decode(d, { stream: !0 });
108
- const g = n.split(`
109
-
110
- `);
111
- n = (o = g.pop()) != null ? o : "";
112
- for (const y of g) {
113
- const h = (r = y.match(/^event: (.+)$/m)) == null ? void 0 : r[1], a = (l = y.match(/^data: (.+)$/m)) == null ? void 0 : l[1];
114
- h && a && t(h, JSON.parse(a));
109
+ const { done: o, value: l } = await e.read();
110
+ if (o) {
111
+ i += s.decode();
112
+ break;
115
113
  }
114
+ i += s.decode(l, { stream: !0 });
115
+ const d = i.split(/\r?\n\r?\n/);
116
+ i = (r = d.pop()) != null ? r : "";
117
+ for (const c of d) $(c, t);
118
+ }
119
+ i.trim() && $(i, t);
120
+ }
121
+ function $(n, t) {
122
+ var i, r;
123
+ const e = (i = n.match(/^event:\s*(.+)$/m)) == null ? void 0 : i[1], s = (r = n.match(/^data:\s*(.+)$/m)) == null ? void 0 : r[1];
124
+ e && s && t(e, JSON.parse(s));
125
+ }
126
+ class U {
127
+ constructor(t, e = 16) {
128
+ a(this, "queue", []);
129
+ a(this, "timer", null);
130
+ a(this, "drainWaiters", []);
131
+ this.onChunk = t, this.interval = e;
132
+ }
133
+ enqueue(t) {
134
+ this.queue.push(...Array.from(t)), this.timer || this.tick();
135
+ }
136
+ async drain() {
137
+ !this.timer && !this.queue.length || await new Promise((t) => this.drainWaiters.push(t));
138
+ }
139
+ clear() {
140
+ this.timer && clearTimeout(this.timer), this.timer = null, this.queue = [], this.resolveDrainWaiters();
141
+ }
142
+ tick() {
143
+ const t = Math.max(1, Math.ceil(this.queue.length / 90)), e = this.queue.splice(0, t).join("");
144
+ if (e && this.onChunk(e), !this.queue.length) {
145
+ this.timer = null, this.resolveDrainWaiters();
146
+ return;
147
+ }
148
+ this.timer = setTimeout(() => this.tick(), this.interval);
149
+ }
150
+ resolveDrainWaiters() {
151
+ for (const t of this.drainWaiters.splice(0)) t();
116
152
  }
117
153
  }
118
- class T {
154
+ class q {
119
155
  constructor() {
120
- c(this, "client", null);
121
- c(this, "options", null);
122
- c(this, "root", null);
123
- c(this, "panel", null);
124
- c(this, "context", null);
125
- c(this, "contextKey", "");
126
- c(this, "selectedPageKey", "");
127
- c(this, "currentThread", null);
128
- c(this, "conversations", []);
129
- c(this, "messages", []);
130
- c(this, "steps", []);
131
- c(this, "sourceSnapshots", []);
132
- c(this, "sourceUploadStatus", "");
133
- c(this, "sourceUploadError", "");
134
- c(this, "sourceUploading", !1);
135
- c(this, "streaming", "");
156
+ a(this, "client", null);
157
+ a(this, "options", null);
158
+ a(this, "root", null);
159
+ a(this, "panel", null);
160
+ a(this, "context", null);
161
+ a(this, "contextKey", "");
162
+ a(this, "selectedPageKey", "");
163
+ a(this, "currentThread", null);
164
+ a(this, "conversations", []);
165
+ a(this, "messages", []);
166
+ a(this, "steps", []);
167
+ a(this, "sourceSnapshots", []);
168
+ a(this, "sourceUploadStatus", "");
169
+ a(this, "sourceUploadError", "");
170
+ a(this, "sourceUploading", !1);
171
+ a(this, "sourceRefreshTimer", null);
172
+ a(this, "streaming", "");
173
+ a(this, "asking", !1);
174
+ a(this, "waitingForFirstContent", !1);
175
+ a(this, "answerError", "");
176
+ a(this, "streamFailure", "");
177
+ a(this, "streamDone", null);
178
+ a(this, "typewriter", new U((t) => {
179
+ this.streaming += t, this.updateStreamingMessage();
180
+ }));
136
181
  }
137
182
  mount(t) {
138
183
  var e;
139
- this.unmount(), this.options = t, this.client = new $(t), this.root = document.createElement("div"), this.root.className = "pageops-sdk", ((e = t.container) != null ? e : document.body).appendChild(this.root), this.renderClosed();
184
+ this.unmount(), this.options = t, this.client = new S(t), this.root = document.createElement("div"), this.root.className = "pageops-sdk", ((e = t.container) != null ? e : document.body).appendChild(this.root), this.renderClosed();
140
185
  }
141
186
  unmount() {
142
187
  var t;
143
- (t = this.root) == null || t.remove(), this.root = null, this.panel = null, this.context = null, this.contextKey = "", this.selectedPageKey = "", this.currentThread = null, this.conversations = [], this.messages = [], this.steps = [], this.sourceSnapshots = [], this.sourceUploadStatus = "", this.sourceUploadError = "", this.sourceUploading = !1, this.streaming = "";
188
+ this.stopSourceRefresh(), this.resetAnswerState(), (t = this.root) == null || t.remove(), this.root = null, this.panel = null, this.context = null, this.contextKey = "", this.selectedPageKey = "", this.currentThread = null, this.conversations = [], this.messages = [], this.steps = [], this.sourceSnapshots = [], this.sourceUploadStatus = "", this.sourceUploadError = "", this.sourceUploading = !1;
144
189
  }
145
190
  open() {
146
191
  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());
147
192
  }
148
193
  close() {
149
- this.renderClosed();
194
+ this.stopSourceRefresh(), this.renderClosed();
150
195
  }
151
196
  updateContext(t) {
152
- this.options && (this.options = { ...this.options, ...t }, this.client = new $(this.options), this.context = null, this.contextKey = "");
197
+ this.options && (this.options = { ...this.options, ...t }, this.client = new S(this.options), this.context = null, this.contextKey = "");
153
198
  }
154
199
  renderClosed() {
155
200
  var t;
@@ -165,12 +210,12 @@ class T {
165
210
  return (s = (e = (t = this.options) == null ? void 0 : t.getPageContext) == null ? void 0 : e.call(t)) != null ? s : {};
166
211
  }
167
212
  getPageContextKey(t) {
168
- var e, s, n, o;
213
+ var e, s, i, r;
169
214
  return JSON.stringify([
170
215
  (e = t.route) != null ? e : "",
171
216
  (s = t.url) != null ? s : location.href,
172
- (n = t.title) != null ? n : document.title,
173
- (o = t.menuPath) != null ? o : []
217
+ (i = t.title) != null ? i : document.title,
218
+ (r = t.menuPath) != null ? r : []
174
219
  ]);
175
220
  }
176
221
  async loadSources() {
@@ -180,7 +225,7 @@ class T {
180
225
  } catch (t) {
181
226
  this.sourceUploadError = t instanceof Error ? t.message : "源码包状态加载失败";
182
227
  }
183
- this.renderPanel();
228
+ this.scheduleSourceRefresh(), this.renderPanel();
184
229
  }
185
230
  }
186
231
  async loadConversations() {
@@ -190,16 +235,16 @@ class T {
190
235
  var s;
191
236
  if (!this.client) return;
192
237
  const t = await this.ensureContext(), e = (s = t.menu_path) != null && s.length ? t.menu_path.join(" / ") : t.route || document.title || "新的问答";
193
- this.currentThread = await this.client.createConversation(t.id, e), this.selectedPageKey = this.contextKey, this.conversations = [this.currentThread, ...this.conversations], this.messages = [], this.steps = [], this.streaming = "", this.renderPanel();
238
+ this.currentThread = await this.client.createConversation(t.id, e), this.selectedPageKey = this.contextKey, this.conversations = [this.currentThread, ...this.conversations], this.messages = [], this.steps = [], this.streaming = "", this.answerError = "", this.renderPanel();
194
239
  }
195
240
  async selectThread(t) {
196
- this.client && (this.currentThread = t, this.selectedPageKey = this.getPageContextKey(this.getPageContext()), this.messages = await this.client.listMessages(t.id), this.steps = [], this.streaming = "", this.renderPanel());
241
+ this.client && (this.currentThread = t, this.selectedPageKey = this.getPageContextKey(this.getPageContext()), this.messages = await this.client.listMessages(t.id), this.steps = [], this.streaming = "", this.answerError = "", this.renderPanel());
197
242
  }
198
243
  async uploadSource(t) {
199
244
  if (this.client) {
200
245
  this.sourceUploading = !0, this.sourceUploadStatus = "上传中...", this.sourceUploadError = "", this.renderPanel();
201
246
  try {
202
- await this.client.uploadSource(t), this.sourceSnapshots = await this.client.listSources(), this.sourceUploadStatus = "上传完成";
247
+ await this.client.uploadSource(t), this.sourceSnapshots = await this.client.listSources(), this.sourceUploadStatus = this.isProjectMemoryUpdating() ? "源码上传完成,项目记忆更新中..." : "上传完成", this.scheduleSourceRefresh();
203
248
  } catch (e) {
204
249
  this.sourceUploadError = e instanceof Error ? e.message : "源码包上传失败", this.sourceUploadStatus = "";
205
250
  } finally {
@@ -208,49 +253,110 @@ class T {
208
253
  }
209
254
  }
210
255
  async ask(t) {
211
- if (!this.client) return;
212
- if (!this.sourceSnapshots.length) {
213
- this.sourceUploadError = "请先上传代码包后再提问。", this.renderPanel();
256
+ if (!this.client || this.asking) return;
257
+ const e = this.questionUnavailableReason();
258
+ if (e) {
259
+ this.sourceUploadError = e, this.renderPanel();
214
260
  return;
215
261
  }
216
- const e = this.getPageContextKey(this.getPageContext());
217
- if (this.currentThread && this.selectedPageKey && this.selectedPageKey !== e && (this.currentThread = null), this.currentThread || await this.newConversation(), !this.currentThread) return;
218
- this.messages.push({ id: `local-${Date.now()}`, role: "user", content: t, metadata_json: {} }), this.steps = [], this.streaming = "", this.renderPanel();
219
- const s = await this.client.streamQuestion(this.currentThread.id, t);
220
- if (!s.ok || !s.body) throw new Error("PageOps 流式问答失败");
221
- await E(s.body, (n, o) => {
222
- var r;
223
- n === "step" && this.upsertStep(o), n === "delta" && (this.streaming += String((r = o.content) != null ? r : "")), n === "done" && this.selectThread(this.currentThread), n === "error" && this.upsertStep({ id: "error", title: "执行失败", status: "failed", details: o }), this.renderPanel();
224
- });
262
+ this.resetAnswerState(), this.asking = !0, this.waitingForFirstContent = !0, this.renderPanel();
263
+ try {
264
+ const s = this.getPageContextKey(this.getPageContext());
265
+ if (this.currentThread && this.selectedPageKey && this.selectedPageKey !== s && (this.currentThread = null), this.currentThread || await this.newConversation(), !this.currentThread) throw new Error("无法创建问答会话,请稍后重试。");
266
+ this.messages.push({ id: `local-${Date.now()}`, role: "user", content: t, metadata_json: {} }), this.steps = [], this.renderPanel();
267
+ const i = await this.client.streamQuestion(this.currentThread.id, t);
268
+ if (!i.ok) throw new Error(await T(i, "服务暂时无法回答,请稍后重试。"));
269
+ if (!i.body) throw new Error("服务未返回有效的流式响应,请稍后重试。");
270
+ if (await k(i.body, (r, o) => this.handleStreamEvent(r, o)), this.streamFailure) throw new Error(this.streamFailure);
271
+ if (!this.streamDone) throw new Error("服务响应意外中断,请稍后重试。");
272
+ await this.typewriter.drain(), await this.selectThread(this.currentThread);
273
+ } catch (s) {
274
+ this.typewriter.clear(), this.waitingForFirstContent = !1, this.answerError = s instanceof Error ? s.message : "服务异常,请稍后重试。", this.upsertStep({ id: "error", title: "执行失败", status: "failed", details: { message: this.answerError } });
275
+ } finally {
276
+ this.asking = !1, this.waitingForFirstContent = !1, this.renderPanel();
277
+ }
278
+ }
279
+ handleStreamEvent(t, e) {
280
+ var s, i;
281
+ if (t === "step") {
282
+ this.upsertStep(e), this.renderPanel();
283
+ return;
284
+ }
285
+ if (t === "delta") {
286
+ const r = String((s = e.content) != null ? s : "");
287
+ if (!r) return;
288
+ this.waitingForFirstContent = !1, this.typewriter.enqueue(r);
289
+ return;
290
+ }
291
+ t === "done" && (this.streamDone = e), t === "error" && (this.streamFailure = String((i = e.message) != null ? i : "服务异常,请稍后重试。"));
292
+ }
293
+ updateStreamingMessage() {
294
+ var s, i;
295
+ const t = (s = this.panel) == null ? void 0 : s.querySelector("[data-streaming-content]");
296
+ if (!t) {
297
+ this.renderPanel();
298
+ return;
299
+ }
300
+ t.innerHTML = w(this.streaming);
301
+ const e = (i = this.panel) == null ? void 0 : i.querySelector(".po-messages");
302
+ e && (e.scrollTop = e.scrollHeight);
303
+ }
304
+ resetAnswerState() {
305
+ this.typewriter.clear(), this.asking = !1, this.waitingForFirstContent = !1, this.answerError = "", this.streamFailure = "", this.streamDone = null, this.streaming = "";
225
306
  }
226
307
  upsertStep(t) {
227
308
  const e = this.steps.findIndex((s) => s.id === t.id);
228
309
  this.steps = e === -1 ? [...this.steps, t] : this.steps.map((s) => s.id === t.id ? { ...s, ...t } : s);
229
310
  }
311
+ latestAnalysisStatus() {
312
+ var t, e, s;
313
+ return String((s = (e = (t = this.sourceSnapshots[0]) == null ? void 0 : t.metadata) == null ? void 0 : e.analysis_status) != null ? s : "");
314
+ }
315
+ isProjectMemoryUpdating() {
316
+ return ["pending", "running"].includes(this.latestAnalysisStatus());
317
+ }
318
+ questionUnavailableReason() {
319
+ return this.sourceSnapshots.length ? this.isProjectMemoryUpdating() ? "项目记忆正在更新,完成前暂不能问答。" : this.latestAnalysisStatus() === "failed" ? "项目记忆更新失败,请重新上传或重新索引。" : "" : "请先上传代码包后再提问。";
320
+ }
321
+ scheduleSourceRefresh() {
322
+ this.stopSourceRefresh(), this.isProjectMemoryUpdating() && (this.sourceRefreshTimer = setTimeout(() => void this.loadSources(), 1500));
323
+ }
324
+ stopSourceRefresh() {
325
+ this.sourceRefreshTimer && clearTimeout(this.sourceRefreshTimer), this.sourceRefreshTimer = null;
326
+ }
230
327
  renderPanel() {
231
- this.panel && (this.panel.innerHTML = `
328
+ if (!this.panel) return;
329
+ const t = this.questionUnavailableReason(), e = t || (this.asking ? "回答生成中,请稍候" : "请输入页面分析问题,Enter 发送,Shift + Enter 换行"), s = !!(t || this.asking);
330
+ if (this.panel.innerHTML = `
232
331
  <aside class="po-sidebar">
233
332
  <div class="po-brand"><div class="po-logo"></div><div><strong>PageOps 问答</strong><span>页面工程专家</span></div></div>
234
- <button class="po-new" data-action="new">+ 新建问答</button>
333
+ <button class="po-new" data-action="new" ${this.asking ? "disabled" : ""}>+ 新建问答</button>
235
334
  <input class="po-search" placeholder="搜索问答" />
236
- <div class="po-thread-list">${this.conversations.map((t) => {
237
- var e;
335
+ <div class="po-thread-list">${this.conversations.map((i) => {
336
+ var r;
238
337
  return `
239
- <button class="po-thread ${t.id === ((e = this.currentThread) == null ? void 0 : e.id) ? "active" : ""}" data-thread="${t.id}">
240
- <strong>${u(t.title)}</strong><span>${b(t.created_at)}</span>
338
+ <button class="po-thread ${i.id === ((r = this.currentThread) == null ? void 0 : r.id) ? "active" : ""}" data-thread="${i.id}" ${this.asking ? "disabled" : ""}>
339
+ <strong>${u(i.title)}</strong><span>${b(i.created_at)}</span>
241
340
  </button>`;
242
341
  }).join("")}</div>
243
342
  </aside>
244
343
  <main class="po-chat">
245
344
  <header><div><p>问数回答</p><h2>${this.currentThread ? u(this.currentThread.title) : "未选择问答"}</h2></div><span>Markdown · 流式输出</span></header>
246
345
  <section class="po-messages">
247
- ${this.messages.map((t) => `<article class="po-message ${t.role}"><b>${t.role === "user" ? "你" : "PageOps 分析"}</b><div>${t.role === "assistant" ? S(t.content) : u(t.content)}</div></article>`).join("")}
248
- ${this.streaming ? `<article class="po-message assistant streaming"><b>PageOps 分析</b><div>${S(this.streaming)}</div></article>` : ""}
346
+ ${this.messages.map((i) => `<article class="po-message ${i.role}"><b>${i.role === "user" ? "你" : "PageOps 分析"}</b><div>${i.role === "assistant" ? w(i.content) : u(i.content)}</div></article>`).join("")}
347
+ ${this.renderAnswerState()}
249
348
  </section>
250
- <form class="po-composer"><textarea ${this.sourceSnapshots.length ? "" : "disabled"} placeholder="${this.sourceSnapshots.length ? "请输入页面分析问题,Enter 发送,Shift + Enter 换行" : "请先上传代码包后再提问"}"></textarea><button type="submit" ${this.sourceSnapshots.length ? "" : "disabled"}>${this.sourceSnapshots.length ? "发送" : "请先上传代码包"}</button></form>
349
+ <form class="po-composer"><textarea ${s ? "disabled" : ""} placeholder="${u(e)}"></textarea><button type="submit" ${s ? "disabled" : ""}>${t ? "暂不可提问" : this.asking ? "回答中" : "发送"}</button></form>
251
350
  </main>
252
351
  <aside class="po-trace"><header><h2>执行过程</h2><button data-action="close">×</button></header><section>${this.renderSourceUploader()}${this.renderSteps()}</section></aside>
253
- `, this.bindPanelEvents());
352
+ `, this.bindPanelEvents(), this.asking) {
353
+ const i = this.panel.querySelector(".po-messages");
354
+ i && (i.scrollTop = i.scrollHeight);
355
+ }
356
+ }
357
+ renderAnswerState() {
358
+ const t = this.asking && this.waitingForFirstContent ? '<article class="po-message assistant waiting" role="status" aria-live="polite"><b>PageOps 分析</b><div class="po-ai-waiting"><span class="po-ai-spinner" aria-hidden="true"></span><span>正在理解问题并检索证据</span></div></article>' : "", e = this.streaming ? `<article class="po-message assistant streaming"><b>PageOps 分析</b><div><span data-streaming-content>${w(this.streaming)}</span>${this.asking ? '<span class="po-typing-cursor" aria-hidden="true"></span>' : ""}</div></article>` : "", s = this.answerError ? `<article class="po-message assistant answer-error" role="alert"><b>PageOps 分析</b><strong>本次回答失败</strong><div>${u(this.answerError)}</div></article>` : "";
359
+ return `${t}${e}${s}`;
254
360
  }
255
361
  renderSourceUploader() {
256
362
  return `
@@ -268,8 +374,9 @@ class T {
268
374
  `;
269
375
  }
270
376
  renderSourceItem(t) {
271
- const e = t.filename || "未命名代码包", s = t.created_at ? b(t.created_at) : "刚刚上传", n = U(t.archive_bytes || t.total_bytes || 0);
272
- return `<article class="po-source-item"><strong>${u(e)}</strong><span>${u(s)} · ${u(n)}</span></article>`;
377
+ var l, d, c;
378
+ const e = t.filename || "未命名代码包", s = t.created_at ? b(t.created_at) : "刚刚上传", i = F(t.archive_bytes || t.total_bytes || 0), r = String((d = (l = t.metadata) == null ? void 0 : l.analysis_status) != null ? d : "unknown"), o = (c = { pending: "项目记忆等待更新", running: "项目记忆更新中", ready: "项目记忆已就绪", failed: "项目记忆更新失败" }[r]) != null ? c : "项目记忆状态未知";
379
+ return `<article class="po-source-item"><strong>${u(e)}</strong><span>${u(s)} · ${u(i)}</span><span>${u(o)}</span></article>`;
273
380
  }
274
381
  renderSteps() {
275
382
  return (this.steps.length ? this.steps : [{ id: "idle", title: "等待任务", status: "pending", details: { message: "发送消息后展示执行过程。" } }]).map((e) => {
@@ -278,43 +385,43 @@ class T {
278
385
  }).join("");
279
386
  }
280
387
  bindPanelEvents() {
281
- var t, e, s, n, o, r, l, m, d, g, y;
282
- (e = (t = this.panel) == null ? void 0 : t.querySelector('[data-action="new"]')) == null || e.addEventListener("click", () => void this.newConversation()), (n = (s = this.panel) == null ? void 0 : s.querySelector('[data-action="close"]')) == null || n.addEventListener("click", () => this.close()), (r = (o = this.panel) == null ? void 0 : o.querySelector('[data-action="upload-source"]')) == null || r.addEventListener("change", (h) => {
388
+ var t, e, s, i, r, o, l, d, c, m, v;
389
+ (e = (t = this.panel) == null ? void 0 : t.querySelector('[data-action="new"]')) == null || e.addEventListener("click", () => void this.newConversation()), (i = (s = this.panel) == null ? void 0 : s.querySelector('[data-action="close"]')) == null || i.addEventListener("click", () => this.close()), (o = (r = this.panel) == null ? void 0 : r.querySelector('[data-action="upload-source"]')) == null || o.addEventListener("change", (g) => {
283
390
  var p;
284
- const a = (p = h.target.files) == null ? void 0 : p[0];
285
- a && this.uploadSource(a);
286
- }), (l = this.panel) == null || l.querySelectorAll("[data-thread]").forEach((h) => {
287
- h.addEventListener("click", () => {
288
- const a = this.conversations.find((p) => p.id === h.dataset.thread);
289
- a && this.selectThread(a);
391
+ const h = (p = g.target.files) == null ? void 0 : p[0];
392
+ h && this.uploadSource(h);
393
+ }), (l = this.panel) == null || l.querySelectorAll("[data-thread]").forEach((g) => {
394
+ g.addEventListener("click", () => {
395
+ const h = this.conversations.find((p) => p.id === g.dataset.thread);
396
+ h && this.selectThread(h);
290
397
  });
291
- }), (d = (m = this.panel) == null ? void 0 : m.querySelector("form")) == null || d.addEventListener("submit", (h) => {
292
- var v;
293
- h.preventDefault();
294
- const a = (v = this.panel) == null ? void 0 : v.querySelector("textarea"), p = a == null ? void 0 : a.value.trim();
295
- p && (a.value = "", this.ask(p));
296
- }), (y = (g = this.panel) == null ? void 0 : g.querySelector("textarea")) == null || y.addEventListener("keydown", (h) => {
297
- var p, v;
298
- const a = h;
299
- a.key === "Enter" && !a.shiftKey && (a.preventDefault(), (v = (p = this.panel) == null ? void 0 : p.querySelector("form")) == null || v.requestSubmit());
398
+ }), (c = (d = this.panel) == null ? void 0 : d.querySelector("form")) == null || c.addEventListener("submit", (g) => {
399
+ var y;
400
+ g.preventDefault();
401
+ const h = (y = this.panel) == null ? void 0 : y.querySelector("textarea"), p = h == null ? void 0 : h.value.trim();
402
+ p && (h.value = "", this.ask(p));
403
+ }), (v = (m = this.panel) == null ? void 0 : m.querySelector("textarea")) == null || v.addEventListener("keydown", (g) => {
404
+ var p, y;
405
+ const h = g;
406
+ h.key === "Enter" && !h.shiftKey && (h.preventDefault(), (y = (p = this.panel) == null ? void 0 : p.querySelector("form")) == null || y.requestSubmit());
300
407
  });
301
408
  }
302
409
  }
303
- function u(i) {
304
- return i.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
410
+ function u(n) {
411
+ return n.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
305
412
  }
306
- function b(i) {
307
- return new Intl.DateTimeFormat("zh-CN", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }).format(new Date(i));
413
+ function b(n) {
414
+ return new Intl.DateTimeFormat("zh-CN", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }).format(new Date(n));
308
415
  }
309
- function U(i) {
310
- if (!i) return "0 B";
416
+ function F(n) {
417
+ if (!n) return "0 B";
311
418
  const t = ["B", "KB", "MB", "GB"];
312
- let e = i, s = 0;
419
+ let e = n, s = 0;
313
420
  for (; e >= 1024 && s < t.length - 1; )
314
421
  e /= 1024, s += 1;
315
422
  return `${e >= 10 || s === 0 ? e.toFixed(0) : e.toFixed(1)} ${t[s]}`;
316
423
  }
317
- const _ = new T();
424
+ const _ = new q();
318
425
  export {
319
426
  _ as PageOpsSDK
320
427
  };
@@ -1,27 +1,25 @@
1
- (function(d,l){typeof exports=="object"&&typeof module!="undefined"?l(exports):typeof define=="function"&&define.amd?define(["exports"],l):(d=typeof globalThis!="undefined"?globalThis:d||self,l(d.PageOpsSDK={}))})(this,(function(d){"use strict";var K=Object.defineProperty;var O=(d,l,y)=>l in d?K(d,l,{enumerable:!0,configurable:!0,writable:!0,value:y}):d[l]=y;var c=(d,l,y)=>O(d,typeof l!="symbol"?l+"":l,y);class l{constructor(t){this.options=t}async createContext(t=(n=>(n=(e=>(s=>(s=(e=this.options).getPageContext)==null?void 0:s.call(e))())())!=null?n:{})()){var i,r,h;return this.request("/context/session",{method:"POST",body:JSON.stringify({app_id:this.options.appId,env:this.options.env,route:t.route,url:(i=t.url)!=null?i:location.href,title:(r=t.title)!=null?r:document.title,menu_path:(h=t.menuPath)!=null?h:[],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 r,h;const s=(e==null?void 0:e.body)instanceof FormData?e.headers:{"content-type":"application/json",...(r=e==null?void 0:e.headers)!=null?r:{}},n=await fetch(`${this.base()}${t}`,{...e,headers:s}),i=await n.json();if(!n.ok)throw new Error((h=i.message)!=null?h:"PageOps 请求失败");return i}base(){const t=this.options.apiBase.replace(/\/$/,"");return t.endsWith("/api")?t:`${t}/api`}}function y(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function v(o){return y(o).replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>")}function x(o,t){const e=o[t],s=o[t+1];if(!(e!=null&&e.includes("|"))||!/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s!=null?s:""))return null;const n=[];let i=t;for(;i<o.length&&o[i].includes("|")&&o[i].trim();)n.push(o[i]),i+=1;const r=g=>g.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(f=>v(f.trim())),h=r(n[0]).map(g=>`<th>${g}</th>`).join(""),S=n.slice(2).map(g=>`<tr>${r(g).map(f=>`<td>${f}</td>`).join("")}</tr>`).join("");return{html:`<table><thead><tr>${h}</tr></thead><tbody>${S}</tbody></table>`,next:i}}function P(o){const t=o.split(`
2
- `),e=[];for(let s=0;s<t.length;s+=1){const n=t[s];if(n.trim().startsWith("```")){const r=[];for(s+=1;s<t.length&&!t[s].trim().startsWith("```");)r.push(t[s]),s+=1;e.push(`<pre><code>${y(r.join(`
3
- `))}</code></pre>`);continue}const i=x(t,s);if(i){e.push(i.html),s=i.next-1;continue}n.startsWith("### ")?e.push(`<h4>${v(n.slice(4))}</h4>`):n.startsWith("## ")?e.push(`<h3>${v(n.slice(3))}</h3>`):n.startsWith("# ")?e.push(`<h2>${v(n.slice(2))}</h2>`):n.startsWith("- ")?e.push(`<li>${v(n.slice(2))}</li>`):n.trim()?e.push(`<p>${v(n)}</p>`):e.push("<br>")}return e.join("")}async function C(o,t){var i,r,h;const e=o.getReader(),s=new TextDecoder;let n="";for(;;){const{done:S,value:g}=await e.read();if(S)break;n+=s.decode(g,{stream:!0});const f=n.split(`
4
-
5
- `);n=(i=f.pop())!=null?i:"";for(const $ of f){const p=(r=$.match(/^event: (.+)$/m))==null?void 0:r[1],a=(h=$.match(/^data: (.+)$/m))==null?void 0:h[1];p&&a&&t(p,JSON.parse(a))}}}class T{constructor(){c(this,"client",null);c(this,"options",null);c(this,"root",null);c(this,"panel",null);c(this,"context",null);c(this,"contextKey","");c(this,"selectedPageKey","");c(this,"currentThread",null);c(this,"conversations",[]);c(this,"messages",[]);c(this,"steps",[]);c(this,"sourceSnapshots",[]);c(this,"sourceUploadStatus","");c(this,"sourceUploadError","");c(this,"sourceUploading",!1);c(this,"streaming","")}mount(t){var e;this.unmount(),this.options=t,this.client=new l(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.contextKey="",this.selectedPageKey="",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 l(this.options),this.context=null,this.contextKey="")}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.client||!this.options)throw new Error("PageOps SDK 未初始化");const t=this.getPageContext(),e=this.getPageContextKey(t);return this.context&&this.contextKey===e?this.context:(this.context=await this.client.createContext(t),this.contextKey=e,this.context)}getPageContext(){var t,e,s;return(s=(e=(t=this.options)==null?void 0:t.getPageContext)==null?void 0:e.call(t))!=null?s:{}}getPageContextKey(t){var e,s,n,i;return JSON.stringify([(e=t.route)!=null?e:"",(s=t.url)!=null?s:location.href,(n=t.title)!=null?n:document.title,(i=t.menuPath)!=null?i:[]])}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(){var s;if(!this.client)return;const t=await this.ensureContext(),e=(s=t.menu_path)!=null&&s.length?t.menu_path.join(" / "):t.route||document.title||"新的问答";this.currentThread=await this.client.createConversation(t.id,e),this.selectedPageKey=this.contextKey,this.conversations=[this.currentThread,...this.conversations],this.messages=[],this.steps=[],this.streaming="",this.renderPanel()}async selectThread(t){this.client&&(this.currentThread=t,this.selectedPageKey=this.getPageContextKey(this.getPageContext()),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}const e=this.getPageContextKey(this.getPageContext());if(this.currentThread&&this.selectedPageKey&&this.selectedPageKey!==e&&(this.currentThread=null),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 s=await this.client.streamQuestion(this.currentThread.id,t);if(!s.ok||!s.body)throw new Error("PageOps 流式问答失败");await C(s.body,(n,i)=>{var r;n==="step"&&this.upsertStep(i),n==="delta"&&(this.streaming+=String((r=i.content)!=null?r:"")),n==="done"&&this.selectThread(this.currentThread),n==="error"&&this.upsertStep({id:"error",title:"执行失败",status:"failed",details:i}),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=`
1
+ (function(p,h){typeof exports=="object"&&typeof module!="undefined"?h(exports):typeof define=="function"&&define.amd?define(["exports"],h):(p=typeof globalThis!="undefined"?globalThis:p||self,h(p.PageOpsSDK={}))})(this,(function(p){"use strict";var j=Object.defineProperty;var F=(p,h,y)=>h in p?j(p,h,{enumerable:!0,configurable:!0,writable:!0,value:y}):p[h]=y;var a=(p,h,y)=>F(p,typeof h!="symbol"?h+"":h,y);class h{constructor(e){this.options=e}async createContext(e=(i=>(i=(t=>(s=>(s=(t=this.options).getPageContext)==null?void 0:s.call(t))())())!=null?i:{})()){var r,o,l;return this.request("/context/session",{method:"POST",body:JSON.stringify({app_id:this.options.appId,env:this.options.env,route:e.route,url:(r=e.url)!=null?r:location.href,title:(o=e.title)!=null?o:document.title,menu_path:(l=e.menuPath)!=null?l:[],tenant_id:e.tenantId,user_role:e.userRole,build_version:e.buildVersion})})}async listConversations(){return(await this.request(`/conversations?app_id=${encodeURIComponent(this.options.appId)}`)).conversations}async createConversation(e,t){return this.request("/conversations",{method:"POST",body:JSON.stringify({app_id:this.options.appId,context_session_id:e,title:t})})}async listMessages(e){return(await this.request(`/conversations/${encodeURIComponent(e)}/messages?app_id=${encodeURIComponent(this.options.appId)}`)).messages}async listSources(){return(await this.request(`/sources?project_id=${encodeURIComponent(this.options.appId)}`)).sources}uploadSource(e){const t=new FormData;return t.append("file",e),this.request(`/sources/upload?project_id=${encodeURIComponent(this.options.appId)}`,{method:"POST",body:t,headers:{}})}streamQuestion(e,t){return fetch(`${this.base()}/question/stream`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:this.options.appId,thread_id:e,question:t})})}async request(e,t){var o,l;const s=(t==null?void 0:t.body)instanceof FormData?t.headers:{"content-type":"application/json",...(o=t==null?void 0:t.headers)!=null?o:{}},i=await fetch(`${this.base()}${e}`,{...t,headers:s}),r=await i.json();if(!i.ok)throw new Error((l=r.message)!=null?l:"PageOps 请求失败");return r}base(){const e=this.options.apiBase.replace(/\/$/,"");return e.endsWith("/api")?e:`${e}/api`}}async function y(n,e){const t=await n.json().catch(()=>null);return typeof(t==null?void 0:t.message)=="string"&&t.message.trim()?t.message:e}function b(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function w(n){return b(n).replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>")}function T(n,e){const t=n[e],s=n[e+1];if(!(t!=null&&t.includes("|"))||!/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s!=null?s:""))return null;const i=[];let r=e;for(;r<n.length&&n[r].includes("|")&&n[r].trim();)i.push(n[r]),r+=1;const o=d=>d.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(S=>w(S.trim())),l=o(i[0]).map(d=>`<th>${d}</th>`).join(""),g=i.slice(2).map(d=>`<tr>${o(d).map(S=>`<td>${S}</td>`).join("")}</tr>`).join("");return{html:`<table><thead><tr>${l}</tr></thead><tbody>${g}</tbody></table>`,next:r}}function $(n){const e=n.split(`
2
+ `),t=[];for(let s=0;s<e.length;s+=1){const i=e[s];if(i.trim().startsWith("```")){const o=[];for(s+=1;s<e.length&&!e[s].trim().startsWith("```");)o.push(e[s]),s+=1;t.push(`<pre><code>${b(o.join(`
3
+ `))}</code></pre>`);continue}const r=T(e,s);if(r){t.push(r.html),s=r.next-1;continue}i.startsWith("### ")?t.push(`<h4>${w(i.slice(4))}</h4>`):i.startsWith("## ")?t.push(`<h3>${w(i.slice(3))}</h3>`):i.startsWith("# ")?t.push(`<h2>${w(i.slice(2))}</h2>`):i.startsWith("- ")?t.push(`<li>${w(i.slice(2))}</li>`):i.trim()?t.push(`<p>${w(i)}</p>`):t.push("<br>")}return t.join("")}async function x(n,e){var r;const t=n.getReader(),s=new TextDecoder;let i="";for(;;){const{done:o,value:l}=await t.read();if(o){i+=s.decode();break}i+=s.decode(l,{stream:!0});const g=i.split(/\r?\n\r?\n/);i=(r=g.pop())!=null?r:"";for(const d of g)P(d,e)}i.trim()&&P(i,e)}function P(n,e){var i,r;const t=(i=n.match(/^event:\s*(.+)$/m))==null?void 0:i[1],s=(r=n.match(/^data:\s*(.+)$/m))==null?void 0:r[1];t&&s&&e(t,JSON.parse(s))}class k{constructor(e,t=16){a(this,"queue",[]);a(this,"timer",null);a(this,"drainWaiters",[]);this.onChunk=e,this.interval=t}enqueue(e){this.queue.push(...Array.from(e)),this.timer||this.tick()}async drain(){!this.timer&&!this.queue.length||await new Promise(e=>this.drainWaiters.push(e))}clear(){this.timer&&clearTimeout(this.timer),this.timer=null,this.queue=[],this.resolveDrainWaiters()}tick(){const e=Math.max(1,Math.ceil(this.queue.length/90)),t=this.queue.splice(0,e).join("");if(t&&this.onChunk(t),!this.queue.length){this.timer=null,this.resolveDrainWaiters();return}this.timer=setTimeout(()=>this.tick(),this.interval)}resolveDrainWaiters(){for(const e of this.drainWaiters.splice(0))e()}}class U{constructor(){a(this,"client",null);a(this,"options",null);a(this,"root",null);a(this,"panel",null);a(this,"context",null);a(this,"contextKey","");a(this,"selectedPageKey","");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,"sourceRefreshTimer",null);a(this,"streaming","");a(this,"asking",!1);a(this,"waitingForFirstContent",!1);a(this,"answerError","");a(this,"streamFailure","");a(this,"streamDone",null);a(this,"typewriter",new k(e=>{this.streaming+=e,this.updateStreamingMessage()}))}mount(e){var t;this.unmount(),this.options=e,this.client=new h(e),this.root=document.createElement("div"),this.root.className="pageops-sdk",((t=e.container)!=null?t:document.body).appendChild(this.root),this.renderClosed()}unmount(){var e;this.stopSourceRefresh(),this.resetAnswerState(),(e=this.root)==null||e.remove(),this.root=null,this.panel=null,this.context=null,this.contextKey="",this.selectedPageKey="",this.currentThread=null,this.conversations=[],this.messages=[],this.steps=[],this.sourceSnapshots=[],this.sourceUploadStatus="",this.sourceUploadError="",this.sourceUploading=!1}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.stopSourceRefresh(),this.renderClosed()}updateContext(e){this.options&&(this.options={...this.options,...e},this.client=new h(this.options),this.context=null,this.contextKey="")}renderClosed(){var e;this.root&&(this.root.innerHTML='<button class="po-fab" type="button">多轮问答</button>',(e=this.root.querySelector("button"))==null||e.addEventListener("click",()=>this.open()))}async ensureContext(){if(!this.client||!this.options)throw new Error("PageOps SDK 未初始化");const e=this.getPageContext(),t=this.getPageContextKey(e);return this.context&&this.contextKey===t?this.context:(this.context=await this.client.createContext(e),this.contextKey=t,this.context)}getPageContext(){var e,t,s;return(s=(t=(e=this.options)==null?void 0:e.getPageContext)==null?void 0:t.call(e))!=null?s:{}}getPageContextKey(e){var t,s,i,r;return JSON.stringify([(t=e.route)!=null?t:"",(s=e.url)!=null?s:location.href,(i=e.title)!=null?i:document.title,(r=e.menuPath)!=null?r:[]])}async loadSources(){if(this.client){try{this.sourceSnapshots=await this.client.listSources(),this.sourceUploadError=""}catch(e){this.sourceUploadError=e instanceof Error?e.message:"源码包状态加载失败"}this.scheduleSourceRefresh(),this.renderPanel()}}async loadConversations(){this.client&&(this.conversations=await this.client.listConversations(),this.renderPanel())}async newConversation(){var s;if(!this.client)return;const e=await this.ensureContext(),t=(s=e.menu_path)!=null&&s.length?e.menu_path.join(" / "):e.route||document.title||"新的问答";this.currentThread=await this.client.createConversation(e.id,t),this.selectedPageKey=this.contextKey,this.conversations=[this.currentThread,...this.conversations],this.messages=[],this.steps=[],this.streaming="",this.answerError="",this.renderPanel()}async selectThread(e){this.client&&(this.currentThread=e,this.selectedPageKey=this.getPageContextKey(this.getPageContext()),this.messages=await this.client.listMessages(e.id),this.steps=[],this.streaming="",this.answerError="",this.renderPanel())}async uploadSource(e){if(this.client){this.sourceUploading=!0,this.sourceUploadStatus="上传中...",this.sourceUploadError="",this.renderPanel();try{await this.client.uploadSource(e),this.sourceSnapshots=await this.client.listSources(),this.sourceUploadStatus=this.isProjectMemoryUpdating()?"源码上传完成,项目记忆更新中...":"上传完成",this.scheduleSourceRefresh()}catch(t){this.sourceUploadError=t instanceof Error?t.message:"源码包上传失败",this.sourceUploadStatus=""}finally{this.sourceUploading=!1,this.renderPanel()}}}async ask(e){if(!this.client||this.asking)return;const t=this.questionUnavailableReason();if(t){this.sourceUploadError=t,this.renderPanel();return}this.resetAnswerState(),this.asking=!0,this.waitingForFirstContent=!0,this.renderPanel();try{const s=this.getPageContextKey(this.getPageContext());if(this.currentThread&&this.selectedPageKey&&this.selectedPageKey!==s&&(this.currentThread=null),this.currentThread||await this.newConversation(),!this.currentThread)throw new Error("无法创建问答会话,请稍后重试。");this.messages.push({id:`local-${Date.now()}`,role:"user",content:e,metadata_json:{}}),this.steps=[],this.renderPanel();const i=await this.client.streamQuestion(this.currentThread.id,e);if(!i.ok)throw new Error(await y(i,"服务暂时无法回答,请稍后重试。"));if(!i.body)throw new Error("服务未返回有效的流式响应,请稍后重试。");if(await x(i.body,(r,o)=>this.handleStreamEvent(r,o)),this.streamFailure)throw new Error(this.streamFailure);if(!this.streamDone)throw new Error("服务响应意外中断,请稍后重试。");await this.typewriter.drain(),await this.selectThread(this.currentThread)}catch(s){this.typewriter.clear(),this.waitingForFirstContent=!1,this.answerError=s instanceof Error?s.message:"服务异常,请稍后重试。",this.upsertStep({id:"error",title:"执行失败",status:"failed",details:{message:this.answerError}})}finally{this.asking=!1,this.waitingForFirstContent=!1,this.renderPanel()}}handleStreamEvent(e,t){var s,i;if(e==="step"){this.upsertStep(t),this.renderPanel();return}if(e==="delta"){const r=String((s=t.content)!=null?s:"");if(!r)return;this.waitingForFirstContent=!1,this.typewriter.enqueue(r);return}e==="done"&&(this.streamDone=t),e==="error"&&(this.streamFailure=String((i=t.message)!=null?i:"服务异常,请稍后重试。"))}updateStreamingMessage(){var s,i;const e=(s=this.panel)==null?void 0:s.querySelector("[data-streaming-content]");if(!e){this.renderPanel();return}e.innerHTML=$(this.streaming);const t=(i=this.panel)==null?void 0:i.querySelector(".po-messages");t&&(t.scrollTop=t.scrollHeight)}resetAnswerState(){this.typewriter.clear(),this.asking=!1,this.waitingForFirstContent=!1,this.answerError="",this.streamFailure="",this.streamDone=null,this.streaming=""}upsertStep(e){const t=this.steps.findIndex(s=>s.id===e.id);this.steps=t===-1?[...this.steps,e]:this.steps.map(s=>s.id===e.id?{...s,...e}:s)}latestAnalysisStatus(){var e,t,s;return String((s=(t=(e=this.sourceSnapshots[0])==null?void 0:e.metadata)==null?void 0:t.analysis_status)!=null?s:"")}isProjectMemoryUpdating(){return["pending","running"].includes(this.latestAnalysisStatus())}questionUnavailableReason(){return this.sourceSnapshots.length?this.isProjectMemoryUpdating()?"项目记忆正在更新,完成前暂不能问答。":this.latestAnalysisStatus()==="failed"?"项目记忆更新失败,请重新上传或重新索引。":"":"请先上传代码包后再提问。"}scheduleSourceRefresh(){this.stopSourceRefresh(),this.isProjectMemoryUpdating()&&(this.sourceRefreshTimer=setTimeout(()=>void this.loadSources(),1500))}stopSourceRefresh(){this.sourceRefreshTimer&&clearTimeout(this.sourceRefreshTimer),this.sourceRefreshTimer=null}renderPanel(){if(!this.panel)return;const e=this.questionUnavailableReason(),t=e||(this.asking?"回答生成中,请稍候":"请输入页面分析问题,Enter 发送,Shift + Enter 换行"),s=!!(e||this.asking);if(this.panel.innerHTML=`
6
4
  <aside class="po-sidebar">
7
5
  <div class="po-brand"><div class="po-logo"></div><div><strong>PageOps 问答</strong><span>页面工程专家</span></div></div>
8
- <button class="po-new" data-action="new">+ 新建问答</button>
6
+ <button class="po-new" data-action="new" ${this.asking?"disabled":""}>+ 新建问答</button>
9
7
  <input class="po-search" placeholder="搜索问答" />
10
- <div class="po-thread-list">${this.conversations.map(t=>{var e;return`
11
- <button class="po-thread ${t.id===((e=this.currentThread)==null?void 0:e.id)?"active":""}" data-thread="${t.id}">
12
- <strong>${u(t.title)}</strong><span>${w(t.created_at)}</span>
8
+ <div class="po-thread-list">${this.conversations.map(i=>{var r;return`
9
+ <button class="po-thread ${i.id===((r=this.currentThread)==null?void 0:r.id)?"active":""}" data-thread="${i.id}" ${this.asking?"disabled":""}>
10
+ <strong>${u(i.title)}</strong><span>${E(i.created_at)}</span>
13
11
  </button>`}).join("")}</div>
14
12
  </aside>
15
13
  <main class="po-chat">
16
14
  <header><div><p>问数回答</p><h2>${this.currentThread?u(this.currentThread.title):"未选择问答"}</h2></div><span>Markdown · 流式输出</span></header>
17
15
  <section class="po-messages">
18
- ${this.messages.map(t=>`<article class="po-message ${t.role}"><b>${t.role==="user"?"你":"PageOps 分析"}</b><div>${t.role==="assistant"?P(t.content):u(t.content)}</div></article>`).join("")}
19
- ${this.streaming?`<article class="po-message assistant streaming"><b>PageOps 分析</b><div>${P(this.streaming)}</div></article>`:""}
16
+ ${this.messages.map(i=>`<article class="po-message ${i.role}"><b>${i.role==="user"?"你":"PageOps 分析"}</b><div>${i.role==="assistant"?$(i.content):u(i.content)}</div></article>`).join("")}
17
+ ${this.renderAnswerState()}
20
18
  </section>
21
- <form class="po-composer"><textarea ${this.sourceSnapshots.length?"":"disabled"} placeholder="${this.sourceSnapshots.length?"请输入页面分析问题,Enter 发送,Shift + Enter 换行":"请先上传代码包后再提问"}"></textarea><button type="submit" ${this.sourceSnapshots.length?"":"disabled"}>${this.sourceSnapshots.length?"发送":"请先上传代码包"}</button></form>
19
+ <form class="po-composer"><textarea ${s?"disabled":""} placeholder="${u(t)}"></textarea><button type="submit" ${s?"disabled":""}>${e?"暂不可提问":this.asking?"回答中":"发送"}</button></form>
22
20
  </main>
23
21
  <aside class="po-trace"><header><h2>执行过程</h2><button data-action="close">×</button></header><section>${this.renderSourceUploader()}${this.renderSteps()}</section></aside>
24
- `,this.bindPanelEvents())}renderSourceUploader(){return`
22
+ `,this.bindPanelEvents(),this.asking){const i=this.panel.querySelector(".po-messages");i&&(i.scrollTop=i.scrollHeight)}}renderAnswerState(){const e=this.asking&&this.waitingForFirstContent?'<article class="po-message assistant waiting" role="status" aria-live="polite"><b>PageOps 分析</b><div class="po-ai-waiting"><span class="po-ai-spinner" aria-hidden="true"></span><span>正在理解问题并检索证据</span></div></article>':"",t=this.streaming?`<article class="po-message assistant streaming"><b>PageOps 分析</b><div><span data-streaming-content>${$(this.streaming)}</span>${this.asking?'<span class="po-typing-cursor" aria-hidden="true"></span>':""}</div></article>`:"",s=this.answerError?`<article class="po-message assistant answer-error" role="alert"><b>PageOps 分析</b><strong>本次回答失败</strong><div>${u(this.answerError)}</div></article>`:"";return`${e}${t}${s}`}renderSourceUploader(){return`
25
23
  <div class="po-source-uploader">
26
24
  <strong>源码包</strong>
27
25
  <p>上传 zip、tar、tar.gz 或 tgz 后,PageOps 将基于代码证据回答问题。</p>
@@ -30,7 +28,7 @@
30
28
  <input type="file" accept=".zip,.tar,.gz,.tgz" data-action="upload-source" ${this.sourceUploading?"disabled":""} />
31
29
  </label>
32
30
  ${this.sourceUploadStatus?`<p class="po-upload-status">${u(this.sourceUploadStatus)}</p>`:""}
33
- ${this.sourceSnapshots.length?`<div class="po-source-list">${this.sourceSnapshots.map(t=>this.renderSourceItem(t)).join("")}</div>`:'<p class="po-upload-empty">当前系统暂无代码包,请先上传后再提问。</p>'}
31
+ ${this.sourceSnapshots.length?`<div class="po-source-list">${this.sourceSnapshots.map(e=>this.renderSourceItem(e)).join("")}</div>`:'<p class="po-upload-empty">当前系统暂无代码包,请先上传后再提问。</p>'}
34
32
  ${this.sourceUploadError?`<p class="po-upload-error">${u(this.sourceUploadError)}</p>`:""}
35
33
  </div>
36
- `}renderSourceItem(t){const e=t.filename||"未命名代码包",s=t.created_at?w(t.created_at):"刚刚上传",n=E(t.archive_bytes||t.total_bytes||0);return`<article class="po-source-item"><strong>${u(e)}</strong><span>${u(s)} · ${u(n)}</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>${u(e.title)}</strong><span>${e.status}</span></summary><pre>${u(JSON.stringify((s=e.details)!=null?s:{},null,2))}</pre></details>`}).join("")}bindPanelEvents(){var t,e,s,n,i,r,h,S,g,f,$;(e=(t=this.panel)==null?void 0:t.querySelector('[data-action="new"]'))==null||e.addEventListener("click",()=>void this.newConversation()),(n=(s=this.panel)==null?void 0:s.querySelector('[data-action="close"]'))==null||n.addEventListener("click",()=>this.close()),(r=(i=this.panel)==null?void 0:i.querySelector('[data-action="upload-source"]'))==null||r.addEventListener("change",p=>{var m;const a=(m=p.target.files)==null?void 0:m[0];a&&this.uploadSource(a)}),(h=this.panel)==null||h.querySelectorAll("[data-thread]").forEach(p=>{p.addEventListener("click",()=>{const a=this.conversations.find(m=>m.id===p.dataset.thread);a&&this.selectThread(a)})}),(g=(S=this.panel)==null?void 0:S.querySelector("form"))==null||g.addEventListener("submit",p=>{var b;p.preventDefault();const a=(b=this.panel)==null?void 0:b.querySelector("textarea"),m=a==null?void 0:a.value.trim();m&&(a.value="",this.ask(m))}),($=(f=this.panel)==null?void 0:f.querySelector("textarea"))==null||$.addEventListener("keydown",p=>{var m,b;const a=p;a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),(b=(m=this.panel)==null?void 0:m.querySelector("form"))==null||b.requestSubmit())})}}function u(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function w(o){return new Intl.DateTimeFormat("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).format(new Date(o))}function E(o){if(!o)return"0 B";const t=["B","KB","MB","GB"];let e=o,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 U=new T;d.PageOpsSDK=U,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"})}));
34
+ `}renderSourceItem(e){var l,g,d;const t=e.filename||"未命名代码包",s=e.created_at?E(e.created_at):"刚刚上传",i=q(e.archive_bytes||e.total_bytes||0),r=String((g=(l=e.metadata)==null?void 0:l.analysis_status)!=null?g:"unknown"),o=(d={pending:"项目记忆等待更新",running:"项目记忆更新中",ready:"项目记忆已就绪",failed:"项目记忆更新失败"}[r])!=null?d:"项目记忆状态未知";return`<article class="po-source-item"><strong>${u(t)}</strong><span>${u(s)} · ${u(i)}</span><span>${u(o)}</span></article>`}renderSteps(){return(this.steps.length?this.steps:[{id:"idle",title:"等待任务",status:"pending",details:{message:"发送消息后展示执行过程。"}}]).map(t=>{var s;return`<details class="po-step ${t.status}" ${t.status==="running"||t.status==="failed"?"open":""}><summary><strong>${u(t.title)}</strong><span>${t.status}</span></summary><pre>${u(JSON.stringify((s=t.details)!=null?s:{},null,2))}</pre></details>`}).join("")}bindPanelEvents(){var e,t,s,i,r,o,l,g,d,S,C;(t=(e=this.panel)==null?void 0:e.querySelector('[data-action="new"]'))==null||t.addEventListener("click",()=>void this.newConversation()),(i=(s=this.panel)==null?void 0:s.querySelector('[data-action="close"]'))==null||i.addEventListener("click",()=>this.close()),(o=(r=this.panel)==null?void 0:r.querySelector('[data-action="upload-source"]'))==null||o.addEventListener("change",f=>{var m;const c=(m=f.target.files)==null?void 0:m[0];c&&this.uploadSource(c)}),(l=this.panel)==null||l.querySelectorAll("[data-thread]").forEach(f=>{f.addEventListener("click",()=>{const c=this.conversations.find(m=>m.id===f.dataset.thread);c&&this.selectThread(c)})}),(d=(g=this.panel)==null?void 0:g.querySelector("form"))==null||d.addEventListener("submit",f=>{var v;f.preventDefault();const c=(v=this.panel)==null?void 0:v.querySelector("textarea"),m=c==null?void 0:c.value.trim();m&&(c.value="",this.ask(m))}),(C=(S=this.panel)==null?void 0:S.querySelector("textarea"))==null||C.addEventListener("keydown",f=>{var m,v;const c=f;c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),(v=(m=this.panel)==null?void 0:m.querySelector("form"))==null||v.requestSubmit())})}}function u(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function E(n){return new Intl.DateTimeFormat("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).format(new Date(n))}function q(n){if(!n)return"0 B";const e=["B","KB","MB","GB"];let t=n,s=0;for(;t>=1024&&s<e.length-1;)t/=1024,s+=1;return`${t>=10||s===0?t.toFixed(0):t.toFixed(1)} ${e[s]}`}const K=new U;p.PageOpsSDK=K,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"})}));
package/dist/types.d.ts CHANGED
@@ -56,6 +56,7 @@ export interface SourceSnapshot {
56
56
  file_count: number;
57
57
  total_bytes?: number;
58
58
  created_at?: string | null;
59
+ metadata?: Record<string, unknown>;
59
60
  }
60
61
  export interface SourceSnapshotListResponse {
61
62
  sources: SourceSnapshot[];
@@ -0,0 +1,13 @@
1
+ export declare class TypewriterQueue {
2
+ private readonly onChunk;
3
+ private readonly interval;
4
+ private queue;
5
+ private timer;
6
+ private drainWaiters;
7
+ constructor(onChunk: (chunk: string) => void, interval?: number);
8
+ enqueue(content: string): void;
9
+ drain(): Promise<void>;
10
+ clear(): void;
11
+ private tick;
12
+ private resolveDrainWaiters;
13
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pageops/sdk",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "description": "PageOps embeddable frontend SDK",
5
5
  "type": "module",
6
6
  "main": "dist/pageops-sdk.umd.cjs",
@@ -15,16 +15,21 @@
15
15
  },
16
16
  "./dist/pageops-sdk.css": "./dist/pageops-sdk.css"
17
17
  },
18
- "files": ["dist"],
18
+ "files": [
19
+ "dist"
20
+ ],
19
21
  "scripts": {
20
22
  "build": "vite build && tsc --emitDeclarationOnly",
21
- "pack:check": "npm pack --dry-run"
23
+ "pack:check": "npm pack --dry-run",
24
+ "test": "vitest run"
22
25
  },
23
26
  "dependencies": {},
24
27
  "devDependencies": {
25
28
  "@types/node": "22.10.2",
29
+ "jsdom": "25.0.1",
26
30
  "typescript": "5.8.3",
27
- "vite": "6.3.5"
31
+ "vite": "6.3.5",
32
+ "vitest": "3.2.4"
28
33
  },
29
34
  "engines": {
30
35
  "node": ">=20"