UNPKG

@artmate/chat

Version:

借鉴字节开源react库AntX,通过vue实现的版本

83 lines (82 loc) 2.68 kB
import p from "../artStream/index.js"; import y from "./artFetch.js"; const s = class s { constructor(n) { this.create = async (d, e, o) => { var r; const i = { method: "POST", body: JSON.stringify({ model: this.model, ...d }), headers: this.defaultHeaders }; try { const t = await y(this.baseURL, { fetch: this.customOptions.fetch, ...i }), h = t.headers.get("content-type") || ""; if (o) { await this.customResponseHandler(t, e, o); return; } switch (h) { case "text/event-stream": await this.sseResponseHandler(t, e); break; case "application/json": await this.jsonResponseHandler(t, e); break; default: throw new Error(`Unsupported content type: ${h}`); } } catch (t) { const h = t instanceof Error ? t : new Error("Unknown error!"); throw (r = e == null ? void 0 : e.onError) == null || r.call(e, h), h; } }, this.customResponseHandler = async (d, e, o) => { var r, t; const i = []; for await (const h of p({ readableStream: d.body, transformStream: o })) i.push(h), (r = e == null ? void 0 : e.onUpdate) == null || r.call(e, h); (t = e == null ? void 0 : e.onSuccess) == null || t.call(e, i); }, this.sseResponseHandler = async (d, e) => { var i, r; const o = []; for await (const t of p({ readableStream: d.body })) o.push(t), (i = e == null ? void 0 : e.onUpdate) == null || i.call(e, t); (r = e == null ? void 0 : e.onSuccess) == null || r.call(e, o); }, this.jsonResponseHandler = async (d, e) => { var i, r; const o = await d.json(); (i = e == null ? void 0 : e.onUpdate) == null || i.call(e, o), (r = e == null ? void 0 : e.onSuccess) == null || r.call(e, [o]); }; const { /* baseURL, model, dangerouslyApiKey, */ ...u } = n; this.baseURL = n.baseURL, this.model = n.model, this.defaultHeaders = { "Content-Type": "application/json", ...n.dangerouslyApiKey && { Authorization: n.dangerouslyApiKey } }, this.customOptions = u; } static init(n) { if (!n.baseURL || typeof n.baseURL != "string") throw new Error("The baseURL is not valid!"); const u = n.fetch || n.baseURL; return s.instanceBuffer.has(u) || s.instanceBuffer.set(u, new s(n)), s.instanceBuffer.get(u); } }; s.instanceBuffer = /* @__PURE__ */ new Map(); let f = s; const R = f.init; export { R as default };