Extract file text
Turn PDF, DOCX, XLSX, PPTX, and text files into bounded, sanitized text, and feed it to knowledge ingestion.
@yolk-sdk/extractors turns file bytes your app already has into sanitized text with metadata.
It gives you one Effect service, FileExtractor, a Node implementation that parses PDF, DOCX,
XLSX, and PPTX in worker threads with size and time limits, and an adapter that plugs it into
knowledge ingestion. Uploads, auth, storage, and what you do
with the text stay in your app.
Install
pnpm add @yolk-sdk/extractors@canary effect@4.2.0With knowledge ingestion:
pnpm add @yolk-sdk/extractors@canary @yolk-sdk/knowledge@canary effect@4.2.0Only if you extract .xlsx files, add SheetJS from its CDN (not the npm xlsx package):
pnpm add https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgzRequires Node.js 22 or later. @yolk-sdk/extractors/node is server-only.
SheetJS (xlsx >=0.20.3) is an optional peer, loaded only when an XLSX file is extracted. The
npm xlsx package stops at 0.18.5, which has CVE-2023-30533 and CVE-2024-22363; fixed releases
are published only on cdn.sheetjs.com. Because the peer is optional, it never arrives
transitively: each host adds it directly. pnpm records the tarball URL and integrity hash in the
lockfile. Other formats never load SheetJS.
Subpaths
| Subpath | Runtime | Use for |
|---|---|---|
@yolk-sdk/extractors | runtime-portable | the FileExtractor service tag and FileExtractorApi type; types FileInput, ExtractedFile, ExtractedFileMetadata, ExtractedFileFormat, OfficeFileFormat, FileExtractorError; fileFormatFor, extractedFileFormats, isOfficeFileFormat; defaultFileExtractorLimits and the FileExtractorLimits schema; sanitizeExtractedText; errors and FileExtractionFailureReason; minimumSheetJsVersion, sheetJsInstallCommand |
@yolk-sdk/extractors/node | Node, server | FileExtractorLayer, makeFileExtractorLayer(options), defaultWorkerIsolation, normalizeOfficeArchive; types FileExtractorOptions, FileExtractorIsolation, WorkerIsolationOptions, OfficeArchiveLimits, SheetJsLoader; also re-exports FileExtractor and FileExtractorApi |
@yolk-sdk/extractors/knowledge | runtime-portable | FileKnowledgeExtractorLayer and makeFileKnowledgeExtractor: a @yolk-sdk/knowledge/extraction KnowledgeExtractor backed by the FileExtractor in context |
@yolk-sdk/extractors/node/extraction-worker | Node worker | the worker entry the Node layer starts; do not import it directly (see Next.js) |
The root and ./knowledge import no parsers and no Node built-ins, so code that only needs the
contract (for example a service that receives a FileExtractor from context) can run anywhere.
Extract a file
Create extract.mts (the .mts extension makes it an ES module, so top-level await works in
any project):
import { readFile } from 'node:fs/promises'
import { basename } from 'node:path'
import { Effect } from 'effect'
import { FileExtractor } from '@yolk-sdk/extractors'
import { FileExtractorLayer } from '@yolk-sdk/extractors/node'
const path = process.argv[2] ?? 'notes.txt'
const program = Effect.gen(function* () {
const extractor = yield* FileExtractor
const bytes = new Uint8Array(yield* Effect.promise(() => readFile(path)))
return yield* extractor.extract({ filename: basename(path), mediaType: '', bytes })
}).pipe(Effect.provide(FileExtractorLayer))
const extracted = await Effect.runPromise(program)
console.log(extracted.metadata)
console.log(extracted.content)Create a text file and run the script:
printf 'Quarterly notes\r\n\r\n\r\n\r\nRevenue grew.\r\n' > notes.txt
pnpm dlx tsx extract.mts notes.txtYou should see the metadata and the sanitized text (line endings normalized, repeated spaces and blank lines collapsed):
{ format: 'text', title: 'notes.txt' }
Quarterly notes
Revenue grew.Pass a .pdf, .docx, .pptx, or .xlsx path to parse it in a worker thread. A workbook with
one sheet named Q1 prints { format: 'xlsx', title: 'report.xlsx', sheetNames: [ 'Q1' ] }
followed by a # Q1 section of CSV rows.
In a server, bytes comes from your upload or storage layer. mediaType can be the upload's
media type or ''. The extractor copies the input before a parser reads it, so your buffer is
never detached.
Formats and output
The format comes from the filename extension (txt, md, markdown, csv, json, pdf,
docx, xlsx, pptx), then the media type, then any text/* media type as plain text.
fileFormatFor exposes the same rule. Anything else fails with UnsupportedFileFormatError.
| Format | Where it is read | Text | Metadata |
|---|---|---|---|
text, markdown, csv, json | calling thread | UTF-8 decoded | title = filename |
pdf | worker thread (unpdf) | text of all pages | PDF Title if set, pageCount |
docx | worker thread | raw text (mammoth) | title = filename |
xlsx | worker thread | one # <sheet> section per worksheet with CSV rows; external links text <url> | workbook title or filename, sheetNames |
pptx | worker thread | slide text by slide part number, then speaker notes | title = filename |
With the default isolation, only PDF, DOCX, XLSX, and PPTX are parsed in worker threads. Text
formats are only decoded and sanitized in the calling thread; no parser reads them. Chart sheets
appear in sheetNames but get no text section.
All text goes through sanitizeExtractedText: line endings are normalized, control characters
dropped, and runs of spaces, dots, and blank lines collapsed. An empty result fails with
FileExtractionError. XLSX cells show their cached values; formulas are never evaluated, so a
formula cell without a cached value is empty. See the
package README for the
full XLSX and Office archive rules.
Limits
makeFileExtractorLayer({ limits }) overrides any of defaultFileExtractorLimits (fragment):
FileExtractorLayer uses the defaults. Invalid values are a defect when the layer is built, not a
typed failure.
import { makeFileExtractorLayer } from '@yolk-sdk/extractors/node'
const FileExtractorLive = makeFileExtractorLayer({
limits: { maxInputBytes: 10 * 1024 * 1024, maxXlsxCellVisits: 50_000 }
})| Limit | Default | Bounds |
|---|---|---|
maxInputBytes | 50 MiB | input size, every format |
maxArchiveEntries | 10,000 | ZIP entries in DOCX, XLSX, PPTX |
maxExpandedBytes | 50 MiB | inflated bytes of an Office archive, counted while inflating |
maxXlsxSheets | 100 | worksheets |
maxXlsxCellVisits | 100,000 | cells inside every sheet's declared range, absent cells included |
maxXlsxTextCharacters | 512 Ki | XLSX text, annotations and the omission marker included; at least 62 |
maxXlsxHyperlinks | 10,000 | hyperlinks read per workbook; extra links are dropped from the text output |
Exceeding a limit fails the extraction with FileExtractionError. Hyperlinks that do not fit the
text budget or the hyperlink cap are the exception: the cell is written plain and the text ends
with one [Some hyperlinks omitted: …] marker.
Worker isolation
Each PDF, DOCX, XLSX, and PPTX extraction runs in a fresh Node worker_threads worker. Only the
extracted text and metadata come back. Pass an isolation object to change the defaults
(defaultWorkerIsolation) (fragment):
import { makeFileExtractorLayer } from '@yolk-sdk/extractors/node'
const FileExtractorLive = makeFileExtractorLayer({
isolation: { maxOldGenerationSizeMb: 512, timeoutMs: 60_000, maxConcurrentWorkers: 2 }
})isolation option | Default | Bounds |
|---|---|---|
maxOldGenerationSizeMb | 256 | V8 old-generation heap of each worker |
maxYoungGenerationSizeMb | 32 | V8 young-generation heap of each worker |
stackSizeMb | 4 | stack of each worker |
timeoutMs | 30,000 | wall-clock time per worker (a real timer, at most 2³¹−1 ms) |
maxConcurrentWorkers | 4 | this layer's share of the pool of 4 workers per JavaScript realm |
maxQueueWaitMs | the layer's timeoutMs | wait for a worker slot (at most 2³¹−1 ms), then fail with busy |
workerUrl | the package's own worker | the worker entry, for hosts that bundle or relocate the package |
- One pool per realm. Every layer in a JavaScript realm (the main thread, or each worker
thread that builds the layer) shares one pool of 4 workers, however often the layer is built.
maxConcurrentWorkers(1 to 4) can only lower a layer's share. Slots are handed out first come, first served. - What the worker bounds. V8 heap, stack, and running time. A worker that runs out of heap,
times out, cannot start, or exits without a result is terminated and the extraction fails with
a
reason. There is no fallback to parsing in-process. - What it does not bound. Process memory (RSS) and memory outside the V8 heap, such as Buffers, inflated archive parts, and PDF.js decoded data. Those are limited only by the input and expanded-size limits. Your platform's memory limit is the outer bound: four workers at the default heap add up to about 1 GB of V8 heap, so size the host for that plus your own load, or lower the limits.
isolation: 'none' parses in the calling thread, for runtimes without worker threads. It is
unsafe for untrusted input: a crafted file can exhaust the process heap or block the event loop.
It is also the only mode that accepts a loadSheetJs or loadMammoth function (for example
mammoth's browser build); passing one with worker isolation is a defect when the layer is built.
Errors and failure reasons
extract fails with one of three tagged errors (the FileExtractorError union):
| Error | When | Fields |
|---|---|---|
UnsupportedFileFormatError | neither the extension nor the media type maps to a supported format | filename, mediaType |
FileExtractionError | the file is unreadable, invalid, over a limit, or empty, or the worker stopped | message (safe to show users), format, reason, cause |
SheetJsUnavailableError | an XLSX file arrived but SheetJS is missing, not a SheetJS build, or older than 0.20.3 | reason (missing, invalid, outdated), installedVersion |
SheetJsUnavailableError is host misconfiguration, not a bad upload. Its message includes
sheetJsInstallCommand. Office archive failures (OfficeArchiveError) reach you as
FileExtractionError with the archive error as cause; OfficeArchiveError itself is only
returned by normalizeOfficeArchive.
FileExtractionError.reason (FileExtractionFailureReason) is set only when a worker was stopped
or never admitted:
reason | Meaning | Typical host response |
|---|---|---|
resource-limit | the worker ran out of its V8 heap | reject the file, or raise maxOldGenerationSizeMb if your memory allows |
timeout | the worker exceeded timeoutMs and was terminated | reject the file, or retry; it may time out again with the same limits |
worker-unavailable | the worker could not start (missing or unloadable file) | fix deployment: see Next.js and workerUrl |
worker-failed | the worker crashed, exited, or sent a malformed message | log and reject the file |
busy | no worker slot freed up within maxQueueWaitMs | retry later; no worker was started |
No reason means the extraction itself failed, usually because the file is unreadable, invalid,
too large, or empty.
Fragment, mapping errors to host responses inside the program above:
import { Effect } from 'effect'
const handled = program.pipe(
Effect.catchTags({
UnsupportedFileFormatError: error => Effect.fail(`Unsupported file: ${error.filename}`),
FileExtractionError: error =>
Effect.fail(error.reason === 'busy' ? 'Try again shortly' : error.message),
SheetJsUnavailableError: error => Effect.die(error) // host misconfiguration
})
)Feed knowledge ingestion
FileKnowledgeExtractorLayer provides KnowledgeExtractor from the FileExtractor in context.
Give it the Node layer and include the result in the layers you provide to
ingestKnowledgeDocument (fragment):
import { Layer } from 'effect'
import { FileKnowledgeExtractorLayer } from '@yolk-sdk/extractors/knowledge'
import { FileExtractorLayer } from '@yolk-sdk/extractors/node'
const KnowledgeExtractorLive = FileKnowledgeExtractorLayer.pipe(Layer.provide(FileExtractorLayer))- String
contentpasses through unchanged; blank text fails. - Bytes are extracted with the format chosen from the source name (
Filename or ref,Urlpath,Textlabel) and media type (LoadedKnowledgeSource.mediaType, then theFilesource's, thentext/plainforTextsources). - The extracted title becomes the document title.
format,pageCount, andsheetNamesmerge under the source's own metadata, so your keys win. - Failures become
KnowledgeExtractionErrorwith the original error ascause.
Use makeFileKnowledgeExtractor(extractor) when you already hold a FileExtractorApi value. See
Ingest knowledge for the rest of the pipeline.
Next.js
The Node layer starts its worker from the package's dist/node/extraction-worker.mjs, a
self-contained file whose only other import is the optional xlsx peer. Keep both packages
unbundled in server code:
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
serverExternalPackages: ['@yolk-sdk/extractors', 'xlsx']
}
export default nextConfigWith the package external, Next.js 16 (Turbopack) output file tracing includes the worker; this
was checked with an output: 'standalone' build. If a bundler moves the
Node module into a chunk of another name, there is no default worker: extraction fails closed with
reason: 'worker-unavailable' and starts nothing. Then copy
@yolk-sdk/extractors/node/extraction-worker somewhere with xlsx resolvable beside it and pass
its URL as isolation.workerUrl. If your tracer misses dist/node/extraction-worker.mjs, add it
(and xlsx) with outputFileTracingIncludes.
Host responsibilities
- Upload size, auth, and per-user quota policy; storage of the original files.
- Limits that fit your runtime's memory and the model context you feed the text to. The worker limits bound V8 heap and time, not the process.
- Installing SheetJS from the CDN when XLSX extraction is needed.
- Deciding what happens to the text: knowledge ingestion, attachments, or other use.
- Deployment config that keeps the worker file on disk (see Next.js).
Boundaries
- The package is domain-free: no upload, auth, storage, or product concepts.
@yolk-sdk/extractors/knowledgeis the only bridge to@yolk-sdk/knowledge; the knowledge package never imports extractors.