gengx
This commit is contained in:
+6
-140
@@ -1,141 +1,7 @@
|
||||
"use strict";
|
||||
const common_vendor = require("../../common/vendor.js");
|
||||
function joinApiUrl(base, path) {
|
||||
const b = String(base || "").replace(/\/+$/, "");
|
||||
const p = String(path || "").replace(/^\/+/, "");
|
||||
return p ? `${b}/${p}` : b;
|
||||
}
|
||||
function appendQuery(url, data) {
|
||||
if (!data || typeof data !== "object")
|
||||
return url;
|
||||
const keys = Object.keys(data);
|
||||
if (!keys.length)
|
||||
return url;
|
||||
const qs = keys.map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(data[k] ?? "")}`).join("&");
|
||||
return url + (url.includes("?") ? "&" : "?") + qs;
|
||||
}
|
||||
function decodeChunkData(data) {
|
||||
if (typeof data === "string")
|
||||
return data;
|
||||
if (!data)
|
||||
return "";
|
||||
if (typeof TextDecoder !== "undefined" && data instanceof ArrayBuffer) {
|
||||
return new TextDecoder("utf-8").decode(new Uint8Array(data));
|
||||
}
|
||||
if (data instanceof ArrayBuffer) {
|
||||
const bytes = new Uint8Array(data);
|
||||
let str = "";
|
||||
for (let i = 0; i < bytes.length; i++)
|
||||
str += String.fromCharCode(bytes[i]);
|
||||
try {
|
||||
return decodeURIComponent(escape(str));
|
||||
} catch (e) {
|
||||
return str;
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
function consumeSseBuffer(buffer, onEvent) {
|
||||
let rest = buffer;
|
||||
let idx = rest.indexOf("\n\n");
|
||||
while (idx !== -1) {
|
||||
const block = rest.slice(0, idx);
|
||||
rest = rest.slice(idx + 2);
|
||||
let event = "message";
|
||||
let dataLine = "";
|
||||
block.split("\n").forEach((line) => {
|
||||
if (line.startsWith("event:"))
|
||||
event = line.slice(6).trim();
|
||||
else if (line.startsWith("data:"))
|
||||
dataLine += line.slice(5).trim();
|
||||
});
|
||||
if (dataLine) {
|
||||
try {
|
||||
onEvent(event, JSON.parse(dataLine));
|
||||
} catch (e) {
|
||||
onEvent(event, dataLine);
|
||||
}
|
||||
}
|
||||
idx = rest.indexOf("\n\n");
|
||||
}
|
||||
return rest;
|
||||
}
|
||||
function parsePartialDietPlainText(text) {
|
||||
const out = {};
|
||||
if (!text)
|
||||
return out;
|
||||
const lineRe = /^(早餐|喝的|午餐|晚餐|提示|少碰)[::]\s*(.*)$/gm;
|
||||
let match;
|
||||
while ((match = lineRe.exec(text)) !== null) {
|
||||
const key = { "早餐": "breakfast", "喝的": "drinks", "午餐": "lunch", "晚餐": "dinner", "提示": "tips", "少碰": "avoid" }[match[1]];
|
||||
const val = (match[2] || "").trim();
|
||||
if (key === "avoid") {
|
||||
out.avoid = val.split(/[、,,;;\s]+/).map((s) => s.trim()).filter(Boolean);
|
||||
} else {
|
||||
out[key] = val;
|
||||
}
|
||||
}
|
||||
const tail = text.match(/(?:^|\n)(早餐|喝的|午餐|晚餐|提示|少碰)[::]\s*([^\n]*)$/);
|
||||
if (tail) {
|
||||
const key = { "早餐": "breakfast", "喝的": "drinks", "午餐": "lunch", "晚餐": "dinner", "提示": "tips", "少碰": "avoid" }[tail[1]];
|
||||
const val = (tail[2] || "").trim();
|
||||
if (key === "avoid") {
|
||||
if (val)
|
||||
out.avoid = val.split(/[、,,;;\s]+/).map((s) => s.trim()).filter(Boolean);
|
||||
} else {
|
||||
out[key] = val;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
function requestAiStream(opts) {
|
||||
const {
|
||||
baseUrl,
|
||||
url,
|
||||
method = "GET",
|
||||
data = {},
|
||||
onEvent,
|
||||
fallback
|
||||
} = opts;
|
||||
return new Promise((resolve, reject) => {
|
||||
const token = common_vendor.index.getStorageSync("token") || "";
|
||||
let sseBuffer = "";
|
||||
let requestUrl = joinApiUrl(baseUrl, url);
|
||||
if (method === "GET") {
|
||||
requestUrl = appendQuery(requestUrl, data);
|
||||
}
|
||||
const task = common_vendor.wx$1.request({
|
||||
url: requestUrl,
|
||||
method,
|
||||
data: method === "POST" ? data : {},
|
||||
enableChunked: true,
|
||||
timeout: 6e4,
|
||||
header: {
|
||||
token,
|
||||
"content-type": "application/x-www-form-urlencoded",
|
||||
"Cache-Control": "no-cache"
|
||||
},
|
||||
success: (res) => {
|
||||
if (res && res.data) {
|
||||
sseBuffer += decodeChunkData(res.data);
|
||||
sseBuffer = consumeSseBuffer(sseBuffer, onEvent);
|
||||
}
|
||||
resolve(res);
|
||||
},
|
||||
fail: (err) => reject(err)
|
||||
});
|
||||
if (task && typeof task.onChunkReceived === "function") {
|
||||
task.onChunkReceived((res) => {
|
||||
sseBuffer += decodeChunkData(res.data);
|
||||
sseBuffer = consumeSseBuffer(sseBuffer, onEvent);
|
||||
});
|
||||
} else if (typeof fallback === "function") {
|
||||
fallback().then(resolve).catch(reject);
|
||||
} else {
|
||||
reject(new Error("当前环境不支持流式请求"));
|
||||
}
|
||||
});
|
||||
}
|
||||
exports.parsePartialDietPlainText = parsePartialDietPlainText;
|
||||
exports.requestAiStream = requestAiStream;
|
||||
"use strict";const p=require("../../common/vendor.js");function k(e,n){const r=String(e||"").replace(/\/+$/,""),t=String(n||"").replace(/^\/+/,"");return t?`${r}/${t}`:r}function v(e,n){if(!n||typeof n!="object")return e;const r=Object.keys(n);if(!r.length)return e;const t=r.map(c=>`${encodeURIComponent(c)}=${encodeURIComponent(n[c]??"")}`).join("&");return e+(e.includes("?")?"&":"?")+t}function m(e){if(typeof e=="string")return e;if(!e)return"";if(typeof TextDecoder<"u"&&e instanceof ArrayBuffer)return new TextDecoder("utf-8").decode(new Uint8Array(e));if(e instanceof ArrayBuffer){const n=new Uint8Array(e);let r="";for(let t=0;t<n.length;t++)r+=String.fromCharCode(n[t]);try{return decodeURIComponent(escape(r))}catch{return r}}return""}function h(e,n){let r=e,t=r.indexOf(`
|
||||
|
||||
`);for(;t!==-1;){const c=r.slice(0,t);r=r.slice(t+2);let o="message",i="";if(c.split(`
|
||||
`).forEach(s=>{s.startsWith("event:")?o=s.slice(6).trim():s.startsWith("data:")&&(i+=s.slice(5).trim())}),i)try{n(o,JSON.parse(i))}catch{n(o,i)}t=r.indexOf(`
|
||||
|
||||
`)}return r}function w(e){const n={};if(!e)return n;const r=/^(早餐|喝的|午餐|晚餐|提示|少碰)[::]\s*(.*)$/gm;let t;for(;(t=r.exec(e))!==null;){const o={早餐:"breakfast",喝的:"drinks",午餐:"lunch",晚餐:"dinner",提示:"tips",少碰:"avoid"}[t[1]],i=(t[2]||"").trim();o==="avoid"?n.avoid=i.split(/[、,,;;\s]+/).map(s=>s.trim()).filter(Boolean):n[o]=i}const c=e.match(/(?:^|\n)(早餐|喝的|午餐|晚餐|提示|少碰)[::]\s*([^\n]*)$/);if(c){const o={早餐:"breakfast",喝的:"drinks",午餐:"lunch",晚餐:"dinner",提示:"tips",少碰:"avoid"}[c[1]],i=(c[2]||"").trim();o==="avoid"?i&&(n.avoid=i.split(/[、,,;;\s]+/).map(s=>s.trim()).filter(Boolean)):n[o]=i}return n}function C(e){const{baseUrl:n,url:r,method:t="GET",data:c={},onEvent:o,fallback:i}=e;return new Promise((s,l)=>{const y=p.index.getStorageSync("token")||"";let f="",u=k(n,r);t==="GET"&&(u=v(u,c));const d=p.wx$1.request({url:u,method:t,data:t==="POST"?c:{},enableChunked:!0,timeout:6e4,header:{token:y,"content-type":"application/x-www-form-urlencoded","Cache-Control":"no-cache"},success:a=>{a&&a.data&&(f+=m(a.data),f=h(f,o)),s(a)},fail:a=>l(a)});d&&typeof d.onChunkReceived=="function"?d.onChunkReceived(a=>{f+=m(a.data),f=h(f,o)}):typeof i=="function"?i().then(s).catch(l):l(new Error("当前环境不支持流式请求"))})}exports.parsePartialDietPlainText=w;exports.requestAiStream=C;
|
||||
//# sourceMappingURL=../../../.sourcemap/mp-weixin/tongji/utils/aiStreamRequest.js.map
|
||||
|
||||
Reference in New Issue
Block a user