/** * 上传件**读成文本** —— 附件要能真正喂进活动,不能只剩一个文件名。 * * 活动那一侧读得懂的只有文字:S1 要把 BOM 拆成一行一条需求,拿到的必须是行与列, * 不是一串二进制。所以入口这一步只干一件事:**把文件读成人和模型都看得懂的文本**, * 读不出来就如实说读不出来(界面不撒谎),绝不返回一段猜出来的内容。 * * 不引第三方库:xlsx 本质是一个 ZIP 包着几份 XML,Node 自带的 `zlib.inflateRawSync` * 就能解;为一件读表的活拉进一整个电子表格库,是拿依赖换五十行代码。 * * 这一份是**纯计算**:进字节、出文本,不碰库不碰网,所以能逐条测。 */ import { inflateRawSync } from 'node:zlib'; /** 读的结果 —— text 缺席不是错误,是「这类文件读不出文本」这件事实 */ export type Extracted = { readonly text?: string; /** 一句人话:读出了什么 / 为什么读不出。会原样摆到界面上,也会进活动的入参 */ readonly note: string; }; /** 纯文本族:直接按 UTF-8 解 */ const TEXT_EXT = ['txt', 'csv', 'tsv', 'md', 'json', 'xml', 'html', 'htm', 'log', 'yaml', 'yml']; const extOf = (name: string): string => { const i = name.lastIndexOf('.'); return i === -1 ? '' : name.slice(i + 1).toLowerCase(); }; /** 表格读出来上限:再大的表也不该整份灌进提示词(超出就截,并在 note 里说清楚) */ const TEXT_CAP = 20_000; export function extractText(name: string, contentType: string, bytes: Uint8Array): Extracted { const ext = extOf(name); if (ext === 'xlsx' || contentType.includes('spreadsheetml')) return fromXlsx(bytes); if (TEXT_EXT.includes(ext) || contentType.startsWith('text/') || contentType === 'application/json') { const text = new TextDecoder('utf-8').decode(bytes); return cap(text, `按 UTF-8 文本读出 ${text.length} 字`); } return { note: `${ext === '' ? '这个文件' : `.${ext} 文件`}读不出文本 —— 只有文件名与大小进得了活动,明细请贴进正文`, }; } function cap(text: string, how: string): Extracted { if (text.length <= TEXT_CAP) return { text, note: how }; return { text: text.slice(0, TEXT_CAP), note: `${how},超出 ${TEXT_CAP} 字的部分已截断` }; } /* ==================== xlsx = ZIP + 几份 XML ==================== */ /** * 最小 ZIP 读取 —— 只认这一件事需要的部分: * 从尾部找中央目录结束记录(EOCD)→ 逐条读中央目录 → 按偏移取本地头 → 取数据段。 * * 只支持 store(0)与 deflate(8)两种压缩法 —— xlsx 出厂就这两种。 * 认不出的条目跳过而不是抛:一份表里混了一条读不了的条目,不该让整份表读不出来。 */ function readZip(bytes: Uint8Array): Map { const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); const files = new Map(); // EOCD 的签名 0x06054b50,从尾部往回找(注释段最长 64K) let eocd = -1; for (let i = bytes.length - 22; i >= 0 && i >= bytes.length - 22 - 65_536; i--) { if (view.getUint32(i, true) === 0x06054b50) { eocd = i; break; } } if (eocd === -1) return files; const count = view.getUint16(eocd + 10, true); let p = view.getUint32(eocd + 16, true); const dec = new TextDecoder('utf-8'); for (let n = 0; n < count; n++) { if (p + 46 > bytes.length || view.getUint32(p, true) !== 0x02014b50) break; const method = view.getUint16(p + 10, true); const compressed = view.getUint32(p + 20, true); const nameLen = view.getUint16(p + 28, true); const extraLen = view.getUint16(p + 30, true); const commentLen = view.getUint16(p + 32, true); const localAt = view.getUint32(p + 42, true); const entryName = dec.decode(bytes.subarray(p + 46, p + 46 + nameLen)); p += 46 + nameLen + extraLen + commentLen; // 本地头的可变段长度与中央目录的未必一致,必须照本地头自己的来 if (localAt + 30 > bytes.length || view.getUint32(localAt, true) !== 0x04034b50) continue; const lNameLen = view.getUint16(localAt + 26, true); const lExtraLen = view.getUint16(localAt + 28, true); const from = localAt + 30 + lNameLen + lExtraLen; const raw = bytes.subarray(from, from + compressed); if (method === 0) files.set(entryName, raw); else if (method === 8) { try { files.set(entryName, new Uint8Array(inflateRawSync(raw))); } catch { /* 这一条解不开就跳过 —— 别让一条坏条目把整份表拖垮 */ } } } return files; } /** XML 实体还原 —— 只有这五个是 XML 预定义的 */ function unescapeXml(s: string): string { return s .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, "'") .replace(/&#(\d+);/g, (_, code: string) => String.fromCodePoint(Number(code))) .replace(/&/g, '&'); } /** 共享字符串表:`` 一条一个字符串,里面可能被拆成多个 ``(富文本) */ function sharedStrings(xml: string): string[] { return [...xml.matchAll(/([\s\S]*?)<\/si>/g)].map((m) => [...(m[1] ?? '').matchAll(/]*>([\s\S]*?)<\/t>/g)].map((t) => unescapeXml(t[1] ?? '')).join(''), ); } /** A1 → 列号 0;AB7 → 列号 27。行号不用,行由 `` 自己划 */ function columnOf(ref: string): number { const letters = /^([A-Z]+)/.exec(ref)?.[1] ?? 'A'; let n = 0; for (const ch of letters) n = n * 26 + (ch.charCodeAt(0) - 64); return n - 1; } /** * 一张表读成 TSV —— 给模型看的东西,行列对齐比什么都重要。 * * 单元格三种取值:`t="s"` 查共享串表、`t="inlineStr"` 取内联 ``、其余取 `` 原样 * (数字、日期序列号都在这一类)。日期不转换:转错了比不转更糟,原值至少可以追。 */ function sheetToRows(xml: string, shared: readonly string[]): string[][] { const rows: string[][] = []; for (const rowMatch of xml.matchAll(/]*>([\s\S]*?)<\/row>/g)) { const cells: string[] = []; for (const cell of (rowMatch[1] ?? '').matchAll(/]*)>([\s\S]*?)<\/c>/g)) { const attrs = cell[1] ?? ''; const inner = cell[2] ?? ''; const type = /t="([^"]+)"/.exec(attrs)?.[1]; const at = columnOf(/r="([A-Z]+\d+)"/.exec(attrs)?.[1] ?? 'A1'); const v = /([\s\S]*?)<\/v>/.exec(inner)?.[1] ?? ''; let text: string; if (type === 's') text = shared[Number(v)] ?? ''; else if (type === 'inlineStr') { text = [...inner.matchAll(/]*>([\s\S]*?)<\/t>/g)].map((t) => unescapeXml(t[1] ?? '')).join(''); } else text = unescapeXml(v); while (cells.length < at) cells.push(''); cells.push(text); } // 整行皆空的不留:表尾常挂着一片格式化过的空行 if (cells.some((c) => c !== '')) rows.push(cells); } return rows; } function fromXlsx(bytes: Uint8Array): Extracted { const zip = readZip(bytes); if (zip.size === 0) return { note: '这份 .xlsx 打不开(不是合法的 ZIP 包)' }; const dec = new TextDecoder('utf-8'); const sharedRaw = zip.get('xl/sharedStrings.xml'); const shared = sharedRaw === undefined ? [] : sharedStrings(dec.decode(sharedRaw)); const sheets = [...zip.keys()].filter((k) => /^xl\/worksheets\/sheet\d+\.xml$/.test(k)).sort(); if (sheets.length === 0) return { note: '这份 .xlsx 里没有工作表' }; const parts: string[] = []; let total = 0; for (const key of sheets) { const raw = zip.get(key); if (raw === undefined) continue; const rows = sheetToRows(dec.decode(raw), shared); if (rows.length === 0) continue; total += rows.length; parts.push(sheets.length > 1 ? `# ${key.replace(/^xl\/worksheets\//, '')}` : ''); parts.push(rows.map((r) => r.join('\t')).join('\n')); } if (total === 0) return { note: '这份 .xlsx 是空的(没有一行有内容)' }; return cap(parts.filter((s) => s !== '').join('\n'), `读出 ${sheets.length} 张表、共 ${total} 行(制表符分列)`); }