Initial public release
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "@genoffice/file-parse",
|
||||
"version": "0.1.0",
|
||||
"license": "Apache-2.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "shared attachment parsing: pdf/docx/pptx/xlsx and plain-text formats to text; images flagged for multimodal input",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest"
|
||||
},
|
||||
"dependencies": {
|
||||
"@genoffice/docx-engine": "*",
|
||||
"fast-xml-parser": "^5.3.4",
|
||||
"jszip": "^3.10.1",
|
||||
"pdfjs-dist": "^5.4.54"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.10.1",
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^4.1.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { parseDocx } from '@genoffice/docx-engine'
|
||||
|
||||
/** flatten a parsed docx into readable text (structure markers preserved) */
|
||||
export async function docxToText(bytes: Uint8Array): Promise<string> {
|
||||
const doc = await parseDocx(new Uint8Array(bytes))
|
||||
const lines: string[] = []
|
||||
for (const block of doc.blocks) {
|
||||
if (block.hidden) continue
|
||||
switch (block.type) {
|
||||
case 'heading':
|
||||
lines.push(`${'#'.repeat(Math.min(block.level ?? 1, 6))} ${runText(block)}`)
|
||||
break
|
||||
case 'listItem':
|
||||
lines.push(`- ${runText(block)}`)
|
||||
break
|
||||
case 'paragraph':
|
||||
lines.push(runText(block))
|
||||
break
|
||||
case 'table': {
|
||||
const rows = block.table?.rows ?? []
|
||||
for (const row of rows) {
|
||||
lines.push(row.map((cell) => cell.paras.join(' ')).join(' | '))
|
||||
}
|
||||
break
|
||||
}
|
||||
default:
|
||||
if (block.textboxes?.length) {
|
||||
for (const box of block.textboxes) {
|
||||
for (const para of box.paras) lines.push(para.runs.map((r) => r.text).join(''))
|
||||
}
|
||||
} else if (block.previewText) {
|
||||
lines.push(block.previewText)
|
||||
}
|
||||
}
|
||||
}
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
function runText(block: { runs?: { text: string }[] }): string {
|
||||
return (block.runs ?? []).map((r) => r.text).join('')
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export { parseFileToText, type ParsedFile, type ParsedFileKind } from './parse'
|
||||
export { docxToText } from './docx'
|
||||
export { pptxToText } from './pptx'
|
||||
export { xlsxToText } from './xlsx'
|
||||
export { pdfToText } from './pdf'
|
||||
@@ -0,0 +1,63 @@
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { extname } from 'node:path'
|
||||
import { docxToText } from './docx'
|
||||
import { pdfToText } from './pdf'
|
||||
import { pptxToText } from './pptx'
|
||||
import { xlsxToText } from './xlsx'
|
||||
|
||||
export type ParsedFileKind = 'text' | 'image' | 'unsupported'
|
||||
|
||||
export interface ParsedFile {
|
||||
ok: boolean
|
||||
text?: string
|
||||
kind: ParsedFileKind
|
||||
mime?: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
/** No text extraction for images: callers read raw bytes and go multimodal (see @genoffice/ai-provider images support) */
|
||||
const IMAGE_MIMES: Record<string, string> = {
|
||||
png: 'image/png',
|
||||
jpg: 'image/jpeg',
|
||||
jpeg: 'image/jpeg',
|
||||
gif: 'image/gif',
|
||||
webp: 'image/webp',
|
||||
}
|
||||
|
||||
const TEXT_EXTS = new Set([
|
||||
'txt',
|
||||
'md',
|
||||
'markdown',
|
||||
'csv',
|
||||
'tsv',
|
||||
'json',
|
||||
'xml',
|
||||
'html',
|
||||
'htm',
|
||||
'log',
|
||||
])
|
||||
|
||||
/** parse an attachment into plain text (or flag it as image / unsupported) */
|
||||
export async function parseFileToText(filePath: string): Promise<ParsedFile> {
|
||||
const ext = extname(filePath).slice(1).toLowerCase()
|
||||
const imageMime = IMAGE_MIMES[ext]
|
||||
if (imageMime) return { ok: true, kind: 'image', mime: imageMime }
|
||||
try {
|
||||
if (TEXT_EXTS.has(ext)) {
|
||||
return { ok: true, kind: 'text', text: await readFile(filePath, 'utf-8') }
|
||||
}
|
||||
switch (ext) {
|
||||
case 'docx':
|
||||
return { ok: true, kind: 'text', text: await docxToText(await readFile(filePath)) }
|
||||
case 'pptx':
|
||||
return { ok: true, kind: 'text', text: await pptxToText(await readFile(filePath)) }
|
||||
case 'xlsx':
|
||||
return { ok: true, kind: 'text', text: await xlsxToText(await readFile(filePath)) }
|
||||
case 'pdf':
|
||||
return { ok: true, kind: 'text', text: await pdfToText(await readFile(filePath)) }
|
||||
}
|
||||
} catch (e) {
|
||||
return { ok: false, kind: 'text', error: e instanceof Error ? e.message : String(e) }
|
||||
}
|
||||
return { ok: false, kind: 'unsupported', error: `Unsupported file type: .${ext || 'unknown'}` }
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import { createRequire } from 'node:module'
|
||||
import { dirname, join } from 'node:path'
|
||||
|
||||
// pdfjs needs the standard_fonts data directory for non-embedded standard fonts
|
||||
// (Helvetica etc.); under Node a filesystem path works (same usage as the official
|
||||
// Node example). The packaged build may fail require.resolve (only out/** is bundled),
|
||||
// so return undefined and omit it — degrading to "non-embedded standard fonts may be
|
||||
// slightly incomplete" (most embedded-font PDFs unaffected) instead of crashing parsing.
|
||||
function standardFontDataUrl(): string | undefined {
|
||||
try {
|
||||
const require = createRequire(import.meta.url)
|
||||
const pdfPath = require.resolve('pdfjs-dist/legacy/build/pdf.mjs')
|
||||
return `${join(dirname(pdfPath), '..', '..', 'standard_fonts')}/`
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* pdfjs's Node compat layer borrows DOMMatrix from the optional dep @napi-rs/canvas,
|
||||
* and pdf.mjs calls `new DOMMatrix()` at module top level — in the packaged build
|
||||
* (no node_modules inside asar) the require fails, so the import throws
|
||||
* "DOMMatrix is not defined" and PDF attachment parsing breaks entirely (not
|
||||
* reproducible in dev since the dep happens to be present). Text extraction only
|
||||
* needs a tiny subset of 2D affine matrices, so ship a pure-JS fallback that
|
||||
* doesn't depend on packaging layout.
|
||||
*/
|
||||
function installDomMatrixPolyfill(): void {
|
||||
const g = globalThis as { DOMMatrix?: unknown }
|
||||
if (g.DOMMatrix) return
|
||||
class DOMMatrixPolyfill {
|
||||
a = 1; b = 0; c = 0; d = 1; e = 0; f = 0
|
||||
constructor(init?: number[] | DOMMatrixPolyfill) {
|
||||
if (Array.isArray(init) && init.length >= 6) {
|
||||
;[this.a, this.b, this.c, this.d, this.e, this.f] = init as [number, number, number, number, number, number]
|
||||
} else if (init && typeof init === 'object') {
|
||||
const m = init as DOMMatrixPolyfill
|
||||
this.a = m.a; this.b = m.b; this.c = m.c; this.d = m.d; this.e = m.e; this.f = m.f
|
||||
}
|
||||
}
|
||||
get is2D(): boolean { return true }
|
||||
get isIdentity(): boolean {
|
||||
return this.a === 1 && this.b === 0 && this.c === 0 && this.d === 1 && this.e === 0 && this.f === 0
|
||||
}
|
||||
/** this × other (DOM spec semantics: result applied to a point = this(other(p))) */
|
||||
#product(o: DOMMatrixPolyfill): [number, number, number, number, number, number] {
|
||||
return [
|
||||
this.a * o.a + this.c * o.b,
|
||||
this.b * o.a + this.d * o.b,
|
||||
this.a * o.c + this.c * o.d,
|
||||
this.b * o.c + this.d * o.d,
|
||||
this.a * o.e + this.c * o.f + this.e,
|
||||
this.b * o.e + this.d * o.f + this.f,
|
||||
]
|
||||
}
|
||||
#assign(v: [number, number, number, number, number, number]): this {
|
||||
;[this.a, this.b, this.c, this.d, this.e, this.f] = v
|
||||
return this
|
||||
}
|
||||
multiply(o: DOMMatrixPolyfill): DOMMatrixPolyfill { return new DOMMatrixPolyfill(this.#product(o)) }
|
||||
multiplySelf(o: DOMMatrixPolyfill): this { return this.#assign(this.#product(o)) }
|
||||
preMultiplySelf(o: DOMMatrixPolyfill): this { return this.#assign(o.#product(this)) }
|
||||
translate(tx = 0, ty = 0): DOMMatrixPolyfill {
|
||||
return this.multiply(new DOMMatrixPolyfill([1, 0, 0, 1, tx, ty]))
|
||||
}
|
||||
translateSelf(tx = 0, ty = 0): this { return this.multiplySelf(new DOMMatrixPolyfill([1, 0, 0, 1, tx, ty])) }
|
||||
scale(sx = 1, sy?: number): DOMMatrixPolyfill {
|
||||
return this.multiply(new DOMMatrixPolyfill([sx, 0, 0, sy ?? sx, 0, 0]))
|
||||
}
|
||||
scaleSelf(sx = 1, sy?: number): this { return this.multiplySelf(new DOMMatrixPolyfill([sx, 0, 0, sy ?? sx, 0, 0])) }
|
||||
invertSelf(): this {
|
||||
const { a, b, c, d, e, f } = this
|
||||
const det = a * d - b * c
|
||||
if (!det || !Number.isFinite(det)) return this.#assign([NaN, NaN, NaN, NaN, NaN, NaN])
|
||||
return this.#assign([d / det, -b / det, -c / det, a / det, (c * f - d * e) / det, (b * e - a * f) / det])
|
||||
}
|
||||
inverse(): DOMMatrixPolyfill { return new DOMMatrixPolyfill(this).invertSelf() }
|
||||
transformPoint(p: { x?: number; y?: number } = {}): { x: number; y: number; z: number; w: number } {
|
||||
const x = p.x ?? 0
|
||||
const y = p.y ?? 0
|
||||
return { x: this.a * x + this.c * y + this.e, y: this.b * x + this.d * y + this.f, z: 0, w: 1 }
|
||||
}
|
||||
}
|
||||
g.DOMMatrix = DOMMatrixPolyfill
|
||||
}
|
||||
|
||||
/** extract text from a pdf with pdfjs-dist (pure JS, no native deps), one section per page */
|
||||
export async function pdfToText(bytes: Uint8Array): Promise<string> {
|
||||
installDomMatrixPolyfill()
|
||||
// Explicitly import the worker module (its top level registers globalThis.pdfjsWorker,
|
||||
// which the fake worker prefers) — otherwise pdfjs looks up pdf.worker.mjs by path at
|
||||
// runtime, the file isn't next to the bundled chunk, and it fails with "Setting up fake
|
||||
// worker failed". A literal specifier lets the bundler include it in the output.
|
||||
// @ts-expect-error the worker build artifact has no type declarations; imported only for its top-level side effect (registering globalThis.pdfjsWorker)
|
||||
await import('pdfjs-dist/legacy/build/pdf.worker.mjs')
|
||||
const { getDocument } = await import('pdfjs-dist/legacy/build/pdf.mjs')
|
||||
const fontUrl = standardFontDataUrl()
|
||||
const doc = await getDocument({
|
||||
// pdfjs transfers the given buffer, so pass a copy
|
||||
data: new Uint8Array(bytes),
|
||||
useSystemFonts: true,
|
||||
...(fontUrl ? { standardFontDataUrl: fontUrl } : {}),
|
||||
verbosity: 0,
|
||||
}).promise
|
||||
try {
|
||||
const pages: string[] = []
|
||||
for (let i = 1; i <= doc.numPages; i++) {
|
||||
const page = await doc.getPage(i)
|
||||
const content = await page.getTextContent()
|
||||
let text = ''
|
||||
for (const item of content.items) {
|
||||
if ('str' in item) {
|
||||
text += item.str
|
||||
if (item.hasEOL) text += '\n'
|
||||
}
|
||||
}
|
||||
pages.push(text.trim())
|
||||
page.cleanup()
|
||||
}
|
||||
return pages.join('\n\n')
|
||||
} finally {
|
||||
await doc.destroy()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import JSZip from 'jszip'
|
||||
import { XMLParser } from 'fast-xml-parser'
|
||||
|
||||
const parser = new XMLParser({ ignoreAttributes: true })
|
||||
|
||||
function slideNumber(path: string): number {
|
||||
const m = /slide(\d+)\.xml$/.exec(path)
|
||||
return m ? Number(m[1]) : 0
|
||||
}
|
||||
|
||||
/** collect the text of all a:t descendants of one node */
|
||||
function collectText(node: unknown, out: string[]): void {
|
||||
if (node == null) return
|
||||
if (typeof node === 'string' || typeof node === 'number') {
|
||||
out.push(String(node))
|
||||
return
|
||||
}
|
||||
if (Array.isArray(node)) {
|
||||
for (const item of node) collectText(item, out)
|
||||
return
|
||||
}
|
||||
if (typeof node === 'object') {
|
||||
for (const [key, value] of Object.entries(node)) {
|
||||
if (key === 'a:t') collectText(value, out)
|
||||
else if (typeof value === 'object') collectText(value, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** walk the slide tree; each a:p paragraph becomes one output line */
|
||||
function collectParagraphs(node: unknown, out: string[]): void {
|
||||
if (node == null || typeof node !== 'object') return
|
||||
if (Array.isArray(node)) {
|
||||
for (const item of node) collectParagraphs(item, out)
|
||||
return
|
||||
}
|
||||
for (const [key, value] of Object.entries(node)) {
|
||||
if (key === 'a:p') {
|
||||
for (const para of Array.isArray(value) ? value : [value]) {
|
||||
const texts: string[] = []
|
||||
collectText(para, texts)
|
||||
const line = texts.join('')
|
||||
if (line.trim()) out.push(line)
|
||||
}
|
||||
} else {
|
||||
collectParagraphs(value, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** extract slide text from a pptx: one "## Slide N" section per slide, one line per paragraph */
|
||||
export async function pptxToText(bytes: Uint8Array): Promise<string> {
|
||||
const zip = await JSZip.loadAsync(bytes)
|
||||
const slidePaths = Object.keys(zip.files)
|
||||
.filter((p) => /^ppt\/slides\/slide\d+\.xml$/.test(p))
|
||||
.sort((a, b) => slideNumber(a) - slideNumber(b))
|
||||
const sections: string[] = []
|
||||
for (const path of slidePaths) {
|
||||
const xml = await zip.files[path]!.async('text')
|
||||
const paras: string[] = []
|
||||
collectParagraphs(parser.parse(xml), paras)
|
||||
sections.push([`## Slide ${slideNumber(path)}`, ...paras].join('\n'))
|
||||
}
|
||||
return sections.join('\n\n')
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import JSZip from 'jszip'
|
||||
import { XMLParser } from 'fast-xml-parser'
|
||||
|
||||
const parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '@_' })
|
||||
|
||||
function asArray<T>(value: T | T[] | undefined): T[] {
|
||||
if (value === undefined || value === null) return []
|
||||
return Array.isArray(value) ? value : [value]
|
||||
}
|
||||
|
||||
/** unwrap a fast-xml-parser text node (plain value, or { '#text': ... } when it carried attributes) */
|
||||
function textOf(node: unknown): string {
|
||||
if (node == null) return ''
|
||||
if (typeof node === 'object' && !Array.isArray(node)) {
|
||||
return textOf((node as Record<string, unknown>)['#text'])
|
||||
}
|
||||
return String(node)
|
||||
}
|
||||
|
||||
/** shared string entry: <si><t>…</t></si> or rich-text runs <si><r><t>…</t></r>…</si> */
|
||||
function sharedStringText(si: Record<string, unknown>): string {
|
||||
if (si['t'] !== undefined) return textOf(si['t'])
|
||||
return asArray(si['r'] as unknown)
|
||||
.map((run) => textOf((run as Record<string, unknown>)['t']))
|
||||
.join('')
|
||||
}
|
||||
|
||||
/** "BC12" → zero-based column index 54 */
|
||||
function columnIndex(cellRef: string): number {
|
||||
let index = 0
|
||||
for (const ch of cellRef) {
|
||||
if (ch < 'A' || ch > 'Z') break
|
||||
index = index * 26 + (ch.charCodeAt(0) - 64)
|
||||
}
|
||||
return index - 1
|
||||
}
|
||||
|
||||
interface Cell {
|
||||
'@_r'?: string
|
||||
'@_t'?: string
|
||||
v?: unknown
|
||||
is?: Record<string, unknown>
|
||||
}
|
||||
|
||||
function cellText(cell: Cell, shared: string[]): string {
|
||||
const type = cell['@_t'] ?? ''
|
||||
if (type === 's') return shared[Number(textOf(cell.v))] ?? ''
|
||||
if (type === 'inlineStr') return cell.is ? sharedStringText(cell.is) : ''
|
||||
if (type === 'b') return textOf(cell.v) === '1' ? 'TRUE' : 'FALSE'
|
||||
return textOf(cell.v)
|
||||
}
|
||||
|
||||
async function zipText(zip: JSZip, path: string): Promise<string | undefined> {
|
||||
const file = zip.file(path)
|
||||
return file ? file.async('text') : undefined
|
||||
}
|
||||
|
||||
/** extract sheet text from an xlsx: one "# SheetName" section per sheet, cells joined with " | " */
|
||||
export async function xlsxToText(bytes: Uint8Array): Promise<string> {
|
||||
const zip = await JSZip.loadAsync(bytes)
|
||||
const workbookXml = await zipText(zip, 'xl/workbook.xml')
|
||||
if (!workbookXml) throw new Error('Invalid xlsx: missing xl/workbook.xml')
|
||||
|
||||
// Sheet order and names come from workbook.xml; r:id maps to the actual sheet path via the workbook rels
|
||||
const workbook = parser.parse(workbookXml) as Record<string, any>
|
||||
const sheets = asArray(workbook.workbook?.sheets?.sheet) as Array<Record<string, unknown>>
|
||||
|
||||
const relsXml = await zipText(zip, 'xl/_rels/workbook.xml.rels')
|
||||
const relTargets = new Map<string, string>()
|
||||
if (relsXml) {
|
||||
const rels = parser.parse(relsXml) as Record<string, any>
|
||||
for (const rel of asArray(rels.Relationships?.Relationship) as Array<Record<string, unknown>>) {
|
||||
const target = String(rel['@_Target'] ?? '')
|
||||
relTargets.set(
|
||||
String(rel['@_Id'] ?? ''),
|
||||
target.startsWith('/') ? target.slice(1) : `xl/${target}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const shared: string[] = []
|
||||
const sharedXml = await zipText(zip, 'xl/sharedStrings.xml')
|
||||
if (sharedXml) {
|
||||
const sst = parser.parse(sharedXml) as Record<string, any>
|
||||
for (const si of asArray(sst.sst?.si) as Array<Record<string, unknown>>) {
|
||||
shared.push(sharedStringText(si))
|
||||
}
|
||||
}
|
||||
|
||||
const sections: string[] = []
|
||||
for (const sheet of sheets) {
|
||||
const path = relTargets.get(String(sheet['@_r:id'] ?? ''))
|
||||
const sheetXml = path ? await zipText(zip, path) : undefined
|
||||
if (!sheetXml) continue
|
||||
const worksheet = parser.parse(sheetXml) as Record<string, any>
|
||||
const lines: string[] = [`# ${String(sheet['@_name'] ?? '')}`]
|
||||
for (const row of asArray(worksheet.worksheet?.sheetData?.row) as Array<Record<string, unknown>>) {
|
||||
const cells: string[] = []
|
||||
for (const cell of asArray(row.c as Cell | Cell[])) {
|
||||
const text = cellText(cell, shared)
|
||||
const col = cell['@_r'] ? columnIndex(cell['@_r']) : cells.length
|
||||
while (cells.length < col) cells.push('')
|
||||
cells[col] = text
|
||||
}
|
||||
lines.push(cells.join(' | '))
|
||||
}
|
||||
sections.push(lines.join('\n'))
|
||||
}
|
||||
return sections.join('\n\n')
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import { mkdtempSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import JSZip from 'jszip'
|
||||
|
||||
/** 1x1 red PNG */
|
||||
export const TINY_PNG_BASE64 =
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='
|
||||
|
||||
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
|
||||
let fixtureDir: string | undefined
|
||||
|
||||
/** write a fixture into a per-run temp dir and return its absolute path */
|
||||
export function writeFixture(name: string, contents: string | Uint8Array): string {
|
||||
if (!fixtureDir) fixtureDir = mkdtempSync(join(tmpdir(), 'file-parse-'))
|
||||
const path = join(fixtureDir, name)
|
||||
writeFileSync(path, contents)
|
||||
return path
|
||||
}
|
||||
|
||||
/** minimal but valid docx: heading + paragraph + list item + 2x2 table */
|
||||
export async function buildDocxFixture(): Promise<Uint8Array> {
|
||||
const zip = new JSZip()
|
||||
zip.file(
|
||||
'[Content_Types].xml',
|
||||
`${XML_DECL}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">` +
|
||||
'<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' +
|
||||
'<Default Extension="xml" ContentType="application/xml"/>' +
|
||||
'<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>' +
|
||||
'<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>' +
|
||||
'</Types>',
|
||||
)
|
||||
zip.file(
|
||||
'_rels/.rels',
|
||||
`${XML_DECL}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>' +
|
||||
'</Relationships>',
|
||||
)
|
||||
zip.file(
|
||||
'word/_rels/document.xml.rels',
|
||||
`${XML_DECL}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>' +
|
||||
'</Relationships>',
|
||||
)
|
||||
zip.file(
|
||||
'word/styles.xml',
|
||||
`${XML_DECL}<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">` +
|
||||
'<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>' +
|
||||
'<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:basedOn w:val="Normal"/>' +
|
||||
'<w:pPr><w:outlineLvl w:val="0"/></w:pPr></w:style>' +
|
||||
'</w:styles>',
|
||||
)
|
||||
const body =
|
||||
'<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>Annual Report</w:t></w:r></w:p>' +
|
||||
'<w:p><w:r><w:t>First paragraph hello docx</w:t></w:r></w:p>' +
|
||||
'<w:tbl><w:tr>' +
|
||||
'<w:tc><w:p><w:r><w:t>Metric</w:t></w:r></w:p></w:tc>' +
|
||||
'<w:tc><w:p><w:r><w:t>Value</w:t></w:r></w:p></w:tc>' +
|
||||
'</w:tr><w:tr>' +
|
||||
'<w:tc><w:p><w:r><w:t>Revenue</w:t></w:r></w:p></w:tc>' +
|
||||
'<w:tc><w:p><w:r><w:t>100</w:t></w:r></w:p></w:tc>' +
|
||||
'</w:tr></w:tbl>'
|
||||
const sectPr =
|
||||
'<w:sectPr><w:pgSz w:w="11906" w:h="16838"/>' +
|
||||
'<w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="708" w:footer="708" w:gutter="0"/>' +
|
||||
'</w:sectPr>'
|
||||
zip.file(
|
||||
'word/document.xml',
|
||||
`${XML_DECL}<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ` +
|
||||
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' +
|
||||
`<w:body>${body}${sectPr}</w:body></w:document>`,
|
||||
)
|
||||
return zip.generateAsync({ type: 'uint8array', compression: 'DEFLATE' })
|
||||
}
|
||||
|
||||
function slideXml(paragraphs: string[][]): string {
|
||||
const paras = paragraphs
|
||||
.map((runs) => `<a:p>${runs.map((t) => `<a:r><a:t>${t}</a:t></a:r>`).join('')}</a:p>`)
|
||||
.join('')
|
||||
return (
|
||||
`${XML_DECL}<p:sld xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" ` +
|
||||
'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">' +
|
||||
`<p:cSld><p:spTree><p:sp><p:txBody>${paras}</p:txBody></p:sp></p:spTree></p:cSld></p:sld>`
|
||||
)
|
||||
}
|
||||
|
||||
/** minimal pptx: only the slide parts our parser reads (3 slides incl. slide10 for numeric ordering) */
|
||||
export async function buildPptxFixture(): Promise<Uint8Array> {
|
||||
const zip = new JSZip()
|
||||
zip.file('ppt/slides/slide1.xml', slideXml([['Product', 'Intro'], ['First slide subtitle']]))
|
||||
zip.file('ppt/slides/slide2.xml', slideXml([['Market Analysis']]))
|
||||
zip.file('ppt/slides/slide10.xml', slideXml([['Summary Slide']]))
|
||||
return zip.generateAsync({ type: 'uint8array', compression: 'DEFLATE' })
|
||||
}
|
||||
|
||||
/** minimal xlsx: shared strings (incl. rich-text runs), inline string, number, boolean, skipped column */
|
||||
export async function buildXlsxFixture(): Promise<Uint8Array> {
|
||||
const zip = new JSZip()
|
||||
zip.file(
|
||||
'xl/workbook.xml',
|
||||
`${XML_DECL}<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" ` +
|
||||
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' +
|
||||
'<sheets><sheet name="Grades" sheetId="1" r:id="rId1"/></sheets></workbook>',
|
||||
)
|
||||
zip.file(
|
||||
'xl/_rels/workbook.xml.rels',
|
||||
`${XML_DECL}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>' +
|
||||
'</Relationships>',
|
||||
)
|
||||
zip.file(
|
||||
'xl/sharedStrings.xml',
|
||||
`${XML_DECL}<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="2" uniqueCount="2">` +
|
||||
'<si><t>Name</t></si>' +
|
||||
'<si><r><t>Sco</t></r><r><t>res</t></r></si>' +
|
||||
'</sst>',
|
||||
)
|
||||
zip.file(
|
||||
'xl/worksheets/sheet1.xml',
|
||||
`${XML_DECL}<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>` +
|
||||
'<row r="1"><c r="A1" t="s"><v>0</v></c><c r="B1" t="s"><v>1</v></c></row>' +
|
||||
'<row r="2"><c r="A2" t="inlineStr"><is><t>Alice</t></is></c><c r="B2"><v>95</v></c><c r="D2" t="b"><v>1</v></c></row>' +
|
||||
'</sheetData></worksheet>',
|
||||
)
|
||||
return zip.generateAsync({ type: 'uint8array', compression: 'DEFLATE' })
|
||||
}
|
||||
|
||||
/** minimal single-page pdf with an uncompressed content stream and a correct xref table */
|
||||
export function buildPdfFixture(text: string): Uint8Array {
|
||||
const stream = `BT /F1 24 Tf 72 720 Td (${text}) Tj ET`
|
||||
const bodies = [
|
||||
'<< /Type /Catalog /Pages 2 0 R >>',
|
||||
'<< /Type /Pages /Kids [3 0 R] /Count 1 >>',
|
||||
'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>',
|
||||
`<< /Length ${stream.length} >>\nstream\n${stream}\nendstream`,
|
||||
'<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>',
|
||||
]
|
||||
let out = '%PDF-1.4\n'
|
||||
const offsets: number[] = [0]
|
||||
for (let i = 0; i < bodies.length; i++) {
|
||||
offsets.push(out.length)
|
||||
out += `${i + 1} 0 obj\n${bodies[i]}\nendobj\n`
|
||||
}
|
||||
const xrefStart = out.length
|
||||
out += `xref\n0 ${bodies.length + 1}\n0000000000 65535 f \n`
|
||||
for (let i = 1; i <= bodies.length; i++) {
|
||||
out += `${String(offsets[i]).padStart(10, '0')} 00000 n \n`
|
||||
}
|
||||
out += `trailer\n<< /Size ${bodies.length + 1} /Root 1 0 R >>\nstartxref\n${xrefStart}\n%%EOF`
|
||||
return new TextEncoder().encode(out)
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseFileToText } from '../src/index'
|
||||
import {
|
||||
buildDocxFixture,
|
||||
buildPptxFixture,
|
||||
buildXlsxFixture,
|
||||
writeFixture,
|
||||
} from './helpers/fixtures'
|
||||
|
||||
describe('parseFileToText: docx', () => {
|
||||
it('extracts headings, paragraphs and tables', async () => {
|
||||
const path = writeFixture('report.docx', await buildDocxFixture())
|
||||
const result = await parseFileToText(path)
|
||||
expect(result.ok).toBe(true)
|
||||
expect(result.kind).toBe('text')
|
||||
expect(result.text).toContain('# Annual Report')
|
||||
expect(result.text).toContain('First paragraph hello docx')
|
||||
expect(result.text).toContain('Metric | Value')
|
||||
expect(result.text).toContain('Revenue | 100')
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseFileToText: pptx', () => {
|
||||
it('extracts one section per slide in numeric order', async () => {
|
||||
const path = writeFixture('deck.pptx', await buildPptxFixture())
|
||||
const result = await parseFileToText(path)
|
||||
expect(result.ok).toBe(true)
|
||||
expect(result.text).toContain('## Slide 1\nProductIntro\nFirst slide subtitle')
|
||||
expect(result.text).toContain('## Slide 2\nMarket Analysis')
|
||||
// slide10 must sort after slide2 (numeric, not lexicographic)
|
||||
expect(result.text!.indexOf('## Slide 10')).toBeGreaterThan(result.text!.indexOf('## Slide 2'))
|
||||
expect(result.text).toContain('## Slide 10\nSummary Slide')
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseFileToText: xlsx', () => {
|
||||
it('extracts sheet name, shared/inline strings, numbers, booleans and empty columns', async () => {
|
||||
const path = writeFixture('table.xlsx', await buildXlsxFixture())
|
||||
const result = await parseFileToText(path)
|
||||
expect(result.ok).toBe(true)
|
||||
expect(result.text).toContain('# Grades')
|
||||
expect(result.text).toContain('Name | Scores')
|
||||
// C2 is missing so the boolean in D2 lands in the 4th column
|
||||
expect(result.text).toContain('Alice | 95 | | TRUE')
|
||||
})
|
||||
|
||||
it('fails gracefully on a corrupt file', async () => {
|
||||
const path = writeFixture('broken.xlsx', Buffer.from('not a zip'))
|
||||
const result = await parseFileToText(path)
|
||||
expect(result.ok).toBe(false)
|
||||
expect(result.error).toBeTruthy()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseFileToText } from '../src/index'
|
||||
import { buildPdfFixture, writeFixture } from './helpers/fixtures'
|
||||
|
||||
describe('parseFileToText: pdf', () => {
|
||||
it('extracts page text via pdfjs', async () => {
|
||||
const path = writeFixture('doc.pdf', buildPdfFixture('Hello PDF parsing'))
|
||||
const result = await parseFileToText(path)
|
||||
expect(result.ok).toBe(true)
|
||||
expect(result.kind).toBe('text')
|
||||
expect(result.text).toContain('Hello PDF parsing')
|
||||
})
|
||||
|
||||
it('fails gracefully on a corrupt pdf', async () => {
|
||||
const path = writeFixture('broken.pdf', Buffer.from('%PDF-1.4 garbage'))
|
||||
const result = await parseFileToText(path)
|
||||
expect(result.ok).toBe(false)
|
||||
expect(result.error).toBeTruthy()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseFileToText } from '../src/index'
|
||||
import { writeFixture } from './helpers/fixtures'
|
||||
|
||||
describe('parseFileToText: plain-text formats', () => {
|
||||
const cases: Array<[string, string]> = [
|
||||
['sample.txt', 'plain text hello'],
|
||||
['sample.md', '# Title\n\nBody paragraph'],
|
||||
['sample.csv', 'a,b,c\n1,2,3'],
|
||||
['sample.tsv', 'a\tb\tc\n1\t2\t3'],
|
||||
['sample.json', '{"key":"value"}'],
|
||||
['sample.xml', '<root><item>value</item></root>'],
|
||||
['sample.html', '<html><body><p>page</p></body></html>'],
|
||||
]
|
||||
|
||||
for (const [name, content] of cases) {
|
||||
it(`reads ${name} verbatim`, async () => {
|
||||
const path = writeFixture(name, content)
|
||||
const result = await parseFileToText(path)
|
||||
expect(result).toEqual({ ok: true, kind: 'text', text: content })
|
||||
})
|
||||
}
|
||||
|
||||
it('is case-insensitive on the extension', async () => {
|
||||
const path = writeFixture('UPPER.TXT', 'upper')
|
||||
const result = await parseFileToText(path)
|
||||
expect(result.ok).toBe(true)
|
||||
expect(result.text).toBe('upper')
|
||||
})
|
||||
|
||||
it('fails gracefully on a missing file', async () => {
|
||||
const result = await parseFileToText('/nonexistent/nowhere.txt')
|
||||
expect(result.ok).toBe(false)
|
||||
expect(result.error).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseFileToText: images and unsupported', () => {
|
||||
it('flags png as image without extracting text', async () => {
|
||||
const path = writeFixture('pic.png', Buffer.from('89504e47', 'hex'))
|
||||
const result = await parseFileToText(path)
|
||||
expect(result).toEqual({ ok: true, kind: 'image', mime: 'image/png' })
|
||||
})
|
||||
|
||||
it.each([
|
||||
['pic.jpg', 'image/jpeg'],
|
||||
['pic.jpeg', 'image/jpeg'],
|
||||
['pic.gif', 'image/gif'],
|
||||
['pic.webp', 'image/webp'],
|
||||
])('maps %s to mime %s', async (name, mime) => {
|
||||
const path = writeFixture(name, Buffer.from([0]))
|
||||
const result = await parseFileToText(path)
|
||||
expect(result.kind).toBe('image')
|
||||
expect(result.mime).toBe(mime)
|
||||
})
|
||||
|
||||
it('rejects unknown extensions as unsupported', async () => {
|
||||
const path = writeFixture('archive.zip', Buffer.from([0x50, 0x4b]))
|
||||
const result = await parseFileToText(path)
|
||||
expect(result.ok).toBe(false)
|
||||
expect(result.kind).toBe('unsupported')
|
||||
expect(result.error).toContain('.zip')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src", "tests"]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from 'vitest/config'
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
testTimeout: 20000,
|
||||
},
|
||||
})
|
||||
Reference in New Issue
Block a user