@xtsai/x-supports
Version:
The biz-support is an library for both frontend & backend
132 lines • 3.99 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateJsonString = validateJsonString;
exports.chatMessagesValidate = chatMessagesValidate;
exports.trimJsonString = trimJsonString;
/**
* 校验 pretty JSON
* @param s json string
* @returns remove space & newline json string
*/
function validateJsonString(s) {
if (!s?.trim()?.length)
return '';
let jsonStr = s.trim();
const removed = [];
const quotes = [];
const allCharacters = jsonStr.split('');
for (let i = 0; i < allCharacters.length; i++) {
const part = allCharacters[i];
if (part === '"') {
quotes.push(i);
}
if (quotes.length % 2 === 0) {
if (/\n|\s/.test(part))
continue;
}
removed.push(part);
}
jsonStr = removed.join('');
try {
const obj = JSON.parse(jsonStr);
return JSON.stringify(obj);
}
catch (e) {
throw new Error(e?.message);
}
}
const AIMessageKeys = ['role', 'content'];
function chatMessagesValidate(input) {
let json = input?.trim();
if (!json?.length)
return '';
const removed = [];
const quotes = [];
const allCharacters = json.split('');
for (let i = 0; i < allCharacters.length; i++) {
const part = allCharacters[i];
if (part === '"') {
quotes.push(i);
}
if (quotes.length % 2 === 0) {
if (/\n|\s/.test(part))
continue;
}
removed.push(part);
}
json = removed.join('');
try {
const objs = JSON.parse(json);
// if (Array.isArray(objs)) throw new Error(`JSON 数据必须是数组`);
const len = objs.length;
if (!len || len % 2 !== 0)
throw new Error(`JSON 数据必须是数组格式,且符合对话形式`);
let err = '';
for (let j = 0; j < len; j++) {
const o = objs[j];
if (typeof o !== 'object') {
err = `第${j + 1}个数据为非法数据`;
break;
}
const keys = Object.keys(o);
const pass = keys.reduce((prev, current) => {
prev = AIMessageKeys.includes(current)
? prev?.length
? prev
: ''
: prev?.length
? `${prev},${current}`
: current;
return prev;
}, '');
if (pass?.length) {
err = `第${j + 1}个数据为非法格式,缺失[${pass}]属性`;
}
}
if (err?.length)
throw new Error(err);
for (let m = 0; m < len; m++) {
if (m % 2 == 0 && objs[m]?.role !== 'user') {
err = `第${m + 1}条对话不是 user`;
break;
}
if (m % 2 == 1 && objs[m]?.role !== 'assistant') {
err = `第${m + 1}条对话不是 assistant`;
break;
}
if (!objs[m].content?.length) {
err = `第${m + 1}条对话内容为空`;
break;
}
}
if (err?.length)
throw new Error(err);
json = JSON.stringify(objs);
return json;
}
catch (e) {
throw new Error(e?.message);
}
}
function trimJsonString(input) {
let json = input?.trim();
if (!json?.length)
return '';
const removed = [];
const quotes = [];
const allCharacters = json.split('');
for (let i = 0; i < allCharacters.length; i++) {
const part = allCharacters[i];
if (part === '"') {
quotes.push(i);
}
if (quotes.length % 2 === 0) {
if (/\n|\s/.test(part))
continue;
}
removed.push(part);
}
json = removed.join('');
return json;
}
//# sourceMappingURL=json-formatter.js.map