wi-chat 0.0.0-stage → 0.3.0

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.
Files changed (95) hide show
  1. package/dist/core/index.cjs +2 -0
  2. package/dist/core/index.d.ts +13 -0
  3. package/dist/core/index.js +454 -0
  4. package/dist/core/useAgent.d.ts +35 -0
  5. package/dist/core/useChat.d.ts +195 -0
  6. package/dist/core/useChatSession.d.ts +89 -0
  7. package/dist/core/useHistory.d.ts +63 -0
  8. package/dist/index.cjs +2 -0
  9. package/dist/index.d.ts +11 -0
  10. package/dist/index.js +76 -0
  11. package/dist/mobile-ui/chat/ChatContainer.vue.d.ts +124 -0
  12. package/dist/mobile-ui/chat/ChatMessagesView.vue.d.ts +72 -0
  13. package/dist/mobile-ui/chat/types.d.ts +9 -0
  14. package/dist/mobile-ui/index.cjs +2 -0
  15. package/dist/mobile-ui/index.d.ts +7 -0
  16. package/dist/mobile-ui/index.js +218 -0
  17. package/dist/mobile-ui/inputbox/Inputbox.vue.d.ts +95 -0
  18. package/dist/mobile-ui/style.css +1 -0
  19. package/dist/parser/answer.d.ts +51 -0
  20. package/dist/parser/answerCom/iframePage/parseIframePage.d.ts +49 -0
  21. package/dist/parser/answerCom/iframePage/types.d.ts +11 -0
  22. package/dist/parser/answerCom/knowledgeStream/parseKnowledgeStream.d.ts +54 -0
  23. package/dist/parser/answerCom/knowledgeStream/types.d.ts +27 -0
  24. package/dist/parser/answerCom/recordset/parseRecordset.d.ts +48 -0
  25. package/dist/parser/answerCom/recordset/types.d.ts +36 -0
  26. package/dist/parser/attach/attachActions.d.ts +43 -0
  27. package/dist/parser/attach/index.d.ts +9 -0
  28. package/dist/parser/attach/parseAttach.d.ts +27 -0
  29. package/dist/parser/attach/types.d.ts +48 -0
  30. package/dist/parser/deepThinking/parseDeepThinking.d.ts +30 -0
  31. package/dist/parser/deepThinking/types.d.ts +14 -0
  32. package/dist/parser/history/history.d.ts +54 -0
  33. package/dist/parser/history/index.d.ts +7 -0
  34. package/dist/parser/index.cjs +3 -0
  35. package/dist/parser/index.d.ts +42 -0
  36. package/dist/parser/index.js +439 -0
  37. package/dist/parser/message.d.ts +60 -0
  38. package/dist/parser/registry.d.ts +81 -0
  39. package/dist/parser/sse.d.ts +34 -0
  40. package/dist/parser/stream.d.ts +8 -0
  41. package/dist/renderers/aiAnswer/AiAnswerBubble.vue.d.ts +58 -0
  42. package/dist/renderers/aiAnswer/contentMap.d.ts +13 -0
  43. package/dist/renderers/deepThinking/DeepThinkingSteps.vue.d.ts +21 -0
  44. package/dist/renderers/iframePage/IframePage.vue.d.ts +19 -0
  45. package/dist/renderers/iframePage/useIframePage.d.ts +64 -0
  46. package/dist/renderers/index.cjs +2 -0
  47. package/dist/renderers/index.d.ts +9 -0
  48. package/dist/renderers/index.js +243 -0
  49. package/dist/renderers/knowledgeStream/KnowledgeStreamResult.vue.d.ts +19 -0
  50. package/dist/renderers/style.css +1 -0
  51. package/dist/request/api.d.ts +132 -0
  52. package/dist/request/client.d.ts +30 -0
  53. package/dist/request/index.cjs +4 -0
  54. package/dist/request/index.d.ts +18 -0
  55. package/dist/request/index.js +264 -0
  56. package/dist/request/login.d.ts +37 -0
  57. package/dist/request/ws.d.ts +91 -0
  58. package/dist/style.css +24 -0
  59. package/dist/styles/github.css +2 -0
  60. package/dist/styles/katex.css +2 -0
  61. package/dist/theme/index.cjs +3 -0
  62. package/dist/theme/index.d.ts +3 -0
  63. package/dist/theme/index.js +37 -0
  64. package/dist/theme/theme.d.ts +40 -0
  65. package/dist/tools/attachDownload.d.ts +20 -0
  66. package/dist/tools/index.cjs +17 -0
  67. package/dist/tools/index.d.ts +8 -0
  68. package/dist/tools/index.js +251 -0
  69. package/dist/tools/markdown/MarkdownContent.vue.d.ts +36 -0
  70. package/dist/tools/markdown/imagePreview.d.ts +15 -0
  71. package/dist/tools/markdown/index.d.ts +5 -0
  72. package/dist/tools/markdown/renderMarkdown.d.ts +22 -0
  73. package/dist/tools/markdown/tableDownload.d.ts +14 -0
  74. package/dist/tools/stream.d.ts +9 -0
  75. package/dist/tools/style.css +1 -0
  76. package/dist/tools/useAutoScroll.d.ts +31 -0
  77. package/dist/web-ui/attach/AttachmentCard.vue.d.ts +91 -0
  78. package/dist/web-ui/attach/AttachmentList.vue.d.ts +94 -0
  79. package/dist/web-ui/attach/types.d.ts +5 -0
  80. package/dist/web-ui/chat/ChatContainer.vue.d.ts +160 -0
  81. package/dist/web-ui/chat/ChatMessagesView.vue.d.ts +83 -0
  82. package/dist/web-ui/chat/types.d.ts +24 -0
  83. package/dist/web-ui/envswitch/EnvSwitch.vue.d.ts +67 -0
  84. package/dist/web-ui/envswitch/types.d.ts +22 -0
  85. package/dist/web-ui/index.cjs +2 -0
  86. package/dist/web-ui/index.d.ts +14 -0
  87. package/dist/web-ui/index.js +1034 -0
  88. package/dist/web-ui/inputbox/Inputbox.vue.d.ts +215 -0
  89. package/dist/web-ui/recordset/RecordsetTable.vue.d.ts +37 -0
  90. package/dist/web-ui/recordset/webAnswerContentMap.d.ts +9 -0
  91. package/dist/web-ui/style.css +1 -0
  92. package/package.json +124 -4
  93. package/styles/github.css +2 -0
  94. package/styles/katex.css +2 -0
  95. package/README.md +0 -3
@@ -0,0 +1,4 @@
1
+ "use strict";var j=Object.create;var A=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var Q=Object.getOwnPropertyNames;var T=Object.getPrototypeOf,q=Object.prototype.hasOwnProperty;var G=(e,o,t,s)=>{if(o&&typeof o=="object"||typeof o=="function")for(let r of Q(o))!q.call(e,r)&&r!==t&&A(e,r,{get:()=>o[r],enumerable:!(s=O(o,r))||s.enumerable});return e};var H=(e,o,t)=>(t=e!=null?j(T(e)):{},G(o||!e||!e.__esModule?A(t,"default",{value:e,enumerable:!0}):t,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const b=require("axios");class R extends Error{constructor(o="登录已过期,请重新认证"){super(o),this.name="AuthExpiredError"}}const $=e=>b.isCancel(e)||e instanceof Error&&(e.name==="AbortError"||e.name==="CanceledError"),B=e=>new URLSearchParams(Object.entries(e).reduce((o,[t,s])=>(o[t]=String(s),o),{})),D={},k=e=>{const{baseURL:o,getWisession:t,getSession:s}=e,r=o.replace(/\/$/,""),n=s??t,i=(d=!1)=>{const c={};d||(c["Content-Type"]="application/x-www-form-urlencoded");const u=n==null?void 0:n();return u&&(c.wisession=u),c};return{baseURL:r,getSession:n,post:async(d,c=D)=>{const u=typeof FormData<"u"&&c instanceof FormData,p=u?c:B(c),a=(await b.post(`${r}${d}`,p,{headers:i(u)})).data;if((a==null?void 0:a.err_code)==="AUTH")throw new R;if((a==null?void 0:a.json_ok)===!1)throw new Error((a==null?void 0:a.json_msg)||(a==null?void 0:a.message)||(a==null?void 0:a.err_msg)||"请求失败");return a},stream:async(d,c=D,u)=>{const p=typeof FormData<"u"&&c instanceof FormData,w=p?c:B(c);return(await b.post(`${r}${d}`,w,{headers:i(p),adapter:"fetch",responseType:"stream",signal:u})).data}}},v="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8Qa+e4QjNlfSR55RGHeltMDqYJR1UCCpWzqY0xV9rgcGKXB3PzvBwn5PUUzPehGHHDXrpU4/gmcDZCjJly9hoI9NPKtjhi3bRFV7aHX0B4ms0S2ImYKtdRR7uSQfJPQFwr6fVOCs2bcPcJMYmSuJZXRKO/Fr7ZD5Uhlkcg5KGzQIDAQAB",P=async e=>{const o=(await import("jsencrypt")).default,t=new o({});t.setPublicKey(v);const s=t.encrypt(e);if(s===!1)throw new Error("密码加密失败");return s},J=async(e,o)=>{const{user:t,pass:s,...r}=o,n={};Object.entries(r).forEach(([y,h])=>{h!==void 0&&(n[y]=h)}),n.user=t,n.pass=await P(s);const i=await e.post("/login",n);if(!i.wisession)throw new Error("登录失败:未返回 wisession");return i},m=async e=>{const o="name"in e&&typeof e.name=="string"?e.name:"",t=e.type||"";if(typeof FileReader<"u")return new Promise((s,r)=>{const n=new FileReader;n.onload=()=>{const i=String(n.result??"");s({name:o,"content-type":t,data:i.split(",")[1]??i})},n.onerror=()=>r(n.error),n.readAsDataURL(e)});if(typeof e.arrayBuffer=="function"){const s=await e.arrayBuffer(),r=typeof Buffer<"u"?Buffer.from(s).toString("base64"):btoa(String.fromCharCode(...new Uint8Array(s)));return{name:o,"content-type":t,data:r}}return{name:o,"content-type":t,data:""}},M=(e,o,t)=>{Object.prototype.hasOwnProperty.call(e,o)?e[o]=Array.isArray(e[o])?[...e[o],t]:[e[o],t]:e[o]=t},U=async e=>{const o={};if(typeof FormData<"u"&&e instanceof FormData)for(const[t,s]of e.entries()){const r=typeof Blob<"u"&&s instanceof Blob?await m(s):s;M(o,t,r)}else if(e&&typeof e=="object")for(const[t,s]of Object.entries(e))typeof Blob<"u"&&s instanceof Blob?o[t]=await m(s):Array.isArray(s)?o[t]=await Promise.all(s.map(async r=>typeof Blob<"u"&&r instanceof Blob?await m(r):r)):o[t]=s;return o.files&&!Array.isArray(o.files)&&(o.files=[o.files]),o.type="chat_stream",o},x=(e,o)=>{const t=e?e.endsWith("/")?e:`${e}/`:"/",s=typeof window<"u"&&window.location?window.location.origin:"http://localhost",r=new URL("chat/ws",new URL(t,s));return r.protocol==="http:"?r.protocol="ws:":r.protocol==="https:"?r.protocol="wss:":typeof window<"u"&&window.location?r.protocol=window.location.protocol==="https:"?"wss:":"ws:":r.protocol.startsWith("ws")||(r.protocol="ws:"),o&&r.searchParams.set("session_id",String(o)),r.toString()},L=async e=>typeof e=="string"?e:typeof Blob<"u"&&e instanceof Blob?e.text():e instanceof ArrayBuffer?new TextDecoder().decode(e):String(e??""),S=(e,o,t=8e3)=>{const s=Math.max(t,1),r=Math.ceil(o.length/s)||1;for(let n=0;n<r;n++){const i=o.slice(n*s,(n+1)*s),y=n===r-1?"E":n===0?"B":"M";e.send(`${y}${i}`)}},W=async e=>{const{baseURL:o,data:t,sessionId:s,signal:r,chunkSize:n=8e3,WebSocketClass:i=typeof WebSocket<"u"?WebSocket:void 0,onOpen:y}=e;if(!i)throw new Error("当前运行环境不支持 WebSocket");const h=await U(t),d=x(o,s),c=new TextEncoder;return new ReadableStream({start(u){let p=!1,w=!1;const a=new i(d),E=()=>{if(!p){p=!0;try{u.close()}catch{}try{a.close()}catch{}}},g=f=>{if(!p){p=!0;try{u.error(f)}catch{}try{a.close()}catch{}}};a.onopen=()=>{try{S(a,JSON.stringify(h),n),y==null||y((f,l)=>{p||a.readyState!==1||S(a,f,l??n)})}catch(f){g(f)}},a.onmessage=async f=>{try{w=!0;const l=await L(f.data);if(!l)return;const F=c.encode(`data: ${l}
2
+
3
+ `);u.enqueue(F);try{const _=JSON.parse(l);(_==null?void 0:_.mode)==="finish"&&E()}catch{}}catch(l){g(l)}},a.onclose=()=>{if(!w){g(new Error("WebSocket 连接已断开(未收到任何回答数据)"));return}E()},a.onerror=f=>{g(f)};const C=()=>{const f=r==null?void 0:r.reason,l=f instanceof Error?f:new DOMException(typeof f=="string"?f:"The user aborted a request.","AbortError");g(l)};r&&(r.aborted?C():r.addEventListener("abort",C,{once:!0}))}})},I=e=>{const o=(e.baseURL||"").replace(/\/$/,"");return{getFileUrl(t){return t?t.startsWith("http://")||t.startsWith("https://")||t.startsWith("/")?t:`${o}/algorithm/get_file_data?file_id=${t}`:""},async getHistoryGroups(){return e.post("/history/get_history_groups",{})},async createHistoryGroup(t){return e.post("/history/create_history_group",{group_title:t})},async deleteHistoryGroup(t){return e.post("/history/delete_history_group",{history_group_id:t})},async setHistoryGroupTitle(t,s){return e.post("/history/set_history_group_title",{history_group_id:t,title:s})},async getHistoryDetail(t,s=0,r=10){const n=await e.post("/history/query_history_detail",{history_group_id:t,last_end:s,last_count:r});return(n==null?void 0:n.details)||[]},async getHistoryAnswer(t){return e.post("/history/get_history_answer",{history_id:t})},async getDefaultLlmId(){return e.post("/admin/get_default_llm_id",{})},async getLlmEntryListByRole(t={entry_group:"智能助手"}){return e.post("/admin/get_llm_entry_list_by_role",t)},async questionStream(t,s){var a;const{question:r,historyGroupId:n,entryId:i,files:y,incPrevQuestion:h,onOpen:d,...c}=t,p={question:r,history_group_id:n,entry_id:i??"",inc_prev_question:h??"Y",...c};y&&y.length>0&&(p.files=y);const w=((a=e.getSession)==null?void 0:a.call(e))??(typeof localStorage<"u"?localStorage.getItem("access-session"):null);return W({baseURL:e.baseURL,data:p,sessionId:w,signal:s,onOpen:d})}}};exports.AuthExpiredError=R;exports.buildChatWsUrl=x;exports.createChatApi=I;exports.createRequest=k;exports.fileToBase64=m;exports.formDataToJson=U;exports.isCancelError=$;exports.login=J;exports.openChatWebSocketStream=W;exports.pwdEncrypt=P;exports.resolveMessageData=L;exports.sendPayloadInChunks=S;
4
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1,18 @@
1
+ /**
2
+ * wi-chat-request —— 对话 + 历史的业务请求层
3
+ *
4
+ * axios 封装:普通请求(post) + SSE 流(stream),统一处理 json_ok / AUTH;
5
+ * WebSocket 对话流(ws):分片帧传输与 ReadableStream 封装;
6
+ * 含登录(pwdEncrypt / login)、历史分组 CRUD、会话明细/回答、question_stream。
7
+ *
8
+ * 注意:全部用具名 re-export 而非 export *——TS < 5.0 的 nodenext 下 star 转发成员
9
+ * 不物化(消费端报 TS2305),且 vite/esbuild 隔离转译要求类型显式标注 export type。
10
+ */
11
+ export { AuthExpiredError, isCancelError, createRequest } from './client';
12
+ export type { RequestOptions, RequestClient } from './client';
13
+ export { pwdEncrypt, login } from './login';
14
+ export type { LoginParams, LoginResult } from './login';
15
+ export { createChatApi } from './api';
16
+ export type { HistoryGroup, HistoryGroupsResult, HistoryDetailItem, AgentEntryItem, ChatApi } from './api';
17
+ export { fileToBase64, formDataToJson, buildChatWsUrl, resolveMessageData, sendPayloadInChunks, openChatWebSocketStream } from './ws';
18
+ export type { FileJsonValue, ChatWsStreamOptions, WsChunkSender } from './ws';
@@ -0,0 +1,264 @@
1
+ import b from "axios";
2
+ class R extends Error {
3
+ constructor(o = "登录已过期,请重新认证") {
4
+ super(o), this.name = "AuthExpiredError";
5
+ }
6
+ }
7
+ const G = (e) => b.isCancel(e) || e instanceof Error && (e.name === "AbortError" || e.name === "CanceledError"), B = (e) => new URLSearchParams(
8
+ Object.entries(e).reduce((o, [t, s]) => (o[t] = String(s), o), {})
9
+ ), A = {}, H = (e) => {
10
+ const { baseURL: o, getWisession: t, getSession: s } = e, r = o.replace(/\/$/, ""), n = s ?? t, i = (d = !1) => {
11
+ const c = {};
12
+ d || (c["Content-Type"] = "application/x-www-form-urlencoded");
13
+ const u = n == null ? void 0 : n();
14
+ return u && (c.wisession = u), c;
15
+ };
16
+ return {
17
+ baseURL: r,
18
+ getSession: n,
19
+ post: async (d, c = A) => {
20
+ const u = typeof FormData < "u" && c instanceof FormData, p = u ? c : B(c), a = (await b.post(`${r}${d}`, p, {
21
+ headers: i(u)
22
+ })).data;
23
+ if ((a == null ? void 0 : a.err_code) === "AUTH")
24
+ throw new R();
25
+ if ((a == null ? void 0 : a.json_ok) === !1)
26
+ throw new Error((a == null ? void 0 : a.json_msg) || (a == null ? void 0 : a.message) || (a == null ? void 0 : a.err_msg) || "请求失败");
27
+ return a;
28
+ },
29
+ stream: async (d, c = A, u) => {
30
+ const p = typeof FormData < "u" && c instanceof FormData, w = p ? c : B(c);
31
+ return (await b.post(`${r}${d}`, w, {
32
+ headers: i(p),
33
+ // 浏览器下 XHR 不支持流式读取(response.data 会变成整包 String),
34
+ // 必须强制 fetch 适配器才能拿到 ReadableStream
35
+ adapter: "fetch",
36
+ responseType: "stream",
37
+ signal: u
38
+ })).data;
39
+ }
40
+ };
41
+ }, P = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8Qa+e4QjNlfSR55RGHeltMDqYJR1UCCpWzqY0xV9rgcGKXB3PzvBwn5PUUzPehGHHDXrpU4/gmcDZCjJly9hoI9NPKtjhi3bRFV7aHX0B4ms0S2ImYKtdRR7uSQfJPQFwr6fVOCs2bcPcJMYmSuJZXRKO/Fr7ZD5Uhlkcg5KGzQIDAQAB", U = async (e) => {
42
+ const o = (await import("jsencrypt")).default, t = new o({});
43
+ t.setPublicKey(P);
44
+ const s = t.encrypt(e);
45
+ if (s === !1)
46
+ throw new Error("密码加密失败");
47
+ return s;
48
+ }, O = async (e, o) => {
49
+ const { user: t, pass: s, ...r } = o, n = {};
50
+ Object.entries(r).forEach(([y, h]) => {
51
+ h !== void 0 && (n[y] = h);
52
+ }), n.user = t, n.pass = await U(s);
53
+ const i = await e.post("/login", n);
54
+ if (!i.wisession)
55
+ throw new Error("登录失败:未返回 wisession");
56
+ return i;
57
+ }, _ = async (e) => {
58
+ const o = "name" in e && typeof e.name == "string" ? e.name : "", t = e.type || "";
59
+ if (typeof FileReader < "u")
60
+ return new Promise((s, r) => {
61
+ const n = new FileReader();
62
+ n.onload = () => {
63
+ const i = String(n.result ?? "");
64
+ s({
65
+ name: o,
66
+ "content-type": t,
67
+ data: i.split(",")[1] ?? i
68
+ });
69
+ }, n.onerror = () => r(n.error), n.readAsDataURL(e);
70
+ });
71
+ if (typeof e.arrayBuffer == "function") {
72
+ const s = await e.arrayBuffer(), r = typeof Buffer < "u" ? Buffer.from(s).toString("base64") : btoa(String.fromCharCode(...new Uint8Array(s)));
73
+ return {
74
+ name: o,
75
+ "content-type": t,
76
+ data: r
77
+ };
78
+ }
79
+ return {
80
+ name: o,
81
+ "content-type": t,
82
+ data: ""
83
+ };
84
+ }, x = (e, o, t) => {
85
+ Object.prototype.hasOwnProperty.call(e, o) ? e[o] = Array.isArray(e[o]) ? [...e[o], t] : [e[o], t] : e[o] = t;
86
+ }, L = async (e) => {
87
+ const o = {};
88
+ if (typeof FormData < "u" && e instanceof FormData)
89
+ for (const [t, s] of e.entries()) {
90
+ const r = typeof Blob < "u" && s instanceof Blob ? await _(s) : s;
91
+ x(o, t, r);
92
+ }
93
+ else if (e && typeof e == "object")
94
+ for (const [t, s] of Object.entries(e))
95
+ typeof Blob < "u" && s instanceof Blob ? o[t] = await _(s) : Array.isArray(s) ? o[t] = await Promise.all(
96
+ s.map(
97
+ async (r) => typeof Blob < "u" && r instanceof Blob ? await _(r) : r
98
+ )
99
+ ) : o[t] = s;
100
+ return o.files && !Array.isArray(o.files) && (o.files = [o.files]), o.type = "chat_stream", o;
101
+ }, F = (e, o) => {
102
+ const t = e ? e.endsWith("/") ? e : `${e}/` : "/", s = typeof window < "u" && window.location ? window.location.origin : "http://localhost", r = new URL("chat/ws", new URL(t, s));
103
+ return r.protocol === "http:" ? r.protocol = "ws:" : r.protocol === "https:" ? r.protocol = "wss:" : typeof window < "u" && window.location ? r.protocol = window.location.protocol === "https:" ? "wss:" : "ws:" : r.protocol.startsWith("ws") || (r.protocol = "ws:"), o && r.searchParams.set("session_id", String(o)), r.toString();
104
+ }, W = async (e) => typeof e == "string" ? e : typeof Blob < "u" && e instanceof Blob ? e.text() : e instanceof ArrayBuffer ? new TextDecoder().decode(e) : String(e ?? ""), C = (e, o, t = 8e3) => {
105
+ const s = Math.max(t, 1), r = Math.ceil(o.length / s) || 1;
106
+ for (let n = 0; n < r; n++) {
107
+ const i = o.slice(n * s, (n + 1) * s), y = n === r - 1 ? "E" : n === 0 ? "B" : "M";
108
+ e.send(`${y}${i}`);
109
+ }
110
+ }, Q = async (e) => {
111
+ const {
112
+ baseURL: o,
113
+ data: t,
114
+ sessionId: s,
115
+ signal: r,
116
+ chunkSize: n = 8e3,
117
+ WebSocketClass: i = typeof WebSocket < "u" ? WebSocket : void 0,
118
+ onOpen: y
119
+ } = e;
120
+ if (!i)
121
+ throw new Error("当前运行环境不支持 WebSocket");
122
+ const h = await L(t), d = F(o, s), c = new TextEncoder();
123
+ return new ReadableStream({
124
+ start(u) {
125
+ let p = !1, w = !1;
126
+ const a = new i(d), S = () => {
127
+ if (!p) {
128
+ p = !0;
129
+ try {
130
+ u.close();
131
+ } catch {
132
+ }
133
+ try {
134
+ a.close();
135
+ } catch {
136
+ }
137
+ }
138
+ }, m = (f) => {
139
+ if (!p) {
140
+ p = !0;
141
+ try {
142
+ u.error(f);
143
+ } catch {
144
+ }
145
+ try {
146
+ a.close();
147
+ } catch {
148
+ }
149
+ }
150
+ };
151
+ a.onopen = () => {
152
+ try {
153
+ C(a, JSON.stringify(h), n), y == null || y((f, l) => {
154
+ p || a.readyState !== 1 || C(a, f, l ?? n);
155
+ });
156
+ } catch (f) {
157
+ m(f);
158
+ }
159
+ }, a.onmessage = async (f) => {
160
+ try {
161
+ w = !0;
162
+ const l = await W(f.data);
163
+ if (!l)
164
+ return;
165
+ const D = c.encode(`data: ${l}
166
+
167
+ `);
168
+ u.enqueue(D);
169
+ try {
170
+ const g = JSON.parse(l);
171
+ (g == null ? void 0 : g.mode) === "finish" && S();
172
+ } catch {
173
+ }
174
+ } catch (l) {
175
+ m(l);
176
+ }
177
+ }, a.onclose = () => {
178
+ if (!w) {
179
+ m(new Error("WebSocket 连接已断开(未收到任何回答数据)"));
180
+ return;
181
+ }
182
+ S();
183
+ }, a.onerror = (f) => {
184
+ m(f);
185
+ };
186
+ const E = () => {
187
+ const f = r == null ? void 0 : r.reason, l = f instanceof Error ? f : new DOMException(typeof f == "string" ? f : "The user aborted a request.", "AbortError");
188
+ m(l);
189
+ };
190
+ r && (r.aborted ? E() : r.addEventListener("abort", E, { once: !0 }));
191
+ }
192
+ });
193
+ }, $ = (e) => {
194
+ const o = (e.baseURL || "").replace(/\/$/, "");
195
+ return {
196
+ getFileUrl(t) {
197
+ return t ? t.startsWith("http://") || t.startsWith("https://") || t.startsWith("/") ? t : `${o}/algorithm/get_file_data?file_id=${t}` : "";
198
+ },
199
+ async getHistoryGroups() {
200
+ return e.post("/history/get_history_groups", {});
201
+ },
202
+ async createHistoryGroup(t) {
203
+ return e.post("/history/create_history_group", { group_title: t });
204
+ },
205
+ async deleteHistoryGroup(t) {
206
+ return e.post("/history/delete_history_group", { history_group_id: t });
207
+ },
208
+ async setHistoryGroupTitle(t, s) {
209
+ return e.post("/history/set_history_group_title", { history_group_id: t, title: s });
210
+ },
211
+ async getHistoryDetail(t, s = 0, r = 10) {
212
+ const n = await e.post("/history/query_history_detail", {
213
+ history_group_id: t,
214
+ last_end: s,
215
+ last_count: r
216
+ });
217
+ return (n == null ? void 0 : n.details) || [];
218
+ },
219
+ async getHistoryAnswer(t) {
220
+ return e.post("/history/get_history_answer", { history_id: t });
221
+ },
222
+ async getDefaultLlmId() {
223
+ return e.post("/admin/get_default_llm_id", {});
224
+ },
225
+ async getLlmEntryListByRole(t = { entry_group: "智能助手" }) {
226
+ return e.post("/admin/get_llm_entry_list_by_role", t);
227
+ },
228
+ async questionStream(t, s) {
229
+ var a;
230
+ const { question: r, historyGroupId: n, entryId: i, files: y, incPrevQuestion: h, onOpen: d, ...c } = t, p = {
231
+ question: r,
232
+ history_group_id: n,
233
+ entry_id: i ?? "",
234
+ inc_prev_question: h ?? "Y",
235
+ ...c
236
+ };
237
+ y && y.length > 0 && (p.files = y);
238
+ const w = ((a = e.getSession) == null ? void 0 : a.call(e)) ?? (typeof localStorage < "u" ? localStorage.getItem("access-session") : null);
239
+ return Q({
240
+ baseURL: e.baseURL,
241
+ data: p,
242
+ sessionId: w,
243
+ signal: s,
244
+ // 传输层选项:连接就绪后向外部交出分片发送器(不混入发给后端的载荷)
245
+ onOpen: d
246
+ });
247
+ }
248
+ };
249
+ };
250
+ export {
251
+ R as AuthExpiredError,
252
+ F as buildChatWsUrl,
253
+ $ as createChatApi,
254
+ H as createRequest,
255
+ _ as fileToBase64,
256
+ L as formDataToJson,
257
+ G as isCancelError,
258
+ O as login,
259
+ Q as openChatWebSocketStream,
260
+ U as pwdEncrypt,
261
+ W as resolveMessageData,
262
+ C as sendPayloadInChunks
263
+ };
264
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,37 @@
1
+ /**
2
+ * 登录能力:密码加密(jsencrypt)+ /login 接口
3
+ *
4
+ * jsencrypt 以 UMD 形式依赖 `window`,属于浏览器专用;
5
+ * 这里用动态 import 延迟加载,避免在 Node 环境(如单元测试)import 本模块时崩溃。
6
+ */
7
+ /** 密码 RSA 加密(失败时抛错,绝不发送明文密码);异步加载 jsencrypt */
8
+ export declare const pwdEncrypt: (pwd: string) => Promise<string>;
9
+ export interface LoginParams {
10
+ /** 登录账号 */
11
+ user: string;
12
+ /** 登录密码(明文传入,login 内部 RSA 加密后发送) */
13
+ pass: string;
14
+ /** 登录端类型:标识从哪个端登录(可选) */
15
+ client?: string;
16
+ /** 对接项目系统标识(可选) */
17
+ system_name?: string;
18
+ /** 其余任意字段直接展开透传到 /login 请求体(如验证码、租户等,可选) */
19
+ [key: string]: unknown;
20
+ }
21
+ export interface LoginResult {
22
+ json_ok?: boolean;
23
+ wisession?: string;
24
+ phone?: string;
25
+ id?: string;
26
+ name?: string;
27
+ real_name?: string;
28
+ [key: string]: any;
29
+ }
30
+ /**
31
+ * 登录接口。前提:request 需先配置 baseURL;本函数通过 request 的 post 调用 /login。
32
+ * user / pass 外的其余字段(client / system_name 及任意自定义参数)平铺展开透传。
33
+ * @returns 登录结果(含 wisession)
34
+ */
35
+ export declare const login: (request: {
36
+ post: <T = any>(url: string, data?: Record<string, unknown>) => Promise<T>;
37
+ }, params: LoginParams) => Promise<LoginResult>;
@@ -0,0 +1,91 @@
1
+ /**
2
+ * packages/chat-request/src/ws.ts
3
+ *
4
+ * WebSocket 对话流传输模块:
5
+ * 负责与后端的 `/chat/ws` 端点建立 WebSocket 连接,处理 FormData/文件 Base64 转换与 B/M/E 分片传输,
6
+ * 并将 WebSocket 收到的消息封装成符合 SSE 规范(`data: ...\n\n`)的 `ReadableStream<Uint8Array>`,
7
+ * 保持上层流式消费(如 `consumeStream`、`useChat`)完全解耦与无缝兼容。
8
+ */
9
+ /**
10
+ * 文件转换为 Base64 结构的对象类型
11
+ */
12
+ export interface FileJsonValue {
13
+ /** 文件名 */
14
+ name: string;
15
+ /** MIME 类型 */
16
+ 'content-type': string;
17
+ /** Base64 数据字符串(不含 data:url 前缀) */
18
+ data: string;
19
+ }
20
+ /**
21
+ * 绑定当前 WebSocket 连接的分片发送器:把载荷文本按 B/M/E 协议分帧发到该连接上。
22
+ * 连接关闭(或流已结束)后调用会被静默丢弃,不抛错。
23
+ */
24
+ export type WsChunkSender = (payloadText: string, chunkSize?: number) => void;
25
+ /**
26
+ * WebSocket 对话流配置参数
27
+ */
28
+ export interface ChatWsStreamOptions {
29
+ /** 基础接口 URL(对应 client.baseURL) */
30
+ baseURL: string;
31
+ /** 请求载荷(支持 FormData 或普通对象) */
32
+ data: Record<string, any> | FormData;
33
+ /** 会话 ID(用于鉴权连接) */
34
+ sessionId?: string | null;
35
+ /** 中止信号(用于取消对话) */
36
+ signal?: AbortSignal;
37
+ /** 单片发送的最大字符数,默认 8000 */
38
+ chunkSize?: number;
39
+ /** 可选的自定义 WebSocket 构造函数(便于单测与跨平台注入) */
40
+ WebSocketClass?: typeof WebSocket;
41
+ /**
42
+ * 连接建立且首包载荷分帧发送完毕后的回调:入参为绑定当前连接的分片发送器,
43
+ * 外部可在回答流结束前用它向同一条连接追发任意载荷(同样按 B/M/E 分帧)。
44
+ * 发送器仅在连接存活期内有效,连接关闭或流中止后调用静默丢弃。
45
+ */
46
+ onOpen?: (sendInChunks: WsChunkSender) => void;
47
+ }
48
+ /**
49
+ * 将 Blob / File 转换为 Base64 结构
50
+ *
51
+ * @param file 待转换的 Blob 或 File 实例
52
+ * @returns 包含 name, content-type 和 base64 data 的结构
53
+ */
54
+ export declare const fileToBase64: (file: Blob) => Promise<FileJsonValue>;
55
+ /**
56
+ * 将 FormData 或普通对象规范化为 WebSocket 传输所需的 JSON 结构
57
+ *
58
+ * @param params 输入的请求参数(FormData 或 Record)
59
+ * @returns 序列化后的 JSON 载荷对象
60
+ */
61
+ export declare const formDataToJson: (params: FormData | Record<string, any>) => Promise<Record<string, any>>;
62
+ /**
63
+ * 构建对话 WebSocket 连接完整 URL
64
+ *
65
+ * @param baseUrl 基础 HTTP/HTTPS 或 WS/WSS URL
66
+ * @param sessionId 可选的用户登录态 session_id
67
+ * @returns 构造好的 ws:// 或 wss:// 协议完整 URL 字符串
68
+ */
69
+ export declare const buildChatWsUrl: (baseUrl: string, sessionId?: string | null) => string;
70
+ /**
71
+ * 将 WebSocket 接收到的 MessageEvent 数据解析为文本字符串
72
+ *
73
+ * @param data WebSocket 消息体数据(string | Blob | ArrayBuffer 等)
74
+ * @returns 统一解析出的文本字符串
75
+ */
76
+ export declare const resolveMessageData: (data: any) => Promise<string>;
77
+ /**
78
+ * 将完整的载荷文本按照指定分片大小按 B/M/E 协议分帧发送
79
+ *
80
+ * @param ws 当前活动的 WebSocket 连接实例
81
+ * @param payloadText 序列化后的 JSON 载荷字符串
82
+ * @param chunkSize 单片字符大小,默认 8000
83
+ */
84
+ export declare const sendPayloadInChunks: (ws: Pick<WebSocket, 'send'>, payloadText: string, chunkSize?: number) => void;
85
+ /**
86
+ * 打开对话 WebSocket 连接,并将返回的下行消息包装为 ReadableStream
87
+ *
88
+ * @param options WebSocket 对话流配置
89
+ * @returns 包装好的 SSE 规范 ReadableStream 实例
90
+ */
91
+ export declare const openChatWebSocketStream: (options: ChatWsStreamOptions) => Promise<ReadableStream<Uint8Array>>;
package/dist/style.css ADDED
@@ -0,0 +1,24 @@
1
+ /**
2
+ * wi-chat-theme —— 全局默认设计 token
3
+ *
4
+ * 提供整套 `--wi-chat-*` CSS 变量的默认值,作为 UI 包(renderers / tools 的 markdown)的兜底层。
5
+ * - 组件消费 `var(--wi-chat-*)`,此处定义默认;
6
+ * - 宿主可用 `createChatTheme()` / `applyTheme()` 在任意作用域覆盖(例如映射宿主主题色)。
7
+ */
8
+ :root {
9
+ /* 主色(默认值,宿主可用 --el-color-primary 映射覆盖) */
10
+ --wi-chat-primary: #5b7fff;
11
+
12
+ /* 文本 */
13
+ --wi-chat-text: #27344d;
14
+ --wi-chat-text-secondary: #8a93a6;
15
+
16
+ /* 边框 / 背景 */
17
+ --wi-chat-border: #e1e4e8;
18
+ --wi-chat-bg: #ffffff;
19
+ --wi-chat-code-bg: #f6f8fa;
20
+ --wi-chat-header-bg: #f6f8fa;
21
+
22
+ /* 圆角 */
23
+ --wi-chat-radius: 6px;
24
+ }
@@ -0,0 +1,2 @@
1
+ /* highlight.js github 主题(re-export 自 highlight.js 依赖,供使用方按需引入) */
2
+ @import 'highlight.js/styles/github.css';
@@ -0,0 +1,2 @@
1
+ /* KaTeX 样式(re-export 自 katex 依赖,供使用方按需引入) */
2
+ @import 'katex/dist/katex.min.css';
@@ -0,0 +1,3 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("wi-chat/style.css");const i="#5b7fff",a=(e,t)=>{if(typeof window>"u")return;const r=t??document.documentElement;return getComputedStyle(r).getPropertyValue(e).trim()||void 0},s={text:"#27344d",textSecondary:"#8a93a6",border:"#e1e4e8",bg:"#ffffff",codeBg:"#f6f8fa",headerBg:"#f6f8fa",radius:"6px"},y=(e={})=>{const{primary:t,hostPrimaryVar:r="--el-color-primary"}=e,c={primary:t??a(r)??a("--wi-chat-primary")??i,...s};return Object.entries(c).filter(([,o])=>o!=null).map(([o,m])=>`--wi-chat-${p(o)}: ${m};`).join(`
2
+ `)},p=e=>{switch(e){case"textSecondary":return"text-secondary";default:return e}},u=(e={},t)=>{if(typeof window>"u")return!1;const r=t??document.documentElement,{primary:n,hostPrimaryVar:c="--el-color-primary"}=e,o=n??a(c,r)??a("--wi-chat-primary",r)??i;return r.style.setProperty("--wi-chat-primary",o),!0};exports.DEFAULT_PRIMARY=i;exports.applyTheme=u;exports.createChatTheme=y;
3
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1,3 @@
1
+
2
+ export { DEFAULT_PRIMARY, createChatTheme, applyTheme } from './theme';
3
+ export type { ChatThemeOptions, ChatThemeTokens } from './theme';
@@ -0,0 +1,37 @@
1
+ import "wi-chat/style.css";
2
+ const i = "#5b7fff", n = (r, e) => {
3
+ if (typeof window > "u")
4
+ return;
5
+ const t = e ?? document.documentElement;
6
+ return getComputedStyle(t).getPropertyValue(r).trim() || void 0;
7
+ }, s = {
8
+ text: "#27344d",
9
+ textSecondary: "#8a93a6",
10
+ border: "#e1e4e8",
11
+ bg: "#ffffff",
12
+ codeBg: "#f6f8fa",
13
+ headerBg: "#f6f8fa",
14
+ radius: "6px"
15
+ }, f = (r = {}) => {
16
+ const { primary: e, hostPrimaryVar: t = "--el-color-primary" } = r, c = { primary: e ?? n(t) ?? n("--wi-chat-primary") ?? i, ...s };
17
+ return Object.entries(c).filter(([, o]) => o != null).map(([o, m]) => `--wi-chat-${p(o)}: ${m};`).join(`
18
+ `);
19
+ }, p = (r) => {
20
+ switch (r) {
21
+ case "textSecondary":
22
+ return "text-secondary";
23
+ default:
24
+ return r;
25
+ }
26
+ }, d = (r = {}, e) => {
27
+ if (typeof window > "u")
28
+ return !1;
29
+ const t = e ?? document.documentElement, { primary: a, hostPrimaryVar: c = "--el-color-primary" } = r, o = a ?? n(c, t) ?? n("--wi-chat-primary", t) ?? i;
30
+ return t.style.setProperty("--wi-chat-primary", o), !0;
31
+ };
32
+ export {
33
+ i as DEFAULT_PRIMARY,
34
+ d as applyTheme,
35
+ f as createChatTheme
36
+ };
37
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,40 @@
1
+ /**
2
+ * wi-chat-theme —— 主题能力(runtime)
3
+ *
4
+ * 提供:
5
+ * - `DEFAULT_PRIMARY`:内置默认主色
6
+ * - `createChatTheme(options?)`:生成一组 `--wi-chat-*` CSS 变量声明字符串;
7
+ * 主色默认读取宿主 `--el-color-primary`(element-plus 或宿主自定义),否则用内置默认
8
+ * - `applyTheme(el?, options?)`:把主题变量写入指定作用域(默认 documentElement)的 style
9
+ */
10
+ /** 内置默认主色 */
11
+ export declare const DEFAULT_PRIMARY = "#5b7fff";
12
+ /** 主题配置项 */
13
+ export interface ChatThemeOptions {
14
+ /** 主色(覆盖默认;不传则尝试读宿主 --el-color-primary) */
15
+ primary?: string;
16
+ /** 当 primary 未显式给出时,读取宿主变量的名称(默认 --el-color-primary) */
17
+ hostPrimaryVar?: string;
18
+ }
19
+ /** 可被 CSS 变量覆盖的语义色 / token */
20
+ export interface ChatThemeTokens {
21
+ primary?: string;
22
+ text?: string;
23
+ textSecondary?: string;
24
+ border?: string;
25
+ bg?: string;
26
+ codeBg?: string;
27
+ headerBg?: string;
28
+ radius?: string;
29
+ }
30
+ /**
31
+ * 生成一组 `--wi-chat-*` CSS 变量声明。用于宿主把主题应用到目标作用域。
32
+ * @example
33
+ * document.head.insertAdjacentHTML('beforeend', `<style>${createChatTheme()}</style>`)
34
+ */
35
+ export declare const createChatTheme: (options?: ChatThemeOptions) => string;
36
+ /**
37
+ * 把主题变量写入指定作用域;默认写在 `document.documentElement`(:root)。
38
+ * @returns 是否成功应用(含 primary 或任一 token 变化)
39
+ */
40
+ export declare const applyTheme: (options?: ChatThemeOptions, el?: HTMLElement) => boolean;
@@ -0,0 +1,20 @@
1
+ import { ChatAttachment } from 'wi-chat/parser';
2
+
3
+ /**
4
+ * 附件下载配置
5
+ */
6
+ export interface DownloadAttachmentOptions {
7
+ /** 后端基础地址(不含结尾斜杠),用于拼接远端文件下载地址 */
8
+ baseURL?: string;
9
+ /** 自定义文件地址解析函数,优先于 baseURL 拼接 */
10
+ getFileUrl?: (fileId: string) => string;
11
+ }
12
+ /**
13
+ * 执行附件下载操作。
14
+ * 本地文件通过 Blob URL 与隐藏 a[download] 直接保存;远端文件先 fetch 为 Blob 再保存,
15
+ * 失败时降级为直接链接触发下载,避免浏览器在新标签页打开文件。
16
+ * @param item 附件对象(结构见 wi-chat-parser 的 ChatAttachment)
17
+ * @param options 下载配置(baseURL 与自定义地址解析函数)
18
+ * @returns 下载流程完成或无可下载内容时结束;远端下载失败会降级处理,不向外抛出业务异常
19
+ */
20
+ export declare const downloadAttachment: (item: ChatAttachment, options?: DownloadAttachmentOptions) => Promise<void>;
@@ -0,0 +1,17 @@
1
+ "use strict";var j=Object.create;var R=Object.defineProperty;var q=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var F=Object.getPrototypeOf,N=Object.prototype.hasOwnProperty;var G=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of I(t))!N.call(e,c)&&c!==n&&R(e,c,{get:()=>t[c],enumerable:!(a=q(t,c))||a.enumerable});return e};var O=(e,t,n)=>(n=e!=null?j(F(e)):{},G(t||!e||!e.__esModule?R(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("wi-chat/style.css");const p=require("vue"),M=require("wi-chat/parser"),J=require("@mdit/plugin-katex"),D=require("highlight.js"),A=require("markdown-it"),k=e=>new A().utils.escapeHtml(e),_=e=>k(e).replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Z=e=>!e||e.includes("get_image_full")?e:e.replace("get_image","get_image_full"),P=e=>{const{langPrefix:t="language-",imagePreview:n=!0,showCodeLang:a=!0,imageSrcResolver:c,imageDownload:s=!0,tableDownload:o=!0}=e,i='<button type="button" class="wi-md-table-download" title="下载 Excel" aria-label="下载表格为 Excel"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg></button>',l=new A({linkify:!0,typographer:!0,breaks:!0,html:!0,langPrefix:t,highlight:(d,u)=>{if(u&&D.getLanguage(u))try{return D.highlight(d,{language:u}).value}catch{return k(d)}return k(d)}}).use(J.katex,{delimiters:"dollars"});return l.renderer.rules.fence=(d,u,m,y,g)=>{var b;const h=d[u],f=h.info.trim().split(/\s+/)[0].toLowerCase(),r=((b=m.highlight)==null?void 0:b.call(m,h.content,f,""))||k(h.content);return`
2
+ <div class="wi-md-block">
3
+ <div class="wi-md-block-header">
4
+ <div class="wi-md-block-header-left">${a&&f?`<span class="wi-md-lang">${k(f)}</span>`:""}</div>
5
+ <div class="wi-md-block-header-right">
6
+ <button type="button" class="wi-md-copy" title="复制" aria-label="复制代码">
7
+ <svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor"><path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25Zm5-5C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z"/></svg>
8
+ </button>
9
+ <button type="button" class="wi-md-toggle" title="折叠" aria-label="折叠代码块">
10
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M7.41 8.59L12 13.17l4.59-4.58L18 10l-6 6-6-6 1.41-1.41z"/></svg>
11
+ </button>
12
+ </div>
13
+ </div>
14
+ <pre class="wi-md-code"><code class="${m.langPrefix}${k(f)}">${r}</code></pre>
15
+ </div>
16
+ `.trim()},l.renderer.rules.table_open=()=>o?'<div class="wi-md-table-wrap"><table class="wi-md-table">':'<table class="wi-md-table">',l.renderer.rules.table_close=()=>o?`</table>${i}</div>`:"</table>",l.renderer.rules.ordered_list_open=(d,u,m,y,g)=>(d[u].attrJoin("class","wi-md-list wi-md-list-ordered"),g.renderToken(d,u,m)),l.renderer.rules.bullet_list_open=(d,u,m,y,g)=>(d[u].attrJoin("class","wi-md-list wi-md-list-bullet"),g.renderToken(d,u,m)),l.renderer.rules.list_item_open=(d,u,m,y,g)=>(d[u].attrJoin("class","wi-md-list-item"),g.renderToken(d,u,m)),l.renderer.rules.image=(d,u,m,y,g)=>{const h=d[u],f=h.attrGet("src")||"",r=h.attrGet("alt")||h.content||"",w=h.attrGet("title")||"",b=[`src="${_(f)}"`,`alt="${_(r)}"`,w?`title="${_(w)}"`:""].filter(Boolean).join(" ");if(!n)return`<img ${b} />`;const v=c?c(f):Z(f),x=s?'<span class="wi-md-image-download" title="下载图片" role="button" aria-label="下载图片"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg></span>':"";return`<span class="wi-md-image-wrap" data-src="${_(v)}"><img ${b} loading="lazy" />${x}</span>`},l};let S=null;const z=()=>(S||(S=P({})),S),V=e=>(e.langPrefix===void 0||e.langPrefix==="language-")&&(e.imagePreview===void 0||e.imagePreview)&&(e.showCodeLang===void 0||e.showCodeLang)&&(e.imageDownload===void 0||e.imageDownload)&&(e.tableDownload===void 0||e.tableDownload)&&!e.imageSrcResolver,E=(e,t={})=>(V(t)?z():P(t)).render(e);let C=null;const L=()=>{C&&(p.render(null,C),C.remove(),C=null)},H=async(e,t,n)=>{L();const a=t&&t.length?t.includes(e)?t:[e,...t.filter(l=>l!==e)]:[e],c=Math.max(n??a.indexOf(e),0),s=document.createElement("div");document.body.appendChild(s),C=s;const{ElImageViewer:o}=await import("element-plus");if(C!==s)return;const i=p.createVNode(o,{urlList:a,initialIndex:Math.min(c,a.length-1),onClose:L,hideOnClickModal:!0,teleported:!0});p.render(i,s)},X=e=>{fetch(e).then(t=>t.blob()).then(t=>{var c;const n=URL.createObjectURL(t),a=document.createElement("a");a.href=n,a.download=((c=e.split("/").pop())==null?void 0:c.split("?")[0])||"image",document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(n)}).catch(()=>{const t=document.createElement("a");t.href=e,t.download="",t.target="_blank",document.body.appendChild(t),t.click(),document.body.removeChild(t)})},$=async(e,t)=>{try{const n=await import("xlsx"),a=n.utils.table_to_sheet(e),c=n.utils.book_new();n.utils.book_append_sheet(c,a,"查询结果");const s=n.write(c,{bookType:"xlsx",type:"array"}),o=new Blob([s],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),i=URL.createObjectURL(o),l=document.createElement("a");l.href=i,l.download=`${t||"表格"}_${new Date().toISOString().slice(0,10)}.xlsx`,document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(i)}catch(n){console.error("[downloadTableAsExcel] 表格导出 Excel 失败:",n)}},K=["innerHTML"],Q=p.defineComponent({__name:"MarkdownContent",props:{source:{default:""},renderOptions:{default:()=>({})}},setup(e){const t=e,n=p.ref(),a=p.computed(()=>E(t.source,t.renderOptions)),c=async(o,i)=>{try{await navigator.clipboard.writeText(i)}catch{const l=document.createElement("textarea");l.value=i,l.style.position="fixed",l.style.opacity="0",document.body.appendChild(l),l.select(),document.execCommand("copy"),l.remove()}o.classList.add("wi-md-copied"),window.setTimeout(()=>o.classList.remove("wi-md-copied"),1500)},s=o=>{var g,h,f,r,w,b;const i=o.target,l=i.closest(".wi-md-copy");if(l){o.preventDefault();const v=((h=(g=l.closest(".wi-md-block"))==null?void 0:g.querySelector(".wi-md-code code"))==null?void 0:h.textContent)||"";c(l,v);return}const d=i.closest(".wi-md-toggle");if(d){o.preventDefault(),(f=d.closest(".wi-md-block"))==null||f.classList.toggle("wi-md-collapsed");return}const u=i.closest(".wi-md-image-download");if(u){o.preventDefault(),o.stopPropagation();const v=(r=u.closest(".wi-md-image-wrap"))==null?void 0:r.dataset.src;v&&X(v);return}const m=i.closest(".wi-md-table-download");if(m){o.preventDefault(),o.stopPropagation();const v=(w=m.closest(".wi-md-table-wrap"))==null?void 0:w.querySelector("table");v&&$(v);return}const y=i.closest(".wi-md-image-wrap img");if(y){o.preventDefault();const v=y.closest(".wi-md-image-wrap"),x=(v==null?void 0:v.dataset.src)||y.src||"";if(!x)return;const T=Array.from(((b=n.value)==null?void 0:b.querySelectorAll(".wi-md-image-wrap"))??[]).map(U=>{var B;return U.dataset.src||((B=U.querySelector("img"))==null?void 0:B.getAttribute("src"))||""}).filter(Boolean);H(x,T.length>1?T:void 0,T.indexOf(x))}};return p.onBeforeUnmount(L),(o,i)=>(p.openBlock(),p.createElementBlock("div",{ref_key:"rootEl",ref:n,class:"wi-markdown",innerHTML:a.value,onClick:s},null,8,K))}}),W=48,Y=48,ee=async()=>{await p.nextTick(),await new Promise(e=>requestAnimationFrame(()=>e()))},te=e=>{const t=p.ref(!1),n=p.ref(!0);let a,c,s={preserveScroll:!0},o=!1,i=!1;const l=r=>r.scrollHeight-r.scrollTop-r.clientHeight<=W,d=r=>r.scrollTop<=Y,u=()=>{const r=e.value;if(!r)return;const w=l(r);n.value=w,t.value=!w},m=async()=>{await ee();const r=e.value;r&&(r.scrollTop=r.scrollHeight,n.value=!0,t.value=!1)},y=async()=>{if(!n.value){t.value=!0;return}await m()},g=async r=>{const w=e.value,b=w?w.scrollHeight:0;try{await r()}finally{await p.nextTick(),e.value&&b&&(e.value.scrollTop+=e.value.scrollHeight-b)}},h=(r,w={preserveScroll:!0})=>{c=r,s=w},f=async()=>{const r=e.value;if(!r||(u(),!c||o))return;const w=d(r);if(w&&!i){i=!0,o=!0;try{(s==null?void 0:s.preserveScroll)!==!1?await g(c):await c()}finally{o=!1,d(r)||(i=!1)}}else w||(i=!1)};return p.watch(e,r=>{a==null||a(),r&&(r.addEventListener("scroll",f,{passive:!0}),a=()=>r.removeEventListener("scroll",f),u())},{immediate:!0,flush:"post"}),p.getCurrentInstance()&&p.onUnmounted(()=>a==null?void 0:a()),{showScrollToBottom:t,forceScrollToBottom:m,requestScrollToBottom:y,onReachTop:h,preserveScrollPosition:g}},oe=async(e,t={})=>{if(typeof window>"u"||typeof document>"u")return;const n=e.attachContent||{},a=e.name||n.file_name||"download";if(n.raw){const s=URL.createObjectURL(n.raw),o=document.createElement("a");o.href=s,o.download=a,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(s);return}if(!n.fileId)return;const c=M.resolveAttachDownloadUrl(n.fileId,t.baseURL,t.getFileUrl);if(c)try{const s=await fetch(c,{credentials:"include"});if(!s.ok)throw new Error(`Download failed with status ${s.status}`);const o=URL.createObjectURL(await s.blob()),i=document.createElement("a");i.href=o,i.download=a,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(o)}catch(s){console.error("[downloadAttachment] fetch blob 失败,降级为直接链接触发:",s);const o=document.createElement("a");o.href=c,o.download=a,document.body.appendChild(o),o.click(),document.body.removeChild(o)}};Object.defineProperty(exports,"consumeStream",{enumerable:!0,get:()=>M.consumeStream});exports.MarkdownContent=Q;exports.closeImagePreview=L;exports.downloadAttachment=oe;exports.downloadTableAsExcel=$;exports.openImagePreview=H;exports.renderMarkdown=E;exports.useAutoScroll=te;
17
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1,8 @@
1
+
2
+ export { renderMarkdown, MarkdownContent, openImagePreview, closeImagePreview, downloadTableAsExcel } from './markdown';
3
+ export type { MarkdownRenderOptions } from './markdown';
4
+ export { useAutoScroll } from './useAutoScroll';
5
+ export type { OnReachTopOptions, UseAutoScrollReturn } from './useAutoScroll';
6
+ export { consumeStream } from './stream';
7
+ export { downloadAttachment } from './attachDownload';
8
+ export type { DownloadAttachmentOptions } from './attachDownload';