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

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

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                                                                                                                                                                                   
/**
 * 节解析器
 * 容错解析LLM返回的节大纲JSON
 */
 
export function parseSections(jsonStr: string): { sections: any[] } | null {
  if (!jsonStr || typeof jsonStr !== 'string') {
    console.error('[SectionParser] 输入为空或非字符串');
    return null;
  }
 
  try {
    let data: any;
    let cleanedStr = jsonStr.trim();
 
    // 调试:打印前50个字符的编码
    const debugStr = cleanedStr.substring(0, Math.min(50, cleanedStr.length));
    console.log('[SectionParser] 原始前50字符:', JSON.stringify(debugStr));
 
    // 清理 JSON 字符串中的非法控制字符和多余空白
    cleanedStr = cleanedStr.replace(/[\x00-\x1F\x7F]/g, (char) => {
      if (char === '\n') return ' ';
      if (char === '\r') return ' ';
      if (char === '\t') return ' ';
      return ' ';
    });
 
    // 移除 markdown 代码块标记
    cleanedStr = cleanedStr.replace(/```json\s*/gi, '').replace(/```\s*/g, '').trim();
 
    // 移除思考标签
    cleanedStr = cleanedStr.replace(/^[\s\S]*?<blockquote>\s*[\s\S]*?<\/blockquote>\s*/, '');
    const secThinkIdx = cleanedStr.indexOf('</think>');
    if (secThinkIdx === 0) cleanedStr = cleanedStr.substring(secThinkIdx + 8).trim();
 
    console.log('[SectionParser] 清理后:', cleanedStr.substring(0, Math.min(100, cleanedStr.length)));
 
    try {
      data = JSON.parse(cleanedStr);
    } catch (firstErr) {
      console.log('[SectionParser] 首次解析失败,尝试正则提取');
      // 尝试找到 JSON 对象
      const match = cleanedStr.match(/\{[\s\S]*\}/);
      if (!match) {
        console.error('[SectionParser] 未找到 JSON 对象');
        return null;
      }
      try {
        const jsonCandidate = match[0];
        console.log('[SectionParser] 正则提取:', jsonCandidate.substring(0, Math.min(100, jsonCandidate.length)));
        data = JSON.parse(jsonCandidate);
      } catch (parseErr) {
        console.error('[SectionParser] JSON 解析失败:', parseErr, '原始:', cleanedStr.substring(0, 200));
        return null;
      }
    }
 
    if (!data || typeof data !== 'object') {
      console.error('[SectionParser] 解析结果非对象');
      return null;
    }
 
    // 兼容:如果顶层就是数组
    if (Array.isArray(data)) {
      data = { sections: data };
    }
 
    // 兼容多种字段名:sections, Sections, section_list 等
    let sectionsArray = data.sections || data.Sections || data.section_list || data.chapter_sections;
    
    if (!Array.isArray(sectionsArray)) {
      console.error('[SectionParser] sections 字段缺失或非数组,实际keys:', Object.keys(data));
      return null;
    }
 
    return {
      sections: sectionsArray.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 : 1000,
      })),
    };
  } catch (err) {
    console.error('[SectionParser] 未知错误:', err);
    return null;
  }
}