All files / modules/book-generator/parsers subsection.parser.ts

0% Statements 0/78
100% Branches 1/1
100% Functions 1/1
0% Lines 0/78

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106                                                                                                                                                                                                                   
/**
 * 小节解析器
 * 容错解析LLM返回的小节大纲JSON
 */
 
export function parseSubsections(jsonStr: string): { subsections: any[] } | null {
  if (!jsonStr || typeof jsonStr !== 'string') {
    console.error('[SubsectionParser] 输入为空或非字符串');
    return null;
  }
 
  try {
    let data: any;
    let cleanedStr = jsonStr.trim();
 
    // 调试:打印前80个字符
    console.log('[SubsectionParser] 原始前80字符:', JSON.stringify(cleanedStr.substring(0, 80)));
 
    // 清理 JSON 字符串中的非法控制字符
    cleanedStr = cleanedStr.replace(/[\x00-\x1F\x7F]/g, (char) => {
      // 将控制字符替换为空格(换行符会导致JSON解析失败)
      return ' ';
    });
 
    // 移除 markdown 代码块标记
    cleanedStr = cleanedStr.replace(/```json\s*/gi, '').replace(/```\s*/g, '').trim();
 
    // 移除思考标签
    cleanedStr = cleanedStr.replace(/^[\s\S]*?<blockquote>\s*[\s\S]*?<\/blockquote>\s*/, '');
    // 如果以 开头,说明思考标签在JSON之前,需要移除
    // 修复:</think>是结束标签,</think>是开始标签
    const thinkEndIdx = cleanedStr.indexOf('</think>');
    if (thinkEndIdx !== -1) {
      cleanedStr = cleanedStr.substring(thinkEndIdx + 8).trim();
    }
 
    console.log('[SubsectionParser] 处理后前100字符:', JSON.stringify(cleanedStr.substring(0, 100)));
 
    try {
      data = JSON.parse(cleanedStr);
    } catch {
      // 使用括号计数法提取JSON对象
      const firstBrace = cleanedStr.indexOf('{');
      if (firstBrace === -1) {
        console.error('[SubsectionParser] 未找到 JSON 对象');
        return null;
      }
      let jsonCandidate = '';
      let depth = 0;
      let started = false;
      for (let i = firstBrace; i < cleanedStr.length; i++) {
        const ch = cleanedStr[i];
        if (ch === '{') {
          depth++;
          started = true;
        } else if (ch === '}') {
          depth--;
        }
        if (started) jsonCandidate += ch;
        if (started && depth === 0) break;
      }
      if (!jsonCandidate) {
        console.error('[SubsectionParser] JSON 对象提取失败');
        return null;
      }
      try {
        data = JSON.parse(jsonCandidate);
      } catch (parseErr) {
        console.error('[SubsectionParser] JSON 解析失败:', parseErr);
        return null;
      }
    }
 
    if (!data || typeof data !== 'object') {
      console.error('[SubsectionParser] 解析结果非对象');
      return null;
    }
 
    // 兼容:如果顶层就是数组
    if (Array.isArray(data)) {
      data = { subsections: data };
    }
 
    // 兼容多种字段名:subsections, Subsections, subsection_list 等
    let subsectionsArray = data.subsections || data.Subsections || data.subsection_list || data.section_subsections;
    
    if (!Array.isArray(subsectionsArray)) {
      console.error('[SubsectionParser] subsections 字段缺失或非数组');
      return null;
    }
 
    return {
      subsections: subsectionsArray.map((s: any, i: number) => ({
        number: s.number || i + 1,
        title: s.title || `第${i + 1}小节`,
        summary: typeof s.summary === 'string' ? s.summary : '',
        keyPoints: Array.isArray(s.keyPoints) ? s.keyPoints : [],
        estimatedWords: typeof s.estimatedWords === 'number' ? s.estimatedWords : 500,
      })),
    };
  } catch (err) {
    console.error('[SubsectionParser] 未知错误:', err);
    return null;
  }
}