This is the full developer documentation for Doc-chunk
# Introduction
> What Doc-chunk is, the problems it solves, and when to use something else.
Doc-chunk is a TypeScript library that splits documents into chunks for retrieval-augmented generation (RAG). You pass it a PDF, an Office file, Markdown, or plain text, and it returns chunks with their text, the headings they belong to, and stable ids. Everything runs on your machine.
```ts
import { chunkDocument } from "docchunk";
const { chunks } = await chunkDocument({ path: "handbook.pdf" });
```
## The problem
[Section titled “The problem”](#the-problem)
A RAG system answers a question by finding the most relevant passages in your documents and passing them to a language model. Whole documents are too long to embed or to send to the model, so they are split into chunks first. The quality of those chunks decides what the search can find, and so what the model can answer.
Getting good chunks takes more work than it first appears.
**Each format needs its own parser.** PDFs, Word files, slides, and spreadsheets each need a different tool, and each tool returns text in a different shape. Some of the easiest options are hosted APIs, which means sending your documents to someone else’s server.
**Simple splitters ignore structure.** Cutting text every 1,000 characters splits sentences in half, separates table rows from their header, breaks code blocks, and joins the end of one section to the start of the next. A chunk like that is a poor match for any question.
**Chunks lose their context.** A chunk that says “Refunds take 5 business days” is much more useful when you know it came from *Returns policy > Refunds*. Most splitters drop the headings.
**Ids that change force a full re-index.** If chunk ids are random, or change whenever anything in the file changes, you have to embed every chunk again after a one-line edit. Embedding costs time and money.
**Different retrieval setups need different chunks.** Small chunks match questions precisely, and large chunks give the model enough context to answer. Many setups need both, linked to each other.
## What Doc-chunk does
[Section titled “What Doc-chunk does”](#what-doc-chunk-does)
Doc-chunk converts every supported format to Markdown, parses it once into blocks (headings, paragraphs, lists, tables, code), and splits it with the strategy you choose.
* **One function for every format.** PDF, Word, PowerPoint, Excel, OpenDocument, RTF, EPUB, CSV, Markdown, and plain text all go through `chunkDocument` and return the same result.
* **Splitting that follows the document’s structure.** The default strategy keeps paragraphs, lists, tables, and code blocks whole, and never puts two sections in one chunk. A table that is too large is split by rows, with the header repeated in each piece.
* **Heading paths.** Every chunk lists the headings above it, such as `["Returns policy", "Refunds"]`, so you can store them as metadata or add them to the text before embedding.
* **Stable ids.** The same document and options always give the same chunk ids, on Node.js and on Bun. Each chunk also has a hash of its text, so you can tell which chunks changed and re-embed only those.
* **11 strategies.** From fixed-size cuts to sentence windows and parent-child chunks, all through the same function and with the same output.
* **Fully local.** No server, no API key, no network requests, and no telemetry.
PDFs and Office files are converted by [anydoc](https://github.com/firecrawl/anydoc), which runs locally. Markdown and text files are read as they are.
## When to use something else
[Section titled “When to use something else”](#when-to-use-something-else)
Doc-chunk is not a good fit in these cases:
* **Scanned documents.** Doc-chunk does not do OCR. A PDF without a text layer returns no chunks and a `NO_TEXT_LAYER` warning. Run OCR first, then pass the text to Doc-chunk.
* **Sizes in tokens.** Sizes are counted in characters. If a chunk must never go over your embedding model’s token limit, leave some margin (see [Sizes are in characters](../how-it-works/#sizes-are-in-characters)) or count tokens after chunking.
* **Browsers, Deno, and edge runtimes.** Doc-chunk runs on Node.js 22.12 or later, and on Bun.
* **HTML pages.** HTML is not a supported input. Convert pages to Markdown first.
* **Semantic chunking.** Doc-chunk splits by structure and size. It does not use embeddings to find topic changes, and it never calls a model.
The full list is on the [Limitations](../limitations/) page.
## Next steps
[Section titled “Next steps”](#next-steps)
* [Quickstart](../quickstart/): install Doc-chunk and chunk your first document.
* [How it works](../how-it-works/): the steps from file to chunks, and the ideas the rest of the docs rely on.
# Quickstart
> Install Doc-chunk and turn your first document into chunks in a few minutes.
This page takes you from installing Doc-chunk to reading your first chunks.
## Requirements
[Section titled “Requirements”](#requirements)
* Node.js 22.12 or later, or Bun 1.x.
* An ES module or CommonJS project. Both work.
## Install
[Section titled “Install”](#install)
* npm
```sh
npm install docchunk
```
* pnpm
```sh
pnpm add docchunk
```
* yarn
```sh
yarn add docchunk
```
* bun
```sh
bun add docchunk
```
TypeScript types are included. You don’t need a separate `@types` package.
## Chunk a file
[Section titled “Chunk a file”](#chunk-a-file)
Pass a file path to `chunkDocument`:
index.ts
```ts
import { chunkDocument } from "docchunk";
const { chunks } = await chunkDocument({ path: "handbook.pdf" });
console.log(chunks);
```
`chunkDocument` reads the file, detects its format, converts it to Markdown, and splits it with the default strategy, `structure`. Besides `chunks`, the result has three more fields:
| Field | Contents |
| ---------- | ------------------------------------------------------------------------------------ |
| `document` | The document’s id, format, and the Markdown the chunks were cut from. |
| `stats` | The number of chunks, their smallest, largest, and average size, and the time taken. |
| `warnings` | Problems that didn’t stop chunking, such as a scanned PDF with no text. |
The same call works for `.docx`, `.pptx`, `.xlsx`, `.md`, `.txt`, and the other [supported formats](../reference/formats/).
In a CommonJS project, load the library with `require`. Everything else is the same.
```js
const { chunkDocument } = require("docchunk");
```
## Chunk Markdown from a string
[Section titled “Chunk Markdown from a string”](#chunk-markdown-from-a-string)
If your text is already in memory, pass it as `content` with its `format`, either `"markdown"` or `"text"`:
index.ts
```ts
import { chunkDocument } from "docchunk";
const markdown = `# Returns policy
You can return most items within 30 days of delivery.
## Start a return
Sign in, open **Orders**, and choose the item you want to return.
## Refunds
We refund the original payment method within 5 business days.`;
const { chunks } = await chunkDocument({ content: markdown, format: "markdown" });
for (const chunk of chunks) {
console.log(chunk.headingPath.join(" > "));
console.log(chunk.text);
console.log("---");
}
```
Output:
```txt
Returns policy
# Returns policy
You can return most items within 30 days of delivery.
---
Returns policy > Start a return
## Start a return
Sign in, open **Orders**, and choose the item you want to return.
---
Returns policy > Refunds
## Refunds
We refund the original payment method within 5 business days.
---
```
Each section became its own chunk. The `structure` strategy never puts two sections in one chunk, even when they would fit, so a chunk is always about one topic.
## Read a chunk
[Section titled “Read a chunk”](#read-a-chunk)
Here is the second chunk from the example above, printed with `console.log(JSON.stringify(chunks[1], null, 2))`:
```json
{
"id": "cf2dc8b73713ce568741",
"text": "## Start a return\n\nSign in, open **Orders**, and choose the item you want to return.",
"index": 1,
"start": 73,
"end": 157,
"charCount": 84,
"headingPath": [
"Returns policy",
"Start a return"
],
"blockTypes": [
"heading",
"paragraph"
],
"contentHash": "264d608f5e01b4272d5a",
"metadata": {}
}
```
The fields you’ll use first:
* `text` is what you embed and send to the model.
* `headingPath` is the list of headings above the chunk. Store it with the embedding, or add it to the text with the [`headingPrefix`](../guides/chunk-document/#options-every-strategy-accepts) option.
* `id` is stable: the same document and options always give the same id. Use it as the key in your vector database.
* `contentHash` is a hash of `text`. When you re-index, compare it with the stored hash to find the chunks that changed.
`start` and `end` are positions in `document.markdown`, the Markdown the chunk was cut from. [Chunk a document](../guides/chunk-document/#the-result) describes every field.
## Choose a strategy
[Section titled “Choose a strategy”](#choose-a-strategy)
The default strategy, `structure`, works well for most documents. To use another one, pass `strategy` in the options:
```ts
import { chunkDocument } from "docchunk";
const { chunks } = await chunkDocument(
{ path: "manual.docx" },
{ strategy: "heading" },
);
```
Some common choices:
| If you want | Use |
| -------------------------------------------------------------------- | ------------------------- |
| Good general-purpose chunks | `structure` (the default) |
| One chunk per section of a manual or guide | `heading` |
| Small chunks for search, each linked to a larger chunk for the model | `parent-child` |
| One sentence per chunk, with the sentences around it as context | `sentence-window` |
See [Strategies](../strategies/) for all 11, and help choosing.
### Set the chunk size
[Section titled “Set the chunk size”](#set-the-chunk-size)
Sizes are in characters, not tokens. The default `size` for `structure` is 1,500 characters:
```ts
const { chunks } = await chunkDocument({ path: "handbook.pdf" }, { size: 1000 });
```
For English prose, a limit of about three characters per token keeps chunks within your embedding model’s limit. For example, 1,500 characters for a model that accepts 512 tokens. Use less for code and for languages that don’t use the Latin alphabet, which need more tokens per character.
## TypeScript: `chunks[0]` may be undefined
[Section titled “TypeScript: chunks\[0\] may be undefined”](#typescript-chunks0-may-be-undefined)
If your `tsconfig.json` enables `noUncheckedIndexedAccess`, TypeScript types `chunks[0]` as `Chunk | undefined`, because the array can be empty. For example, a document with no text returns no chunks.
Loop over the chunks, or check the value before you use it:
```ts
for (const chunk of chunks) {
console.log(chunk.text);
}
const first = chunks[0];
if (first !== undefined) {
console.log(first.text);
}
```
## Next steps
[Section titled “Next steps”](#next-steps)
* [How it works](../how-it-works/) explains heading paths, sizes, and ids.
* [Chunk a document](../guides/chunk-document/) covers sources, formats, options, warnings, and errors.
* [Chunk many documents](../guides/chunk-documents/) shows how to process a folder of files.
# How it works
> The steps from file to chunks, and the ideas the other pages rely on.
This page explains what happens when you call `chunkDocument`, and the ideas the rest of the documentation refers to: sections, heading paths, sizes, and ids.
## From file to chunks
[Section titled “From file to chunks”](#from-file-to-chunks)
```txt
source → detect format → convert to Markdown → normalize → parse into blocks → split → finalize
```
1. **Read the source.** A source is a file path, bytes in memory, or a string. See [Chunk a document](../guides/chunk-document/#sources).
2. **Detect the format.** Doc-chunk uses the `format` you pass, if any. Otherwise it looks at the file name for `.md`, `.markdown`, `.txt`, and `.csv`, and then at the file’s content.
3. **Convert to Markdown.** PDF, Word, PowerPoint, Excel, OpenDocument, RTF, EPUB, and CSV files are converted to Markdown by [anydoc](https://github.com/firecrawl/anydoc), on your machine. Markdown and plain text are used as they are.
4. **Normalize.** Windows (`\r\n`) and old Mac (`\r`) line endings become `\n`, and a byte order mark at the start is removed. The result is returned as `document.markdown`.
5. **Parse into blocks.** The Markdown is parsed once into a list of top-level blocks: headings, paragraphs, lists, tables, code blocks, block quotes, and a few rarer kinds. Plain text is not parsed as Markdown. It is split into paragraphs at blank lines, and characters like `#` and `*` stay as text.
6. **Split.** The [strategy](../strategies/) chooses where each chunk starts and ends.
7. **Finalize.** Doc-chunk builds each chunk’s text, id, and content hash, then the stats and warnings.
Parsing happens once per document. Strategies work on the parsed blocks and their positions, so they never parse the text again.
## Positions refer to `document.markdown`
[Section titled “Positions refer to document.markdown”](#positions-refer-to-documentmarkdown)
Each chunk’s `start` and `end` are character positions in `document.markdown`, not in the original file. For a PDF or Word file, `document.markdown` is the converted Markdown.
For most chunks, `text` is exactly `document.markdown.slice(start, end)`. There are two exceptions:
* With the `headingPrefix` option, the heading path is added before the text.
* When a large table or code block is split, each piece repeats the table header or the code fence, which lie outside its range. See [Blocks larger than the size limit](#blocks-larger-than-the-size-limit).
## Sections and heading paths
[Section titled “Sections and heading paths”](#sections-and-heading-paths)
Headings divide a document into sections. The `headingLevel` option sets which headings start a new section: headings at that level or higher do, and deeper headings stay inside the section they are in. The default is 3, so `#`, `##`, and `###` start sections, and `####` to `######` do not.
The `structure` strategy never puts two sections in one chunk. Take this document, chunked with the default options:
```ts
import { chunkDocument } from "docchunk";
const markdown = `# Guide
Intro text.
## Setup
Install it.
### Linux
Use the package manager.
#### Ubuntu
Run apt.`;
const { chunks } = await chunkDocument({ content: markdown, format: "markdown" });
for (const chunk of chunks) {
console.log(chunk.headingPath);
}
```
It gives three chunks, one per section. The `####` heading doesn’t start a section, so *Ubuntu* stays in the *Linux* chunk:
```txt
[ 'Guide' ]
[ 'Guide', 'Setup' ]
[ 'Guide', 'Setup', 'Linux' ]
```
With `{ headingLevel: 2 }`, the `###` heading no longer starts a section either, so *Linux* and *Ubuntu* join the *Setup* chunk:
```txt
[ 'Guide' ]
[ 'Guide', 'Setup' ]
```
Each list is a chunk’s `headingPath`: the headings above the start of the chunk, outermost first. Heading text is plain text, with Markdown formatting such as `**` or links removed. Plain text documents have no headings, so their chunks have an empty `headingPath`.
### Adding the heading path to the text
[Section titled “Adding the heading path to the text”](#adding-the-heading-path-to-the-text)
An embedding of “Install it.” carries no hint that it’s about setting up a guide. The `headingPrefix` option adds the heading path to the start of each chunk’s text, joined with `>` and followed by a blank line. With the same document:
```ts
const { chunks } = await chunkDocument(
{ content: markdown, format: "markdown" },
{ headingPrefix: true },
);
console.log(chunks[1]?.text);
```
```txt
Guide > Setup
## Setup
Install it.
```
The prefix counts toward the size limit. Doc-chunk reserves room for the longest heading path in the document, so prefixed chunks still fit within `size`.
## Sizes are in characters
[Section titled “Sizes are in characters”](#sizes-are-in-characters)
Every size option (`size`, `minSize`, `overlapChars`, `parentSize`, `childSize`, and the others) is a number of characters. A chunk’s size is the length of its `text`, including:
* Markdown syntax, such as `## `, `**`, table pipes, and code fences.
* Text repeated from the previous chunk, when you use `overlapChars`.
* The heading path, when you use `headingPrefix`.
Doc-chunk doesn’t count tokens. For English prose, a size of about three times your embedding model’s token limit keeps chunks under it: 1,500 characters for a model that accepts 512 tokens. Code and languages that don’t use the Latin alphabet use more tokens per character, so use a smaller size for them.
Some strategies have no size limit by default: `heading` gives one chunk per section, and `paragraph` and `sentence` give one chunk per paragraph or sentence. If one of those chunks is longer than 8,000 characters, the result includes a `LARGE_CHUNK` warning. Set `size` to split long sections.
## Blocks larger than the size limit
[Section titled “Blocks larger than the size limit”](#blocks-larger-than-the-size-limit)
The `structure` strategy packs whole blocks into chunks. When a single block is larger than `size`, it is split along its own structure:
| Block | Split by |
| ------------------------- | -------------------------------------------------------- |
| Table | Rows. Each piece repeats the header row. |
| List | Items. |
| Code block | Lines. Each piece repeats the opening and closing fence. |
| Paragraph and other prose | Sentences, then words. |
For example, this table is 142 characters long, and `size` is 100:
```ts
import { chunkDocument } from "docchunk";
const table = `| Plan | Price | Storage |
| --- | --- | --- |
| Free | $0 | 5 GB |
| Personal | $4 | 100 GB |
| Team | $12 | 1 TB |
| Business | $25 | 5 TB |`;
const { chunks } = await chunkDocument(
{ content: table, format: "markdown" },
{ size: 100, minSize: 50 },
);
for (const chunk of chunks) {
console.log(chunk.text);
console.log("---");
}
```
It is split into two chunks, and each one is a complete table with the header:
```txt
| Plan | Price | Storage |
| --- | --- | --- |
| Free | $0 | 5 GB |
| Personal | $4 | 100 GB |
---
| Plan | Price | Storage |
| --- | --- | --- |
| Team | $12 | 1 TB |
| Business | $25 | 5 TB |
---
```
If a single row, item, line, or word is still larger than `size`, Doc-chunk cuts it at the size limit and adds an `OVERSIZED_BLOCK` warning that points to the chunk.
The `heading`, `paragraph`, `sentence`, `parent-child`, and `hierarchical` strategies split large blocks the same way when they have a size limit. The `fixed`, `fixed-overlap`, and `sliding-window` strategies ignore structure and cut the text at the size limit.
## Sentences
[Section titled “Sentences”](#sentences)
The `sentence` and `sentence-window` strategies, and overlap in `structure`, `paragraph`, and `sentence`, work with whole sentences. Doc-chunk finds sentence boundaries with the JavaScript `Intl.Segmenter` API. A table or a code block counts as a single sentence, so it is never cut in the middle.
`Intl.Segmenter` sometimes ends a sentence after an abbreviation such as “Dr.” or “e.g.”.
## Ids and content hashes
[Section titled “Ids and content hashes”](#ids-and-content-hashes)
Each chunk has two hashes:
* `id` identifies the chunk. It is built from the document’s id, the options that affect chunking, the chunk’s `start` and `end`, and its level. The `metadata` and `signal` options don’t affect it.
* `contentHash` is a hash of the chunk’s `text` alone.
Both are the first 20 hexadecimal characters of a SHA-256 hash. They don’t depend on the runtime or the machine: the same document and options give the same values on Node.js and on Bun.
The document’s id is a hash of `document.markdown`, so any edit to the document changes every chunk `id`. If you pass your own `documentId`, such as a file path or a database key, a chunk keeps its id as long as its `start` and `end` don’t change. An edit changes the positions of the chunks after it, so their ids change too. `contentHash` only changes when the chunk’s text changes, wherever it is in the document.
| After you change | `id` | `contentHash` |
| ---------------------------------- | --------------------------------------- | ------------------------------------------ |
| Nothing | Same | Same |
| Only `metadata` | Same | Same |
| The strategy or a size option | Changes | Changes if the text changes |
| The document, without `documentId` | Changes for every chunk | Changes only for chunks whose text changed |
| The document, with `documentId` | Changes for chunks whose position moved | Changes only for chunks whose text changed |
To re-index a document, compare each chunk’s `contentHash` with the one you stored, and embed only the chunks that differ. [Chunk a document](../guides/chunk-document/#ids-and-re-indexing) shows a full example.
## Levels, parents, and children
[Section titled “Levels, parents, and children”](#levels-parents-and-children)
Most strategies return a flat list of chunks that don’t overlap. Two strategies return chunks at several sizes, where a large chunk contains smaller ones:
* `parent-child` returns two levels: large parent chunks, and small child chunks inside them.
* `hierarchical` returns as many levels as you ask for, or one level per heading depth.
These chunks have three more fields:
| Field | Meaning |
| ---------- | ---------------------------------------------------------------------- |
| `level` | `0` for the largest chunks, `1` for the chunks inside them, and so on. |
| `parentId` | The `id` of the chunk that contains this one. Not set at level 0. |
| `childIds` | The `id`s of the chunks this one contains. |
All levels are returned in one list, sorted by position in the document and then by level, so a parent always comes before the chunks inside it. A common pattern is to embed only the children, and send a matching child’s parent to the model:
```ts
import { chunkDocument } from "docchunk";
const { chunks } = await chunkDocument(
{ path: "policy.pdf" },
{ strategy: "parent-child" },
);
const children = chunks.filter((chunk) => chunk.level === 1);
const chunksById = new Map(chunks.map((chunk) => [chunk.id, chunk]));
// After a search returns a child chunk:
// const parent = chunksById.get(child.parentId);
```
To work with the chunks as a tree instead, pass them to [`buildChunkTree`](../reference/build-chunk-tree/).
# Chunk a document
> Chunk one document from a file path, bytes, or a string, and read the result.
`chunkDocument` turns one document into chunks. This guide covers where the document can come from, which formats are supported, what the result contains, and how to handle warnings and errors.
```ts
import { chunkDocument } from "docchunk";
const result = await chunkDocument(source, options);
```
The first argument is the [source](#sources). The second is optional: the [strategy](#choosing-a-strategy) and its options, plus the [options every strategy accepts](#options-every-strategy-accepts). The function returns a promise of the [result](#the-result).
## Sources
[Section titled “Sources”](#sources)
A source is one of three objects:
| Source | Use it for |
| ------------------------------- | ----------------------------------------------------------------------------------- |
| `{ path }` | A file on disk. |
| `{ bytes, filename?, format? }` | A file you already have in memory, such as an upload or a file from object storage. |
| `{ content, format }` | Markdown or plain text in a string. |
### A file path
[Section titled “A file path”](#a-file-path)
```ts
const result = await chunkDocument({ path: "docs/handbook.pdf" });
```
A relative path is resolved against the current working directory. If the file doesn’t exist, or the path is a folder, `chunkDocument` throws a `DocchunkError` with the code `FILE_NOT_FOUND`.
`result.document.sourcePath` is set to the path you passed.
### Bytes
[Section titled “Bytes”](#bytes)
Pass the file’s bytes as a `Uint8Array`. A Node.js `Buffer` is a `Uint8Array`, so the result of `readFile` works as it is:
```ts
import { readFile } from "node:fs/promises";
import { chunkDocument } from "docchunk";
const bytes = await readFile("notes.md");
const result = await chunkDocument({ bytes, filename: "notes.md" });
console.log(result.document.sourceFormat);
console.log(result.chunks[0]?.text);
```
```txt
markdown
# Notes
Meeting moved to Friday.
```
PDF and Office files are recognized from their content, so `filename` and `format` are optional for them. Markdown, plain text, and CSV have no signature in their content: pass a `filename` with the right extension, or a `format`. Without either, `chunkDocument` throws an `UNSUPPORTED_FORMAT` error.
```ts
const result = await chunkDocument({ bytes, format: "csv" });
```
### A string
[Section titled “A string”](#a-string)
When the text is already in memory, pass it as `content`, with `format` set to `"markdown"` or `"text"`:
```ts
const result = await chunkDocument({ content: markdown, format: "markdown" });
```
The format changes how the text is read. Markdown is parsed into headings, lists, tables, and other blocks. Plain text is split into paragraphs at blank lines, and nothing else is treated as syntax:
```ts
import { chunkDocument } from "docchunk";
const content = "# Not a heading\n\n* not a list item";
const asMarkdown = await chunkDocument({ content, format: "markdown" });
const asText = await chunkDocument({ content, format: "text" });
console.log(asMarkdown.chunks.map((chunk) => chunk.blockTypes));
console.log(asText.chunks.map((chunk) => chunk.blockTypes));
```
```txt
[ [ 'heading', 'list' ] ]
[ [ 'paragraph' ] ]
```
Use `"text"` for text that isn’t Markdown, such as logs or transcripts, so that a line starting with `#` doesn’t become a heading.
## Formats
[Section titled “Formats”](#formats)
| Format | Extensions | Notes |
| ------------ | ---------------------- | ---------------------------------------------------- |
| PDF | `.pdf` | Text-based PDFs only. Images are ignored. |
| Word | `.docx`, `.doc` | |
| PowerPoint | `.pptx`, `.ppt` | |
| Excel | `.xlsx`, `.xls` | Each sheet becomes a Markdown table. |
| OpenDocument | `.odt`, `.ods`, `.odp` | |
| RTF | `.rtf` | |
| EPUB | `.epub` | |
| CSV | `.csv` | Needs a `.csv` file name or `format: "csv"`. |
| Markdown | `.md`, `.markdown` | Not converted. |
| Plain text | `.txt` | Not converted. Split into paragraphs at blank lines. |
### How the format is detected
[Section titled “How the format is detected”](#how-the-format-is-detected)
Doc-chunk uses the first of these that gives an answer:
1. The `format` in the source, if you passed one.
2. A `.md`, `.markdown`, `.txt`, or `.csv` file name.
3. The file’s content. PDF, Office, OpenDocument, EPUB, and RTF files each start with a recognizable signature.
4. Any other file extension.
If none of them works, `chunkDocument` throws an `UNSUPPORTED_FORMAT` error that asks you to pass `format`.
### Conversion
[Section titled “Conversion”](#conversion)
Every format except Markdown and plain text is converted to Markdown by [anydoc](https://github.com/firecrawl/anydoc) before chunking. anydoc runs on your machine, with native binaries for macOS, Linux, and Windows x64. It’s only loaded when a document needs converting, so projects that chunk only Markdown and text never load it.
The converted Markdown is returned as `document.markdown`, and chunk positions refer to it. For example, a CSV file becomes a Markdown table:
```ts
import { chunkDocument } from "docchunk";
const bytes = new TextEncoder().encode("a,b\n1,2\n");
const result = await chunkDocument({ bytes, format: "csv" });
console.log(result.document.markdown);
```
```md
| a | b |
| --- | --- |
| 1 | 2 |
```
### Scanned PDFs
[Section titled “Scanned PDFs”](#scanned-pdfs)
Doc-chunk doesn’t do OCR. PDFs with text work as usual, and images on their pages are ignored. But if any page has no text layer, because it’s scanned or is only an image, the whole PDF gives no chunks, and the result has a `NO_TEXT_LAYER` warning that lists the pages. The same happens when a page is mostly covered by an image, or when a PDF has fewer than 100 characters of text in total. If you need to index scanned documents, run them through an OCR tool first and pass the text to Doc-chunk as `content`.
## Choosing a strategy
[Section titled “Choosing a strategy”](#choosing-a-strategy)
Without options, `chunkDocument` uses the `structure` strategy, which works well for most documents. To choose another, pass `strategy` and that strategy’s options:
```ts
const result = await chunkDocument(
{ path: "manual.docx" },
{ strategy: "heading", headingLevel: 2 },
);
```
Each strategy accepts its own options. In TypeScript, once you set `strategy`, the editor suggests only that strategy’s options and flags any others. At runtime, an option the strategy doesn’t accept throws an `INVALID_OPTIONS` error.
[Strategies](../../strategies/) describes all 11 and helps you choose.
## The result
[Section titled “The result”](#the-result)
`chunkDocument` returns an object with four fields:
```ts
import { chunkDocument } from "docchunk";
const markdown = `# Returns policy
You can return most items within 30 days of delivery.
## Refunds
We refund the original payment method within 5 business days.`;
const { document, stats, warnings } = await chunkDocument({ content: markdown, format: "markdown" });
console.log(document.id, document.sourceFormat, document.charCount);
console.log(stats.count, stats.minChars, stats.maxChars, stats.avgChars);
console.log(warnings);
```
```txt
0a124c7110480079c570 markdown 146
2 71 73 72
[]
```
### `chunks`
[Section titled “chunks”](#chunks)
The chunks, in document order. Each chunk has these fields:
| Field | Type | Description |
| ------------- | ---------- | ------------------------------------------------------------------------------------------------------------- |
| `id` | `string` | Stable id. See [Ids and re-indexing](#ids-and-re-indexing). |
| `text` | `string` | The chunk’s text, in Markdown. |
| `index` | `number` | Position in the `chunks` array, starting at 0. |
| `start` | `number` | Start position in `document.markdown`, in characters. |
| `end` | `number` | End position in `document.markdown`, in characters. Not included in the chunk. |
| `charCount` | `number` | Length of `text` in characters. |
| `headingPath` | `string[]` | The headings above the start of the chunk, outermost first. |
| `blockTypes` | `string[]` | The kinds of blocks the chunk contains, such as `"heading"`, `"paragraph"`, `"list"`, `"table"`, or `"code"`. |
| `contentHash` | `string` | A hash of `text`. |
| `metadata` | `object` | A copy of the `metadata` option. `{}` when you don’t pass one. |
| `contextText` | `string` | The sentences around the chunk. Set by `sentence-window` only. |
| `level` | `number` | Nesting level, `0` for the largest chunks. Set by `parent-child` and `hierarchical` only. |
| `parentId` | `string` | The `id` of the chunk that contains this one. Set by `parent-child` and `hierarchical` only. |
| `childIds` | `string[]` | The `id`s of the chunks inside this one. Set by `parent-child` and `hierarchical` only. |
For most chunks, `text` is exactly `document.markdown.slice(start, end)`. It differs when you use `headingPrefix`, and for pieces of a table or code block that was too large for one chunk, which repeat the table header or code fence. See [How it works](../../how-it-works/#positions-refer-to-documentmarkdown).
### `document`
[Section titled “document”](#document)
| Field | Type | Description |
| -------------- | -------- | --------------------------------------------------------------------------------------------------- |
| `id` | `string` | The `documentId` option, or a hash of `markdown`. |
| `markdown` | `string` | The document as Markdown, after conversion and normalization. Chunk positions refer to this string. |
| `sourceFormat` | `string` | The format of the original document, such as `"pdf"` or `"docx"`. |
| `sourcePath` | `string` | The file path, when the source was a path. |
| `charCount` | `number` | Length of `markdown` in characters. |
### `stats`
[Section titled “stats”](#stats)
| Field | Type | Description |
| ------------ | -------- | -------------------------------------------------- |
| `count` | `number` | Number of chunks. |
| `minChars` | `number` | Characters in the smallest chunk. |
| `maxChars` | `number` | Characters in the largest chunk. |
| `avgChars` | `number` | Average characters per chunk, rounded. |
| `durationMs` | `number` | Time taken, in milliseconds, including conversion. |
When there are no chunks, all the size fields are `0`.
### `warnings`
[Section titled “warnings”](#warnings)
Problems that didn’t stop chunking. See [Warnings](#warnings).
## Options every strategy accepts
[Section titled “Options every strategy accepts”](#options-every-strategy-accepts)
These options work with every strategy.
### `metadata`
[Section titled “metadata”](#metadata)
An object copied onto every chunk. Use it for anything you want to store alongside the embedding, such as the source file or an access group:
```ts
import { chunkDocument } from "docchunk";
const { chunks } = await chunkDocument(
{ content: "# Leave\n\nYou get 25 days of paid leave each year.", format: "markdown" },
{ metadata: { source: "hr-handbook", team: "people" } },
);
console.log(chunks[0]?.metadata);
```
```txt
{ source: 'hr-handbook', team: 'people' }
```
Changing `metadata` doesn’t change chunk ids.
### `documentId`
[Section titled “documentId”](#documentid)
A string used as the document’s id, instead of a hash of its content. It becomes `document.id` and is part of every chunk id. Use a value that identifies the document in your system and doesn’t change when the document is edited, such as its path or database key:
```ts
const result = await chunkDocument(
{ path: "policies/returns.md" },
{ documentId: "policies/returns.md" },
);
```
See [Ids and re-indexing](#ids-and-re-indexing) for when you need it.
### `headingPrefix`
[Section titled “headingPrefix”](#headingprefix)
When `true`, each chunk’s text starts with its heading path, such as `Returns policy > Refunds`, followed by a blank line. The default is `false`. The prefix counts toward the size limit. [How it works](../../how-it-works/#adding-the-heading-path-to-the-text) shows an example.
### `signal`
[Section titled “signal”](#signal)
An `AbortSignal` that stops chunking. When the signal is aborted, `chunkDocument` throws a `DocchunkError` with the code `ABORTED`. To give up on a slow document after 30 seconds:
```ts
import { chunkDocument, DocchunkError } from "docchunk";
try {
const result = await chunkDocument(
{ path: "large-report.pdf" },
{ signal: AbortSignal.timeout(30_000) },
);
} catch (error) {
if (error instanceof DocchunkError && error.code === "ABORTED") {
console.log("Chunking took too long");
}
}
```
Doc-chunk checks the signal between steps: before reading the source, after conversion, and after splitting. A step that has already started, such as converting a PDF, finishes before the abort takes effect.
## Ids and re-indexing
[Section titled “Ids and re-indexing”](#ids-and-re-indexing)
Every chunk has an `id` and a `contentHash`:
* `id` is built from the document’s id, the options that affect chunking, and the chunk’s position. The same document with the same options always gives the same ids.
* `contentHash` depends only on the chunk’s `text`.
Use `contentHash` to find out which chunks changed since you last indexed a document, and embed only those:
```ts
import { chunkDocument } from "docchunk";
const version1 = `# Returns policy
You can return most items within 30 days of delivery.
## Start a return
Sign in, open **Orders**, and choose the item you want to return.
## Refunds
We refund the original payment method within 5 business days.`;
// The same document after an edit to the Refunds section.
const version2 = version1.replace("5 business days", "3 business days");
const options = { documentId: "returns-policy" };
const before = await chunkDocument(
{ content: version1, format: "markdown" },
options,
);
const after = await chunkDocument(
{ content: version2, format: "markdown" },
options,
);
const storedHashes = new Set(before.chunks.map((chunk) => chunk.contentHash));
const changed = after.chunks.filter((chunk) => !storedHashes.has(chunk.contentHash));
console.log(`${changed.length} of ${after.chunks.length} chunks changed`);
for (const chunk of changed) {
console.log(chunk.headingPath);
}
```
```txt
1 of 3 chunks changed
[ 'Returns policy', 'Refunds' ]
```
In a real pipeline, `storedHashes` comes from your vector database. A typical update looks like this:
1. Chunk the new version of the document.
2. Embed the chunks whose `contentHash` isn’t stored yet. Reuse the stored embeddings for the others.
3. Replace the document’s old rows with the new chunks.
### When to pass `documentId`
[Section titled “When to pass documentId”](#when-to-pass-documentid)
Without `documentId`, the document’s id is a hash of its content. That has two effects:
* Any edit to the document changes the id of every chunk. `contentHash` still tells you which chunks really changed.
* Two files with the same content get the same chunk ids. If you store both, their rows collide.
Pass a `documentId` that is unique to each document, such as its path, when you store chunks from many documents in one place or want ids that survive edits. With a fixed `documentId`, a chunk keeps its id as long as its position in the document doesn’t change.
## Warnings
[Section titled “Warnings”](#warnings-1)
Warnings describe problems that didn’t stop chunking. Each one has a `code`, a `message`, and, when it’s about one chunk, a `chunkIndex`.
| Code | When | What to do |
| ----------------- | ------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| `EMPTY_DOCUMENT` | The document has no text. There are no chunks. | Check the source. It may be empty, or contain only images. |
| `NO_TEXT_LAYER` | The PDF has no text layer, usually because it’s scanned. There are no chunks. | Run OCR first, then chunk the text. |
| `OVERSIZED_BLOCK` | A table row, list item, code line, or word was longer than `size`, and was cut at the size limit. | Usually nothing. Raise `size` if the cut pieces are too small to be useful. |
| `LARGE_CHUNK` | A strategy with no size limit produced a chunk of more than 8,000 characters. | Set `size` to split large sections or paragraphs. |
Warnings are returned, not logged. Check them after each call:
```ts
import { chunkDocument } from "docchunk";
const url = "https://example.com/" + "a".repeat(120);
const { warnings } = await chunkDocument(
{ content: `See ${url} for details.`, format: "markdown" },
{ size: 100, minSize: 50 },
);
for (const warning of warnings) {
console.log(warning.code, warning.chunkIndex, warning.message);
}
```
```txt
OVERSIZED_BLOCK 1 Chunk 1 is a hard cut of a row, item, line, or word longer than size.
OVERSIZED_BLOCK 2 Chunk 2 is a hard cut of a row, item, line, or word longer than size.
```
The URL is one 140-character word, longer than the 100-character `size`, so it was cut into two chunks.
## Errors
[Section titled “Errors”](#errors)
When `chunkDocument` can’t produce a result, it throws a `DocchunkError`. The error’s `code` tells you what went wrong, and `message` gives the details:
| Code | Thrown when |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `INVALID_OPTIONS` | An option has the wrong type or value, an option isn’t accepted by the chosen strategy, or the source isn’t one of the three shapes. |
| `UNSUPPORTED_FORMAT` | The format isn’t supported, or can’t be detected. |
| `FILE_NOT_FOUND` | The file at `path` doesn’t exist, is a folder, or can’t be read. |
| `CONVERSION_FAILED` | anydoc couldn’t convert the file, for example because it’s damaged, or because anydoc isn’t available on this platform. |
| `ABORTED` | The `signal` was aborted. |
Options are checked before the document is read, so an `INVALID_OPTIONS` error comes back immediately. The one exception is `headingPrefix`: if a document’s heading paths are so long that no text would fit within `size`, the error comes after the document is read.
```ts
import { chunkDocument, DocchunkError } from "docchunk";
try {
await chunkDocument({ path: "missing.pdf" });
} catch (error) {
if (error instanceof DocchunkError) {
console.log(error.code);
console.log(error.message);
}
}
```
```txt
FILE_NOT_FOUND
File not found: missing.pdf
```
Messages name the option or file at fault. Some examples:
```txt
Unknown option "windowSize" for strategy "structure".
Option "overlapChars" must be less than "size" (500), got 600.
The document's format could not be detected from its content or file name. Pass `format` to name it.
```
When an error has an underlying cause, such as the file system error for `FILE_NOT_FOUND` or anydoc’s error for `CONVERSION_FAILED`, it’s available as `error.cause`.
## Next steps
[Section titled “Next steps”](#next-steps)
* [Chunk many documents](../chunk-documents/): chunk a list of files with one call.
* [Strategies](../../strategies/): choose how documents are split.
# Chunk many documents
> Chunk a list of documents with shared options, a concurrency limit, and per-document errors.
`chunkDocuments` chunks a list of documents with the same options. It runs a few documents at a time, and a document that fails doesn’t stop the others.
```ts
import { chunkDocuments } from "docchunk";
const results = await chunkDocuments(sources, options);
```
The sources are the same objects [`chunkDocument`](../chunk-document/#sources) accepts, and the options are the same too, plus `concurrency`.
## Chunk a list of documents
[Section titled “Chunk a list of documents”](#chunk-a-list-of-documents)
```ts
import { chunkDocuments } from "docchunk";
const results = await chunkDocuments(
[
{ content: "# Leave\n\nYou get 25 days of paid leave.", format: "markdown" },
{ path: "missing.docx" },
{ content: "Office hours are 9 to 5.", format: "text" },
],
{ size: 1000 },
);
for (const item of results) {
if (item.ok) {
console.log("ok", item.result.chunks.length);
} else {
console.log(`source ${item.sourceIndex} failed: ${item.error.code}`);
}
}
```
```txt
ok 1
source 1 failed: FILE_NOT_FOUND
ok 1
```
## Read the results
[Section titled “Read the results”](#read-the-results)
`chunkDocuments` returns one item per source, in the same order as the sources, whatever order the documents finish in. Each item is one of two shapes:
| Shape | Meaning |
| ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `{ ok: true, result }` | The document was chunked. `result` is the same object [`chunkDocument`](../chunk-document/#the-result) returns. |
| `{ ok: false, error, sourceIndex }` | The document failed. `error` is a `DocchunkError`, and `sourceIndex` is the position of the source in the list you passed. |
Check `item.ok` before you read `result` or `error`. In TypeScript, the check also narrows the type, so `item.result` is only available after it.
A failed document doesn’t stop the batch. Every error has a `code`: if something unexpected goes wrong inside Doc-chunk, the error is wrapped in a `DocchunkError` with the code `CONVERSION_FAILED`, and the original error is in `error.cause`.
To know which file each result came from, keep your list of sources and use the item’s position. For path sources, `result.document.sourcePath` also holds the path.
## Options
[Section titled “Options”](#options)
The options apply to every document in the list. They’re checked once, before any document is read, so a wrong option throws immediately instead of failing every document:
```ts
await chunkDocuments(sources, { size: -1 });
// Throws DocchunkError INVALID_OPTIONS:
// Option "size" must be a positive integer, got -1.
```
`chunkDocuments` also throws, instead of returning items, when `sources` isn’t an array or when the batch is [cancelled](#cancel-a-batch). An empty array returns an empty array.
Two of the shared options need care in a batch:
* **`metadata`** is copied onto the chunks of every document. For values that differ per document, such as the file name, add them when you store the chunks.
* **`documentId`** would give every document the same id, so chunks at the same position in different documents would get the same chunk id. Don’t pass it to `chunkDocuments`. If you need your own id for each document, call `chunkDocument` for each one, as shown in [Documents that need different options](#documents-that-need-different-options).
## Concurrency
[Section titled “Concurrency”](#concurrency)
`concurrency` sets how many documents are chunked at the same time. The default is 4, and the value must be a positive whole number:
```ts
const results = await chunkDocuments(sources, { concurrency: 8 });
```
Reading files and converting PDFs and Office files happen off the main JavaScript thread, so several of them can run in parallel. Parsing and splitting the Markdown happen on the main thread, one document at a time. As a result:
* A higher `concurrency` can speed up batches of PDFs and Office files. On Node.js, conversions share libuv’s thread pool, which has 4 threads unless you set the `UV_THREADPOOL_SIZE` environment variable.
* For Markdown and text files, which need no conversion, `concurrency` makes little difference.
* Each document in progress holds its own memory, so a higher `concurrency` uses more memory. See [Large files](#large-files).
## Cancel a batch
[Section titled “Cancel a batch”](#cancel-a-batch)
Pass an `AbortSignal` as `signal` to stop a batch. When the signal is aborted, `chunkDocuments` stops starting new documents and throws a `DocchunkError` with the code `ABORTED`. The results of documents that already finished are not returned.
```ts
import { chunkDocuments, DocchunkError } from "docchunk";
try {
const results = await chunkDocuments(
sources,
{ signal: AbortSignal.timeout(60_000) },
);
} catch (error) {
if (error instanceof DocchunkError && error.code === "ABORTED") {
console.log("The batch took longer than a minute");
}
}
```
The signal is checked before each document, and between the steps of each document. A step that has already started, such as converting a PDF, finishes first. Before each document, the batch also lets pending timers run, so `AbortSignal.timeout` works even when every source is a string in memory.
## Chunk every file in a folder
[Section titled “Chunk every file in a folder”](#chunk-every-file-in-a-folder)
This example finds the supported files in a folder and its subfolders, and chunks them in one batch:
```ts
import { readdir } from "node:fs/promises";
import { extname, join } from "node:path";
import { chunkDocuments } from "docchunk";
const folder = "documents";
const extensions = new Set([".pdf", ".docx", ".pptx", ".xlsx", ".md", ".txt"]);
const entries = await readdir(folder, { recursive: true, withFileTypes: true });
const paths: string[] = [];
for (const entry of entries) {
if (entry.isFile() && extensions.has(extname(entry.name).toLowerCase())) {
paths.push(join(entry.parentPath, entry.name));
}
}
const results = await chunkDocuments(paths.map((path) => ({ path })));
for (const [index, item] of results.entries()) {
if (item.ok) {
console.log(paths[index], item.result.chunks.length);
} else {
console.error(paths[index], item.error.message);
}
}
```
Add the extensions of any other [formats](../chunk-document/#formats) you need.
## Documents that need different options
[Section titled “Documents that need different options”](#documents-that-need-different-options)
`chunkDocuments` uses one set of options for the whole list. When documents need different strategies, sizes, or a `documentId` each, call `chunkDocument` for each one. To keep the same one-failure-doesn’t-stop-the-others behavior, catch errors per document:
```ts
import { chunkDocument } from "docchunk";
const paths = ["guides/setup.md", "guides/billing.md"];
for (const path of paths) {
try {
const result = await chunkDocument(
{ path },
{ documentId: path, metadata: { source: path } },
);
console.log(path, result.chunks.length);
} catch (error) {
console.error(path, error);
}
}
```
This runs one document at a time. For a large list, you can run several of these calls at once with a concurrency library such as `p-limit`.
## Large files
[Section titled “Large files”](#large-files)
Parsing is the most memory-intensive step. While a document is being parsed, it uses about 250 times the size of its Markdown: roughly 250 MB for 1 MB of text. With the default `concurrency` of 4, four large documents can be in progress at the same time.
If your batch includes large files, or your process has a memory limit, lower `concurrency`:
```ts
const results = await chunkDocuments(sources, { concurrency: 1 });
```
[Performance](../../performance/) has measured times and memory use.
## Next steps
[Section titled “Next steps”](#next-steps)
* [Chunk a document](../chunk-document/): sources, formats, the result, warnings, and errors.
* [Strategies](../../strategies/): choose how documents are split.
# Strategies
> Eleven ways to split a document into chunks, and how to choose between them.
A strategy decides where each chunk starts and ends. Doc-chunk has 11. They all use the same function, accept the same sources, and return the same result, so you can switch strategy by changing one option:
```ts
import { chunkDocument } from "docchunk";
const { chunks } = await chunkDocument(
{ path: "handbook.pdf" },
{ strategy: "sentence-window" },
);
```
Without a `strategy` option, Doc-chunk uses [`structure`](./structure/).
## Which strategy to use
[Section titled “Which strategy to use”](#which-strategy-to-use)
Start with `structure`. It works well for most documents and most retrieval setups. Change it when you have a specific reason:
| If you want | Use |
| ------------------------------------------------------------------------------ | --------------------------------------- |
| Good general-purpose chunks | [`structure`](./structure/) |
| One chunk per section, such as one per article in a knowledge base | [`heading`](./heading/) |
| One chunk per paragraph, list, or table, such as one per FAQ answer | [`paragraph`](./paragraph/) |
| Small, precise chunks for search over prose | [`sentence`](./sentence/) |
| Search on single sentences, with the sentences around each match for the model | [`sentence-window`](./sentence-window/) |
| Small chunks for search, each linked to a larger chunk for the model | [`parent-child`](./parent-child/) |
| Chunks at three or more sizes, or one chunk for every section and subsection | [`hierarchical`](./hierarchical/) |
| The same behavior as the recursive character splitters in other libraries | [`recursive`](./recursive/) |
| A simple baseline to compare the other strategies against | [`fixed`](./fixed/) |
| Fixed-size chunks that share some text at each cut | [`fixed-overlap`](./fixed-overlap/) |
| Overlapping windows that cover every part of the text more than once | [`sliding-window`](./sliding-window/) |
[Compare strategies](./compare/) runs all 11 on the same document, so you can see the differences side by side.
## All strategies
[Section titled “All strategies”](#all-strategies)
| Strategy | Splits by | Follows structure | Default size | Output |
| ----------------- | ------------------------------------------ | ----------------- | --------------------- | ----------------------------- |
| `structure` | Whole blocks, packed up to `size` | Yes | 1,500 | Flat list |
| `heading` | Sections | Yes | No limit | Flat list |
| `paragraph` | Blocks | Yes | No limit | Flat list |
| `sentence` | Sentences | Yes | No limit | Flat list |
| `sentence-window` | Sentences | Yes | No limit | Flat list, with `contextText` |
| `parent-child` | Whole blocks, at two sizes | Yes | 4,000 and 800 | Two levels |
| `hierarchical` | Whole blocks at several sizes, or sections | Yes | 6,000, 1,500, and 400 | Several levels |
| `recursive` | Separators, then sentences, then spaces | Partly | 1,500 | Flat list |
| `fixed` | Character count | No | 1,500 | Flat list |
| `fixed-overlap` | Character count, with overlap | No | 1,500 | Flat list |
| `sliding-window` | Character count, moving by `step` | No | 1,500 | Flat list |
A strategy that follows structure never puts two sections in one chunk, keeps tables, lists, and code blocks whole when they fit, and splits a block that is too large along its rows, items, lines, or sentences. `recursive` splits at headings and blank lines first, but it can join small sections into one chunk and doesn’t repeat table headers. The last three ignore structure and cut the text by length.
All sizes are in characters. See [Sizes are in characters](../how-it-works/#sizes-are-in-characters).
## Options
[Section titled “Options”](#options)
Each strategy has its own options, listed on its page. Pass them next to `strategy`:
```ts
const { chunks } = await chunkDocument(
{ path: "handbook.pdf" },
{ strategy: "parent-child", parentSize: 3000, childSize: 600 },
);
```
In TypeScript, the options type depends on `strategy`, so your editor suggests only the options of the strategy you chose, and flags the others. At runtime, an option the strategy doesn’t accept throws an `INVALID_OPTIONS` error.
The options `metadata`, `documentId`, `headingPrefix`, and `signal` work with every strategy. See [Options every strategy accepts](../guides/chunk-document/#options-every-strategy-accepts).
## The example document
[Section titled “The example document”](#the-example-document)
Every strategy page runs the strategy on the same short file, `returns-policy.md`, so you can compare the results:
returns-policy.md
```md
# Returns policy
You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
## Start a return
1. Sign in and open **Orders**.
2. Choose the item you want to return.
3. Print the prepaid shipping label.
## Refunds
We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded.
| Item | Refund |
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
```
The file is 468 characters long, so the examples use small sizes to show how each strategy splits it. In real use, sizes of 500 to 2,000 characters are more common.
# Structure
> Packs whole blocks into chunks up to the size limit, never across a section. The default strategy.
`structure` packs whole paragraphs, lists, tables, and code blocks into chunks of up to `size` characters, and starts a new chunk at every section. It’s the default strategy.
```ts
const { chunks } = await chunkDocument({ path: "handbook.pdf" });
```
## When to use it
[Section titled “When to use it”](#when-to-use-it)
Use `structure` unless you have a reason to choose another strategy. It gives chunks that are about one topic, close to the size you ask for, and that don’t cut sentences, tables, or code in half. It works for manuals, reports, policies, notes, and most other documents.
Consider another strategy when:
* You want exactly one chunk per section, whatever its size: use [`heading`](../heading/).
* You want small chunks for search and large chunks for the model: use [`parent-child`](../parent-child/).
* The text has no structure at all, such as a raw transcript: `structure` still works, but [`sentence`](../sentence/) with a `size` gives the same result more directly.
## How it works
[Section titled “How it works”](#how-it-works)
1. Each heading is joined to the block after it, so a heading never ends a chunk.
2. Blocks are added to a chunk in order until the next one doesn’t fit in `size`. Then a new chunk starts.
3. A new chunk always starts at a section heading: a heading at `headingLevel` or higher. Two sections never share a chunk.
4. A block larger than `size` is split along its structure: tables by rows, lists by items, code by lines, and prose by sentences. See [Blocks larger than the size limit](../../how-it-works/#blocks-larger-than-the-size-limit).
5. A chunk smaller than `minSize` is merged into the chunk before it, or else the chunk after it, if both are in the same section and the result fits in `size`.
6. With `overlapChars`, each chunk also starts with whole sentences from the end of the chunk before it, in the same section.
## Example
[Section titled “Example”](#example)
returns-policy.md
```md
# Returns policy
You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
## Start a return
1. Sign in and open **Orders**.
2. Choose the item you want to return.
3. Print the prepaid shipping label.
## Refunds
We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded.
| Item | Refund |
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
```
With the default options, each section becomes one chunk:
```ts
import { chunkDocument } from "docchunk";
const { chunks } = await chunkDocument({ path: "returns-policy.md" });
for (const chunk of chunks) {
console.log(chunk.text);
console.log("---");
}
```
```txt
# Returns policy
You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
---
## Start a return
1. Sign in and open **Orders**.
2. Choose the item you want to return.
3. Print the prepaid shipping label.
---
## Refunds
We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded.
| Item | Refund |
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
---
```
With a smaller `size`, the sections are split. The paragraphs are split by sentences, the list by items, and the table stays whole because it fits:
```ts
import { chunkDocument } from "docchunk";
const { chunks } = await chunkDocument(
{ path: "returns-policy.md" },
{ size: 100, minSize: 50 },
);
for (const chunk of chunks) {
console.log(chunk.text);
console.log("---");
}
```
```txt
# Returns policy
You can return most items within 30 days of delivery.
---
Items must be unused and in their original packaging.
---
## Start a return
1. Sign in and open **Orders**.
2. Choose the item you want to return.
---
3. Print the prepaid shipping label.
---
## Refunds
We refund the original payment method within 5 business days of receiving the item.
---
Shipping costs are not refunded.
---
| Item | Refund |
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
---
```
## Options
[Section titled “Options”](#options)
| Option | Type | Default | Description |
| -------------- | -------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `size` | `number` | `1500` | Maximum characters per chunk. A positive integer. |
| `minSize` | `number` | `200`, or `size` if smaller | Chunks smaller than this are merged into a neighbor in the same section, when the result fits in `size`. A positive integer, at most `size`. |
| `overlapChars` | `number` | `0` | Characters of whole sentences each chunk repeats from the end of the previous chunk in its section. An integer from 0, less than `size`. |
| `headingLevel` | `number` | `3` | Headings at this level or higher start a new section. An integer from 1 to 6. |
## Good to know
[Section titled “Good to know”](#good-to-know)
* **Small sections stay small.** Sections are never merged, even when two would fit in one chunk. A document with many short sections gives many small chunks. To get fewer, larger chunks, lower `headingLevel`, for example to `2` or `1`, so that fewer headings start a section.
* **`minSize` follows a small `size`.** When you set a `size` below 200 and no `minSize`, `minSize` becomes equal to `size`. A `minSize` you set yourself can’t be larger than `size`.
* **Overlap can be shorter than `overlapChars`.** Overlap uses whole sentences, stays within the section, and never makes a chunk larger than `size`. If the last sentence of the previous chunk is longer than `overlapChars`, the chunk has no overlap.
* **A heading stays with its content.** When a heading is followed by a block too large for one chunk, the heading starts the first piece of that block. The block is then split at `size` minus the heading’s length, so every piece still fits.
* **A heading with no content of its own is a chunk.** A heading followed directly by another section heading, such as a title right before the first `##`, becomes a chunk that contains only the title.
## Related strategies
[Section titled “Related strategies”](#related-strategies)
* [`heading`](../heading/): one chunk per section, with no size limit by default.
* [`paragraph`](../paragraph/): one chunk per block.
* [`parent-child`](../parent-child/): `structure` at two sizes, with links between them.
# Heading
> One chunk per section. With a size limit, a larger section is split into packed blocks.
`heading` gives one chunk per section. A section starts at a heading at `headingLevel` or higher, and includes everything up to the next such heading.
```ts
const { chunks } = await chunkDocument(
{ path: "manual.docx" },
{ strategy: "heading" },
);
```
## When to use it
[Section titled “When to use it”](#when-to-use-it)
Use `heading` when each section of your documents is a complete answer on its own, and you want to retrieve it whole. Examples are knowledge base articles, API reference pages, and manuals where each section covers one task.
Don’t use it for documents with long sections, or with few headings, unless you set `size`. Without `size`, a long section becomes one long chunk, which is a poor match for specific questions and may exceed your embedding model’s limit.
## How it works
[Section titled “How it works”](#how-it-works)
1. The document is divided into sections at every heading at `headingLevel` or higher. Deeper headings stay inside their section.
2. Each section becomes one chunk. Text before the first heading becomes a chunk of its own.
3. With `size`, a section larger than `size` is split into chunks of whole blocks, like [`structure`](../structure/) does. Small sections are not merged.
## Example
[Section titled “Example”](#example)
returns-policy.md
```md
# Returns policy
You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
## Start a return
1. Sign in and open **Orders**.
2. Choose the item you want to return.
3. Print the prepaid shipping label.
## Refunds
We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded.
| Item | Refund |
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
```
Each `#` and `##` section becomes a chunk:
```ts
import { chunkDocument } from "docchunk";
const { chunks } = await chunkDocument(
{ path: "returns-policy.md" },
{ strategy: "heading" },
);
for (const chunk of chunks) {
console.log(chunk.text);
console.log("---");
}
```
```txt
# Returns policy
You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
---
## Start a return
1. Sign in and open **Orders**.
2. Choose the item you want to return.
3. Print the prepaid shipping label.
---
## Refunds
We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded.
| Item | Refund |
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
---
```
With `headingLevel: 1`, only `#` headings start a section, so the whole file is one chunk of 467 characters:
```ts
import { chunkDocument } from "docchunk";
const { chunks } = await chunkDocument(
{ path: "returns-policy.md" },
{ strategy: "heading", headingLevel: 1 },
);
console.log(chunks.length, chunks[0]?.charCount);
```
```txt
1 467
```
## Options
[Section titled “Options”](#options)
| Option | Type | Default | Description |
| -------------- | -------- | -------- | -------------------------------------------------------------------------------------- |
| `size` | `number` | No limit | Maximum characters per chunk. Sections larger than this are split. A positive integer. |
| `headingLevel` | `number` | `3` | Headings at this level or higher start a new section. An integer from 1 to 6. |
## Good to know
[Section titled “Good to know”](#good-to-know)
* **Large sections give a warning.** Without `size`, a chunk of more than 8,000 characters adds a `LARGE_CHUNK` warning to the result. Set `size` to split large sections.
* **Headings with no text of their own become small chunks.** A title followed directly by a subheading, such as `# Guide` right before `## Setup`, becomes a chunk that contains only the title.
* **With `size`, `heading` and `structure` are close.** The difference is that `heading` doesn’t merge small chunks, and has no overlap.
## Related strategies
[Section titled “Related strategies”](#related-strategies)
* [`structure`](../structure/): packs sections into chunks of a set size.
* [`hierarchical`](../hierarchical/) with `by: "heading"`: a chunk for every section and subsection, nested.
# Paragraph
> One chunk per block, with each heading kept with the block after it.
`paragraph` gives one chunk per block: a paragraph, a list, a table, a code block, or a block quote. Each heading is joined to the block after it.
```ts
const { chunks } = await chunkDocument(
{ path: "faq.md" },
{ strategy: "paragraph" },
);
```
## When to use it
[Section titled “When to use it”](#when-to-use-it)
Use `paragraph` when each paragraph is a self-contained answer, such as FAQ entries, glossaries, or release notes where each paragraph describes one change.
Don’t use it for long-form prose, where a paragraph often depends on the ones around it. Chunks of one paragraph each can then lack the context needed to match a question. [`structure`](../structure/) packs related paragraphs together instead.
## How it works
[Section titled “How it works”](#how-it-works)
1. Each block becomes one chunk. A whole list or a whole table counts as one block.
2. A heading is joined to the block after it, so it isn’t a chunk of its own.
3. With `size`, consecutive blocks in the same section are packed together up to `size`, and a block larger than `size` is split along its structure.
4. With `minSize`, a chunk smaller than `minSize` is merged into its neighbor in the same section.
## Example
[Section titled “Example”](#example)
returns-policy.md
```md
# Returns policy
You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
## Start a return
1. Sign in and open **Orders**.
2. Choose the item you want to return.
3. Print the prepaid shipping label.
## Refunds
We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded.
| Item | Refund |
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
```
Each heading is joined to its paragraph or list, and the table is a chunk of its own:
```ts
import { chunkDocument } from "docchunk";
const { chunks } = await chunkDocument(
{ path: "returns-policy.md" },
{ strategy: "paragraph" },
);
for (const chunk of chunks) {
console.log(chunk.text);
console.log("---");
}
```
```txt
# Returns policy
You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
---
## Start a return
1. Sign in and open **Orders**.
2. Choose the item you want to return.
3. Print the prepaid shipping label.
---
## Refunds
We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded.
---
| Item | Refund |
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
---
```
## Options
[Section titled “Options”](#options)
| Option | Type | Default | Description |
| -------------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `size` | `number` | No limit | Maximum characters per chunk. With a size, consecutive blocks are packed together. A positive integer. |
| `minSize` | `number` | `1` | Chunks smaller than this are merged into a neighbor in the same section, when the result fits in `size`. The default merges nothing. A positive integer, at most `size`. |
| `overlapChars` | `number` | `0` | Characters of whole sentences each chunk repeats from the end of the previous chunk in its section. An integer from 0, less than `size`. |
## Good to know
[Section titled “Good to know”](#good-to-know)
* **A long list or table is one chunk.** Without `size`, nothing is split. A chunk of more than 8,000 characters adds a `LARGE_CHUNK` warning. Set `size` to split large blocks.
* **`minSize` works without `size`.** With no size limit, every chunk smaller than `minSize` is merged into a neighbor in the same section. Use it to join very short paragraphs, such as one-line answers, to the paragraph next to them.
* **With `size`, `paragraph` behaves like `structure`,** except that `minSize` defaults to 1 instead of 200.
## Related strategies
[Section titled “Related strategies”](#related-strategies)
* [`structure`](../structure/): packs blocks together up to a size.
* [`sentence`](../sentence/): one chunk per sentence.
# Sentence
> One chunk per sentence, or consecutive sentences in the same section packed up to a size limit.
`sentence` gives one chunk per sentence. With `size`, it packs consecutive sentences of the same section into chunks of up to `size` characters.
```ts
const { chunks } = await chunkDocument(
{ path: "transcript.txt" },
{ strategy: "sentence" },
);
```
## When to use it
[Section titled “When to use it”](#when-to-use-it)
Use `sentence` without `size` for very precise search, where each result should be one statement. Use it with `size` for text without much structure, such as transcripts, emails, or articles written as long runs of paragraphs, when you want chunks that always end at the end of a sentence.
One-sentence chunks often lack context for the model. If you search on sentences but want to send more text to the model, use [`sentence-window`](../sentence-window/).
## How it works
[Section titled “How it works”](#how-it-works)
1. The document is split into sentences with the JavaScript `Intl.Segmenter` API. Each list item gives at least one sentence, and a whole table or code block counts as one sentence.
2. Headings are not sentences, so they aren’t in any chunk’s text. Each chunk’s `headingPath` still lists them.
3. Without `size`, each sentence is a chunk. With `size`, consecutive sentences in the same section are packed together up to `size`.
4. A sentence larger than `size` is split at spaces. A table or code block larger than `size` is split by rows or lines.
## Example
[Section titled “Example”](#example)
returns-policy.md
```md
# Returns policy
You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
## Start a return
1. Sign in and open **Orders**.
2. Choose the item you want to return.
3. Print the prepaid shipping label.
## Refunds
We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded.
| Item | Refund |
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
```
Each sentence, list item, and the table become chunks. The headings are left out:
```ts
import { chunkDocument } from "docchunk";
const { chunks } = await chunkDocument(
{ path: "returns-policy.md" },
{ strategy: "sentence" },
);
for (const chunk of chunks) {
console.log(chunk.text);
console.log("---");
}
```
```txt
You can return most items within 30 days of delivery.
---
Items must be unused and in their original packaging.
---
1. Sign in and open **Orders**.
---
2. Choose the item you want to return.
---
3. Print the prepaid shipping label.
---
We refund the original payment method within 5 business days of receiving the item.
---
Shipping costs are not refunded.
---
| Item | Refund |
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
---
```
With `size: 150`, the sentences of each section are packed together:
```ts
import { chunkDocument } from "docchunk";
const { chunks } = await chunkDocument(
{ path: "returns-policy.md" },
{ strategy: "sentence", size: 150 },
);
for (const chunk of chunks) {
console.log(chunk.text);
console.log("---");
}
```
```txt
You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
---
1. Sign in and open **Orders**.
2. Choose the item you want to return.
3. Print the prepaid shipping label.
---
We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded.
---
| Item | Refund |
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
---
```
## Options
[Section titled “Options”](#options)
| Option | Type | Default | Description |
| -------------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `size` | `number` | No limit | Maximum characters per chunk. With a size, consecutive sentences are packed together. A positive integer. |
| `minSize` | `number` | `1` | Chunks smaller than this are merged into a neighbor in the same section, when the result fits in `size`. The default merges nothing. A positive integer, at most `size`. |
| `overlapChars` | `number` | `0` | Characters of whole sentences each chunk repeats from the end of the previous chunk in its section. An integer from 0, less than `size`. |
## Good to know
[Section titled “Good to know”](#good-to-know)
* **Abbreviations can end a sentence.** `Intl.Segmenter` sometimes ends a sentence after an abbreviation such as “Dr.” or “e.g.”. Setting `size` or `minSize` hides most of these splits, because short pieces are packed or merged with their neighbors.
* **Headings aren’t in the text.** Use `headingPath`, or the `headingPrefix` option, to keep the heading context.
* **Sentences never cross sections.** Packing and overlap stay within one section.
## Related strategies
[Section titled “Related strategies”](#related-strategies)
* [`sentence-window`](../sentence-window/): one sentence per chunk, with the sentences around it as context.
* [`paragraph`](../paragraph/): one chunk per block.
# Sentence window
> One chunk per sentence, with the sentences around it in the same section as context.
`sentence-window` gives one chunk per sentence, like [`sentence`](../sentence/). Each chunk also has a `contextText` field with the sentences around it: `windowSize` sentences before and after, within the same section.
```ts
const { chunks } = await chunkDocument(
{ path: "handbook.pdf" },
{ strategy: "sentence-window" },
);
```
## When to use it
[Section titled “When to use it”](#when-to-use-it)
Use `sentence-window` when you want precise search and enough context for the model to answer. Embed each chunk’s `text`, so a search matches single sentences. When a chunk matches, send its `contextText` to the model instead of its `text`.
It works best with prose. For documents made mostly of tables or code, where one “sentence” is already a whole block, [`structure`](../structure/) is simpler.
## How it works
[Section titled “How it works”](#how-it-works)
1. The document is split into sentences, as in [`sentence`](../sentence/). A whole table or code block counts as one sentence, and headings are left out.
2. Each sentence becomes a chunk, and its `text` is that sentence.
3. `contextText` is the text from `windowSize` sentences before the chunk’s sentence to `windowSize` sentences after it. The window stops at the edges of the section, so the context never includes another section.
## Example
[Section titled “Example”](#example)
returns-policy.md
```md
# Returns policy
You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
## Start a return
1. Sign in and open **Orders**.
2. Choose the item you want to return.
3. Print the prepaid shipping label.
## Refunds
We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded.
| Item | Refund |
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
```
With `windowSize: 1`, each chunk’s context is the sentence before it, the sentence itself, and the sentence after it. Here are the last three chunks:
```ts
import { chunkDocument } from "docchunk";
const { chunks } = await chunkDocument(
{ path: "returns-policy.md" },
{ strategy: "sentence-window", windowSize: 1 },
);
for (const chunk of chunks.slice(5)) {
console.log("text:", chunk.text);
console.log("context:", chunk.contextText);
console.log("---");
}
```
```txt
text: We refund the original payment method within 5 business days of receiving the item.
context: We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded.
---
text: Shipping costs are not refunded.
context: We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded.
| Item | Refund |
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
---
text: | Item | Refund |
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
context: Shipping costs are not refunded.
| Item | Refund |
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
---
```
The first of these chunks has nothing before it in the *Refunds* section, so its context starts with the sentence itself.
## Options
[Section titled “Options”](#options)
| Option | Type | Default | Description |
| ------------ | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `windowSize` | `number` | `3` | Sentences on each side of the chunk’s sentence that go into `contextText`. An integer from 0. With `0`, `contextText` is the same as `text`. |
## Good to know
[Section titled “Good to know”](#good-to-know)
* **`contextText` has no size limit.** It grows with `windowSize`, and a window that includes a large table includes the whole table. Choose `windowSize` with your model’s context in mind.
* **Only `text` counts for size.** `charCount` and `contentHash` describe `text`, not `contextText`.
* **Use `headingPath` for the headings.** Headings are not part of `text` or `contextText`.
## Related strategies
[Section titled “Related strategies”](#related-strategies)
* [`sentence`](../sentence/): the same chunks, without `contextText`.
* [`parent-child`](../parent-child/): the same idea at a larger scale: small chunks for search, each linked to a larger chunk for the model.
# Parent-child
> Small chunks for search, each linked to a larger parent chunk that gives context.
`parent-child` gives chunks at two sizes: large parent chunks, and small child chunks inside each parent. Each child links to its parent, and each parent lists its children.
```ts
const { chunks } = await chunkDocument(
{ path: "policy.pdf" },
{ strategy: "parent-child" },
);
```
## When to use it
[Section titled “When to use it”](#when-to-use-it)
Small chunks give precise search results, but often don’t contain enough for the model to answer. Large chunks give the model context, but their embeddings are less precise. `parent-child` gives you both: embed the children, and when a child matches a question, send its parent to the model.
If you need more than two sizes, use [`hierarchical`](../hierarchical/). If you want context at the level of sentences rather than blocks, use [`sentence-window`](../sentence-window/).
## How it works
[Section titled “How it works”](#how-it-works)
1. The parents are made with [`structure`](../structure/) at `parentSize`. They never cross a section.
2. Each parent is split again with `structure` at `childSize`. The children always lie inside their parent.
3. Parents have `level: 0` and a `childIds` list. Children have `level: 1` and a `parentId`.
4. All chunks are returned in one list, in document order, with each parent before its children.
## Example
[Section titled “Example”](#example)
returns-policy.md
```md
# Returns policy
You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
## Start a return
1. Sign in and open **Orders**.
2. Choose the item you want to return.
3. Print the prepaid shipping label.
## Refunds
We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded.
| Item | Refund |
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
```
```ts
import { chunkDocument } from "docchunk";
const { chunks } = await chunkDocument(
{ path: "returns-policy.md" },
{ strategy: "parent-child", parentSize: 300, childSize: 100 },
);
for (const chunk of chunks) {
const indent = " ".repeat(chunk.level ?? 0);
const firstLine = chunk.text.split("\n")[0];
console.log(`${indent}level ${chunk.level}, ${chunk.charCount} chars: ${firstLine}`);
}
```
```txt
level 0, 125 chars: # Returns policy
level 1, 71 chars: # Returns policy
level 1, 53 chars: Items must be unused and in their original packaging.
level 0, 126 chars: ## Start a return
level 1, 89 chars: ## Start a return
level 1, 36 chars: 3. Print the prepaid shipping label.
level 0, 212 chars: ## Refunds
level 1, 95 chars: ## Refunds
level 1, 32 chars: Shipping costs are not refunded.
level 1, 82 chars: | Item | Refund |
```
Each section is one parent. The *Refunds* parent has three children: the heading with the first sentence, the second sentence, and the table.
## Use the parents and children
[Section titled “Use the parents and children”](#use-the-parents-and-children)
Embed only the children, and keep a way to find each chunk by its `id`:
```ts
import { chunkDocument } from "docchunk";
const { chunks } = await chunkDocument(
{ path: "policy.pdf" },
{ strategy: "parent-child" },
);
const children = chunks.filter((chunk) => chunk.level === 1);
const chunksById = new Map(chunks.map((chunk) => [chunk.id, chunk]));
// Embed and store `children`. When a search returns a child,
// look up its parent and send the parent's text to the model:
// const parent = chunksById.get(child.parentId ?? "");
```
In a vector database, store each child’s `parentId` in its metadata, and store the parents’ text somewhere you can look up by id, such as a key-value store or another table.
## Options
[Section titled “Options”](#options)
| Option | Type | Default | Description |
| ------------ | -------- | ------- | ---------------------------------------------------------------------------------- |
| `parentSize` | `number` | `4000` | Maximum characters per parent chunk. A positive integer, larger than `childSize`. |
| `childSize` | `number` | `800` | Maximum characters per child chunk. A positive integer, smaller than `parentSize`. |
## Good to know
[Section titled “Good to know”](#good-to-know)
* **A parent can have a single child with the same text.** When a parent is no larger than `childSize`, its only child is a copy of it. Both have different `id`s, because their levels differ.
* **Parents follow sections.** A parent never spans two sections, so a document with short sections has parents much smaller than `parentSize`.
* **Children use a `minSize` of 200,** or `childSize` if that is smaller, so very short children are merged with their neighbors.
* **`buildChunkTree` turns the list into a tree.** See [`buildChunkTree`](../../reference/build-chunk-tree/).
## Related strategies
[Section titled “Related strategies”](#related-strategies)
* [`hierarchical`](../hierarchical/): the same idea with any number of levels, or following the headings.
* [`sentence-window`](../sentence-window/): small chunks with surrounding context, at the level of sentences.
# Hierarchical
> Nested chunks at several sizes, or chunks that follow the heading tree.
`hierarchical` gives nested chunks: large chunks, the chunks inside them, the chunks inside those, and so on. It builds the levels in one of two ways: by size, or by heading.
```ts
const { chunks } = await chunkDocument(
{ path: "handbook.pdf" },
{ strategy: "hierarchical", levels: [6000, 1500, 400] },
);
```
## When to use it
[Section titled “When to use it”](#when-to-use-it)
Use `hierarchical` by size when you want more than the two levels of [`parent-child`](../parent-child/), for example to search small chunks and then widen the context step by step.
Use `hierarchical` by heading when you want a chunk for every section and every subsection, so you can retrieve a whole chapter, one of its sections, or one subsection. This suits long documents with a clear outline, such as manuals and specifications.
## How it works
[Section titled “How it works”](#how-it-works)
### By size
[Section titled “By size”](#by-size)
With `by: "size"`, the default, `levels` lists the maximum size of each level, largest first.
1. Level 0 is made with [`structure`](../structure/) at the first size.
2. Each chunk of level 0 is split with `structure` at the second size, giving level 1. Each chunk of level 1 is split at the third size, and so on.
3. Every chunk below level 0 has a `parentId`, and every chunk with children has `childIds`.
`parent-child` is the same as `hierarchical` by size with two levels.
### By heading
[Section titled “By heading”](#by-heading)
With `by: "heading"`, the levels follow the document’s headings.
1. Every heading at `headingLevel` or higher starts a section. Each section becomes a chunk that includes its subsections.
2. A section’s level is how deeply it is nested: level 0 for the outermost sections, 1 for the sections inside them, and so on. Text before the first heading is a chunk at level 0.
3. A section with no subsections that is larger than `leafSize` gets children: it is split with `structure` at `leafSize`, one level deeper.
## Example
[Section titled “Example”](#example)
returns-policy.md
```md
# Returns policy
You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
## Start a return
1. Sign in and open **Orders**.
2. Choose the item you want to return.
3. Print the prepaid shipping label.
## Refunds
We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded.
| Item | Refund |
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
```
By heading, the `#` section contains the whole document, the `##` sections are inside it, and the *Refunds* section is larger than `leafSize`, so it’s split again:
```ts
import { chunkDocument } from "docchunk";
const { chunks } = await chunkDocument(
{ path: "returns-policy.md" },
{ strategy: "hierarchical", by: "heading", leafSize: 150 },
);
for (const chunk of chunks) {
const indent = " ".repeat(chunk.level ?? 0);
const firstLine = chunk.text.split("\n")[0];
console.log(`${indent}level ${chunk.level}, ${chunk.charCount} chars: ${firstLine}`);
}
```
```txt
level 0, 467 chars: # Returns policy
level 1, 126 chars: ## Start a return
level 1, 212 chars: ## Refunds
level 2, 128 chars: ## Refunds
level 2, 82 chars: | Item | Refund |
```
By size, with three levels:
```ts
import { chunkDocument } from "docchunk";
const { chunks } = await chunkDocument(
{ path: "returns-policy.md" },
{ strategy: "hierarchical", levels: [400, 150, 100] },
);
for (const chunk of chunks) {
const indent = " ".repeat(chunk.level ?? 0);
const firstLine = chunk.text.split("\n")[0];
console.log(`${indent}level ${chunk.level}, ${chunk.charCount} chars: ${firstLine}`);
}
```
```txt
level 0, 125 chars: # Returns policy
level 1, 125 chars: # Returns policy
level 2, 71 chars: # Returns policy
level 2, 53 chars: Items must be unused and in their original packaging.
level 0, 126 chars: ## Start a return
level 1, 126 chars: ## Start a return
level 2, 89 chars: ## Start a return
level 2, 36 chars: 3. Print the prepaid shipping label.
level 0, 212 chars: ## Refunds
level 1, 128 chars: ## Refunds
level 2, 95 chars: ## Refunds
level 2, 32 chars: Shipping costs are not refunded.
level 1, 82 chars: | Item | Refund |
level 2, 82 chars: | Item | Refund |
```
## Options
[Section titled “Options”](#options)
| Option | Type | Default | Description |
| -------------- | ----------------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `by` | `"size"` or `"heading"` | `"size"` | How the levels are built. |
| `levels` | `number[]` | `[6000, 1500, 400]` | Maximum characters per chunk at each level, largest first. Used with `by: "size"`. A non-empty array of positive integers, each smaller than the one before. |
| `headingLevel` | `number` | `3` | Headings at this level or higher start a new section. An integer from 1 to 6. |
| `leafSize` | `number` | `1500` | Maximum characters per chunk when a section without subsections is split. Used with `by: "heading"`. A positive integer. |
## Good to know
[Section titled “Good to know”](#good-to-know)
* **A chunk can have a single child with the same text.** When a chunk already fits the next level’s size, its only child is a copy of it, one level deeper.
* **By heading, sections have no size limit.** Only sections without subsections are split, at `leafSize`. A large section with subsections stays whole at its own level, and a chunk of more than 8,000 characters adds a `LARGE_CHUNK` warning.
* **Chunks are sorted by position, then level.** Each chunk comes before the chunks inside it.
* **`buildChunkTree` turns the list into a tree.** See [`buildChunkTree`](../../reference/build-chunk-tree/).
## Related strategies
[Section titled “Related strategies”](#related-strategies)
* [`parent-child`](../parent-child/): two levels by size, with simpler options.
* [`heading`](../heading/): one flat chunk per section.
# Recursive
> Splits on separators, then sentences, then spaces, until every piece fits the size limit.
`recursive` splits the text at a list of separators, from headings to blank lines to line breaks, then at sentences and spaces, until every piece fits in `size`. Then it joins neighboring pieces back together, up to `size`.
```ts
const { chunks } = await chunkDocument(
{ path: "notes.md" },
{ strategy: "recursive" },
);
```
## When to use it
[Section titled “When to use it”](#when-to-use-it)
Use `recursive` when you are moving from another library’s recursive character splitter, such as LangChain’s `RecursiveCharacterTextSplitter`, and want similar chunks.
For new projects, [`structure`](../structure/) usually gives better chunks: it never joins two sections, and it repeats table headers and code fences when it splits them.
## How it works
[Section titled “How it works”](#how-it-works)
1. If the text fits in `size`, it’s one chunk.
2. Otherwise, the text is split at the first separator in `separators` that occurs in it. Each separator stays at the start of the piece after the split.
3. Neighboring pieces are joined back together, as long as the result fits in `size`.
4. A piece that is still larger than `size` is split again with the next separator. After the separators come sentence boundaries, then spaces, and finally a cut at exactly `size` characters.
The default separators, in order, are a line starting with `# `, `## `, `### `, or `#### `, then a blank line, then a line break.
## Example
[Section titled “Example”](#example)
returns-policy.md
```md
# Returns policy
You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
## Start a return
1. Sign in and open **Orders**.
2. Choose the item you want to return.
3. Print the prepaid shipping label.
## Refunds
We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded.
| Item | Refund |
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
```
```ts
import { chunkDocument } from "docchunk";
const { chunks } = await chunkDocument(
{ path: "returns-policy.md" },
{ strategy: "recursive", size: 100 },
);
for (const chunk of chunks) {
console.log(chunk.text);
console.log("---");
}
```
```txt
# Returns policy
---
You can return most items within 30 days of delivery.
---
Items must be unused and in their original packaging.
---
## Start a return
---
1. Sign in and open **Orders**.
2. Choose the item you want to return.
---
3. Print the prepaid shipping label.
---
## Refunds
---
We refund the original payment method within 5 business days of receiving the item.
---
Shipping costs are not refunded.
---
| Item | Refund |
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
---
```
The document was split at headings, then at blank lines, then at sentences. Each heading ended up on its own, because joining it to the paragraph after it would go over `size`.
## Options
[Section titled “Options”](#options)
| Option | Type | Default | Description |
| -------------- | ---------- | ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------- |
| `size` | `number` | `1500` | Maximum characters per chunk. A positive integer. |
| `overlapChars` | `number` | `0` | Characters of whole pieces each chunk repeats from the end of the previous one. An integer from 0, less than `size`. |
| `separators` | `string[]` | `["\n# ", "\n## ", "\n### ", "\n#### ", "\n\n", "\n"]` | Separators tried in order, before sentences, spaces, and a cut at `size`. An array of non-empty strings. |
## Good to know
[Section titled “Good to know”](#good-to-know)
* **Sections can share a chunk.** Pieces are joined whenever they fit, so small sections are joined together, unlike in `structure`.
* **Tables and code blocks are split by lines.** A large table is split at line breaks without repeating its header, and a large code block without repeating its fences.
* **Headings can end up alone,** as in the example, when the text after them is too large to join.
* **Custom separators.** To split plain text at a different marker, such as a line of dashes, pass your own list: `separators: ["\n---\n", "\n\n", "\n"]`.
## Related strategies
[Section titled “Related strategies”](#related-strategies)
* [`structure`](../structure/): splits by the parsed structure instead of separator strings.
* [`sentence`](../sentence/) with `size`: packs whole sentences.
# Fixed
> Cuts the text every size characters, ignoring the document's structure.
`fixed` cuts the document’s Markdown into pieces of `size` characters, from start to end. It ignores headings, paragraphs, tables, and every other part of the structure.
```ts
const { chunks } = await chunkDocument(
{ path: "notes.txt" },
{ strategy: "fixed", size: 1000 },
);
```
## When to use it
[Section titled “When to use it”](#when-to-use-it)
Use `fixed` as a baseline: chunk your documents with `fixed` and with another strategy, and compare the retrieval quality. It’s also fine for text with no structure at all, where every part is equally important, such as logs.
Don’t use it for documents with headings, lists, or tables. Its chunks cut through sentences, list items, and table rows, and mix the end of one section with the start of the next.
## How it works
[Section titled “How it works”](#how-it-works)
1. The first chunk is the first `size` characters of `document.markdown`, the next chunk the following `size` characters, and so on.
2. With `boundary: "word"`, the default, a cut that falls inside a word moves back to just after the last space or line break within the last 10% of the chunk. If there’s none, the cut stays at `size`.
3. With `boundary: "char"`, every cut is at exactly `size` characters.
## Example
[Section titled “Example”](#example)
returns-policy.md
```md
# Returns policy
You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
## Start a return
1. Sign in and open **Orders**.
2. Choose the item you want to return.
3. Print the prepaid shipping label.
## Refunds
We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded.
| Item | Refund |
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
```
```ts
import { chunkDocument } from "docchunk";
const { chunks } = await chunkDocument(
{ path: "returns-policy.md" },
{ strategy: "fixed", size: 200 },
);
for (const chunk of chunks) {
console.log(chunk.text);
console.log("---");
}
```
```txt
# Returns policy
You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
## Start a return
1. Sign in and open **Orders**.
2. Choose the item you
---
want to return.
3. Print the prepaid shipping label.
## Refunds
We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded.
| Item | Refund
---
|
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
---
```
The first cut falls in the middle of a list item, and the second in the middle of the table’s header row.
## Options
[Section titled “Options”](#options)
| Option | Type | Default | Description |
| ---------- | -------------------- | -------- | ------------------------------------------------------------------------------------------------ |
| `size` | `number` | `1500` | Maximum characters per chunk. A positive integer. |
| `boundary` | `"word"` or `"char"` | `"word"` | `"word"` moves a cut back to a space near the end of the chunk. `"char"` cuts at exactly `size`. |
## Good to know
[Section titled “Good to know”](#good-to-know)
* **Chunks can be shorter than `size`.** Word boundaries move cuts back, and spaces and line breaks at the start and end of each chunk are removed.
* **Emoji are never cut in half.** A cut never falls inside a character that JavaScript stores as two code units, such as an emoji.
* **`headingPath` still works.** Each chunk lists the headings above its start, even though the cuts ignore them.
## Related strategies
[Section titled “Related strategies”](#related-strategies)
* [`fixed-overlap`](../fixed-overlap/): the same cuts, with some text repeated between neighboring chunks.
* [`sliding-window`](../sliding-window/): windows that move by a set step.
* [`structure`](../structure/): chunks of a set size that follow the structure.
# Fixed overlap
> Like fixed, but consecutive chunks share a set number of characters.
`fixed-overlap` cuts the text into pieces of `size` characters, like [`fixed`](../fixed/), but each chunk starts `overlapChars` characters before the previous one ended. Text near each cut appears in two chunks.
```ts
const { chunks } = await chunkDocument(
{ path: "notes.txt" },
{ strategy: "fixed-overlap", size: 1000, overlapChars: 150 },
);
```
## When to use it
[Section titled “When to use it”](#when-to-use-it)
Use `fixed-overlap` for text without structure when a sentence cut in half by `fixed` would be lost. With overlap, the text on both sides of every cut is complete in at least one chunk, as long as it’s shorter than `overlapChars`.
For documents with structure, [`structure`](../structure/) with `overlapChars` gives overlap of whole sentences instead.
## How it works
[Section titled “How it works”](#how-it-works)
1. The first chunk is cut as in `fixed`: at `size` characters, moved back to a word boundary with `boundary: "word"`.
2. Each following chunk starts `overlapChars` characters before the end of the previous chunk, and is cut the same way.
3. `size` includes the overlap: every chunk is at most `size` characters long.
## Example
[Section titled “Example”](#example)
returns-policy.md
```md
# Returns policy
You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
## Start a return
1. Sign in and open **Orders**.
2. Choose the item you want to return.
3. Print the prepaid shipping label.
## Refunds
We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded.
| Item | Refund |
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
```
```ts
import { chunkDocument } from "docchunk";
const { chunks } = await chunkDocument(
{ path: "returns-policy.md" },
{ strategy: "fixed-overlap", size: 200, overlapChars: 50 },
);
for (const chunk of chunks) {
console.log(chunk.text);
console.log("---");
}
```
```txt
# Returns policy
You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
## Start a return
1. Sign in and open **Orders**.
2. Choose the item you
---
ign in and open **Orders**.
2. Choose the item you want to return.
3. Print the prepaid shipping label.
## Refunds
We refund the original payment method within 5 business days of receiving the item.
---
thod within 5 business days of receiving the item. Shipping costs are not refunded.
| Item | Refund |
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
---
```
Each chunk after the first repeats the last 50 characters of the chunk before it.
## Options
[Section titled “Options”](#options)
| Option | Type | Default | Description |
| -------------- | -------------------- | -------- | ---------------------------------------------------------------------------------------------------- |
| `size` | `number` | `1500` | Maximum characters per chunk, including the overlap. A positive integer. |
| `overlapChars` | `number` | `200` | Characters each chunk repeats from the end of the previous one. An integer from 0, less than `size`. |
| `boundary` | `"word"` or `"char"` | `"word"` | `"word"` moves a cut back to a space near the end of the chunk. `"char"` cuts at exactly `size`. |
## Good to know
[Section titled “Good to know”](#good-to-know)
* **Chunks can start in the middle of a word.** `boundary` moves where each chunk ends, but each chunk starts exactly `overlapChars` before the previous end, as in the example above.
* **More overlap means more chunks.** Each chunk adds `size - overlapChars` new characters, so an overlap of half the size roughly doubles the number of chunks.
* **With `overlapChars: 0`,** `fixed-overlap` gives the same chunks as `fixed`.
## Related strategies
[Section titled “Related strategies”](#related-strategies)
* [`fixed`](../fixed/): the same cuts, without overlap.
* [`sliding-window`](../sliding-window/): the same strategy, set by the step between chunks instead of the overlap.
# Sliding window
> A window of size characters that moves forward step characters at a time.
`sliding-window` moves a window of `size` characters through the text, `step` characters at a time. Each position of the window is a chunk.
```ts
const { chunks } = await chunkDocument(
{ path: "notes.txt" },
{ strategy: "sliding-window", size: 1000, step: 500 },
);
```
## When to use it
[Section titled “When to use it”](#when-to-use-it)
Use `sliding-window` for text without structure when you want every part of the text to appear in more than one chunk, so that a passage is complete in at least one of them wherever it falls. With `step` at half of `size`, the default, most characters are in two chunks.
For documents with structure, prefer [`structure`](../structure/). For fewer, less overlapping chunks, use [`fixed-overlap`](../fixed-overlap/) with a small overlap.
## How it works
[Section titled “How it works”](#how-it-works)
`sliding-window` is [`fixed-overlap`](../fixed-overlap/) with an overlap of `size - step`:
1. The first chunk is the first `size` characters, moved back to a word boundary with `boundary: "word"`.
2. Each following chunk starts `size - step` characters before the end of the previous one, which is about `step` characters after the previous start.
## Example
[Section titled “Example”](#example)
returns-policy.md
```md
# Returns policy
You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
## Start a return
1. Sign in and open **Orders**.
2. Choose the item you want to return.
3. Print the prepaid shipping label.
## Refunds
We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded.
| Item | Refund |
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
```
```ts
import { chunkDocument } from "docchunk";
const { chunks } = await chunkDocument(
{ path: "returns-policy.md" },
{ strategy: "sliding-window", size: 200, step: 100 },
);
for (const chunk of chunks) {
console.log(chunk.text);
console.log("---");
}
```
```txt
# Returns policy
You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
## Start a return
1. Sign in and open **Orders**.
2. Choose the item you
---
their original packaging.
## Start a return
1. Sign in and open **Orders**.
2. Choose the item you want to return.
3. Print the prepaid shipping label.
## Refunds
We refund the original payment
---
ou want to return.
3. Print the prepaid shipping label.
## Refunds
We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded.
| Item |
---
ent method within 5 business days of receiving the item. Shipping costs are not refunded.
| Item | Refund |
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
---
```
## Options
[Section titled “Options”](#options)
| Option | Type | Default | Description |
| ---------- | -------------------- | -------- | ------------------------------------------------------------------------------------------------ |
| `size` | `number` | `1500` | Characters in each window. A positive integer. |
| `step` | `number` | `750` | Characters the window moves forward each time. A positive integer, at most `size`. |
| `boundary` | `"word"` or `"char"` | `"word"` | `"word"` moves a cut back to a space near the end of the chunk. `"char"` cuts at exactly `size`. |
## Good to know
[Section titled “Good to know”](#good-to-know)
* **The step isn’t exact with word boundaries.** When a window’s end moves back to a space, the next window starts earlier by the same amount.
* **Chunks can start in the middle of a word,** as in `fixed-overlap`.
* **With `step` equal to `size`,** windows don’t overlap, and the result is the same as `fixed`.
## Related strategies
[Section titled “Related strategies”](#related-strategies)
* [`fixed-overlap`](../fixed-overlap/): the same strategy, set by the overlap instead of the step.
* [`fixed`](../fixed/): windows with no overlap.
# Compare strategies
> All 11 strategies run on the same document, side by side.
This page runs every strategy on the same short document, so you can see where each one puts its chunk boundaries. The size-based strategies use sizes of 100 to 400 characters, because the document is small.
## The document
[Section titled “The document”](#the-document)
returns-policy.md
```md
# Returns policy
You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
## Start a return
1. Sign in and open **Orders**.
2. Choose the item you want to return.
3. Print the prepaid shipping label.
## Refunds
We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded.
| Item | Refund |
| --- | --- |
| Unused item | Full price |
| Opened item | 80% |
```
## Results
[Section titled “Results”](#results)
| Strategy | Options | Chunks | Smallest | Largest |
| ---------------------------------------- | ------------------------------------- | ------ | -------- | ------- |
| [`structure`](../structure/) | `{ size: 200, minSize: 50 }` | 4 | 82 | 128 |
| [`heading`](../heading/) | Defaults | 3 | 125 | 212 |
| [`paragraph`](../paragraph/) | Defaults | 4 | 82 | 128 |
| [`sentence`](../sentence/) | Defaults | 8 | 31 | 83 |
| [`sentence-window`](../sentence-window/) | Defaults | 8 | 31 | 83 |
| [`parent-child`](../parent-child/) | `{ parentSize: 300, childSize: 100 }` | 10 | 32 | 212 |
| [`hierarchical`](../hierarchical/) | `{ levels: [400, 150, 100] }` | 14 | 32 | 212 |
| [`recursive`](../recursive/) | `{ size: 200 }` | 4 | 82 | 128 |
| [`fixed`](../fixed/) | `{ size: 200 }` | 3 | 66 | 200 |
| [`fixed-overlap`](../fixed-overlap/) | `{ size: 200, overlapChars: 50 }` | 3 | 167 | 200 |
| [`sliding-window`](../sliding-window/) | `{ size: 200, step: 100 }` | 4 | 173 | 200 |
## Chunk boundaries
[Section titled “Chunk boundaries”](#chunk-boundaries)
Each line is one chunk: its size in characters, then its first and last lines. Chunks inside a larger chunk are indented.
```txt
## structure: 4 chunks, 82 to 128 chars
125 | # Returns policy … You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
126 | ## Start a return … 3. Print the prepaid shipping label.
128 | ## Refunds … We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded.
82 | | Item | Refund | … | Opened item | 80% |
## heading: 3 chunks, 125 to 212 chars
125 | # Returns policy … You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
126 | ## Start a return … 3. Print the prepaid shipping label.
212 | ## Refunds … | Opened item | 80% |
## paragraph: 4 chunks, 82 to 128 chars
125 | # Returns policy … You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
126 | ## Start a return … 3. Print the prepaid shipping label.
128 | ## Refunds … We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded.
82 | | Item | Refund | … | Opened item | 80% |
## sentence: 8 chunks, 31 to 83 chars
53 | You can return most items within 30 days of delivery.
53 | Items must be unused and in their original packaging.
31 | 1. Sign in and open **Orders**.
38 | 2. Choose the item you want to return.
36 | 3. Print the prepaid shipping label.
83 | We refund the original payment method within 5 business days of receiving the item.
32 | Shipping costs are not refunded.
82 | | Item | Refund | … | Opened item | 80% |
## sentence-window: 8 chunks, 31 to 83 chars
53 | You can return most items within 30 days of delivery.
53 | Items must be unused and in their original packaging.
31 | 1. Sign in and open **Orders**.
38 | 2. Choose the item you want to return.
36 | 3. Print the prepaid shipping label.
83 | We refund the original payment method within 5 business days of receiving the item.
32 | Shipping costs are not refunded.
82 | | Item | Refund | … | Opened item | 80% |
## parent-child: 10 chunks, 32 to 212 chars
125 | # Returns policy … You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
71 | # Returns policy … You can return most items within 30 days of delivery.
53 | Items must be unused and in their original packaging.
126 | ## Start a return … 3. Print the prepaid shipping label.
89 | ## Start a return … 2. Choose the item you want to return.
36 | 3. Print the prepaid shipping label.
212 | ## Refunds … | Opened item | 80% |
95 | ## Refunds … We refund the original payment method within 5 business days of receiving the item.
32 | Shipping costs are not refunded.
82 | | Item | Refund | … | Opened item | 80% |
## hierarchical: 14 chunks, 32 to 212 chars
125 | # Returns policy … You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
125 | # Returns policy … You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
71 | # Returns policy … You can return most items within 30 days of delivery.
53 | Items must be unused and in their original packaging.
126 | ## Start a return … 3. Print the prepaid shipping label.
126 | ## Start a return … 3. Print the prepaid shipping label.
89 | ## Start a return … 2. Choose the item you want to return.
36 | 3. Print the prepaid shipping label.
212 | ## Refunds … | Opened item | 80% |
128 | ## Refunds … We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded.
95 | ## Refunds … We refund the original payment method within 5 business days of receiving the item.
32 | Shipping costs are not refunded.
82 | | Item | Refund | … | Opened item | 80% |
82 | | Item | Refund | … | Opened item | 80% |
## recursive: 4 chunks, 82 to 128 chars
125 | # Returns policy … You can return most items within 30 days of delivery. Items must be unused and in their original packaging.
126 | ## Start a return … 3. Print the prepaid shipping label.
128 | ## Refunds … We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded.
82 | | Item | Refund | … | Opened item | 80% |
## fixed: 3 chunks, 66 to 200 chars
200 | # Returns policy … 2. Choose the item you
199 | want to return. … | Item | Refund
66 | | … | Opened item | 80% |
## fixed-overlap: 3 chunks, 167 to 200 chars
200 | # Returns policy … 2. Choose the item you
200 | ign in and open **Orders**. … We refund the original payment method within 5 business days of receiving the item.
167 | thod within 5 business days of receiving the item. Shipping costs are not refunded. … | Opened item | 80% |
## sliding-window: 4 chunks, 173 to 200 chars
200 | # Returns policy … 2. Choose the item you
197 | their original packaging. … We refund the original payment
195 | ou want to return. … | Item |
173 | ent method within 5 business days of receiving the item. Shipping costs are not refunded. … | Opened item | 80% |
```
## What to look at
[Section titled “What to look at”](#what-to-look-at)
* **`structure`, `heading`, `paragraph`, and `recursive`** give almost the same chunks here, because each section is small. They differ on longer documents: `heading` never splits a section without `size`, `paragraph` never packs blocks together without `size`, and `recursive` can join small sections.
* **`sentence` and `sentence-window`** have the same `text`. The difference is `contextText`, which this page doesn’t show. Neither includes the headings in the text.
* **`parent-child` and `hierarchical`** cover the same text once per level, so their chunks add up to more text than the document has. Usually only one level is embedded.
* **`fixed`, `fixed-overlap`, and `sliding-window`** cut through the list and the table. `fixed-overlap` and `sliding-window` also start chunks in the middle of words.
## The script
[Section titled “The script”](#the-script)
The output above comes from this script:
```ts
import { type ChunkOptions, chunkDocument } from "docchunk";
const runs: ChunkOptions[] = [
{ strategy: "structure", size: 200, minSize: 50 },
{ strategy: "heading" },
{ strategy: "paragraph" },
{ strategy: "sentence" },
{ strategy: "sentence-window" },
{ strategy: "parent-child", parentSize: 300, childSize: 100 },
{ strategy: "hierarchical", levels: [400, 150, 100] },
{ strategy: "recursive", size: 200 },
{ strategy: "fixed", size: 200 },
{ strategy: "fixed-overlap", size: 200, overlapChars: 50 },
{ strategy: "sliding-window", size: 200, step: 100 },
];
for (const options of runs) {
const { chunks, stats } = await chunkDocument(
{ path: "returns-policy.md" },
options,
);
const sizes = `${stats.minChars} to ${stats.maxChars} chars`;
console.log(`## ${options.strategy}: ${stats.count} chunks, ${sizes}`);
for (const chunk of chunks) {
const indent = " ".repeat(chunk.level ?? 0);
const lines = chunk.text.split("\n");
const preview = lines.length === 1 ? lines[0] : `${lines[0]} … ${lines.at(-1)}`;
console.log(`${indent}${chunk.charCount} | ${preview}`);
}
}
```
# chunkDocument
> Chunks one document and returns its chunks, stats, and warnings.
Chunks one document.
```ts
function chunkDocument(source: DocumentSource, options?: ChunkOptions): Promise;
```
## Parameters
[Section titled “Parameters”](#parameters)
| Parameter | Type | Description |
| --------- | -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `source` | [`DocumentSource`](../types/#documentsource) | The document: `{ path }`, `{ bytes, filename?, format? }`, or `{ content, format }`. |
| `options` | [`ChunkOptions`](../types/#chunkoptions) | Optional. The strategy, its options, and the [common options](../options/#common-options). Without options, the `structure` strategy is used with its defaults. |
## Returns
[Section titled “Returns”](#returns)
A promise of a [`ChunkResult`](../types/#chunkresult):
| Field | Type | Description |
| ---------- | ------------------------------------------ | ----------------------------------------------------------------- |
| `chunks` | [`Chunk[]`](../types/#chunk) | The chunks, in document order. |
| `document` | [`DocumentInfo`](../types/#documentinfo) | The document’s id, format, path, and Markdown. |
| `stats` | [`ChunkStats`](../types/#chunkstats) | Chunk count, sizes, and time taken. |
| `warnings` | [`ChunkWarning[]`](../types/#chunkwarning) | Problems that didn’t stop chunking. See [Warnings](../warnings/). |
## Throws
[Section titled “Throws”](#throws)
A [`DocchunkError`](../docchunk-error/) with one of these codes:
| Code | When |
| -------------------- | ------------------------------------------------- |
| `INVALID_OPTIONS` | An option or the source is invalid. |
| `UNSUPPORTED_FORMAT` | The format isn’t supported, or can’t be detected. |
| `FILE_NOT_FOUND` | The file at `path` can’t be read. |
| `CONVERSION_FAILED` | The file couldn’t be converted to Markdown. |
| `ABORTED` | `options.signal` was aborted. |
See [Error codes](../error-codes/) for every case.
## Example
[Section titled “Example”](#example)
```ts
import { chunkDocument } from "docchunk";
const { chunks, warnings } = await chunkDocument(
{ path: "handbook.pdf" },
{ strategy: "structure", size: 1000 },
);
```
## See also
[Section titled “See also”](#see-also)
* [Chunk a document](../../guides/chunk-document/): a guide to sources, formats, the result, and errors.
* [Strategies](../../strategies/): the strategies and their options.
# chunkDocuments
> Chunks many documents with shared options and a concurrency limit.
Chunks a list of documents with the same options. A document that fails doesn’t stop the others.
```ts
function chunkDocuments(sources: DocumentSource[], options?: BatchOptions): Promise;
```
## Parameters
[Section titled “Parameters”](#parameters)
| Parameter | Type | Description |
| --------- | ---------------------------------------------- | --------------------------------------------------------------------------------------------- |
| `sources` | [`DocumentSource[]`](../types/#documentsource) | The documents, in any of the shapes `chunkDocument` accepts. |
| `options` | [`BatchOptions`](../types/#batchoptions) | Optional. The same options as `chunkDocument`, applied to every document, plus `concurrency`. |
### `concurrency`
[Section titled “concurrency”](#concurrency)
| Type | Default | Description |
| -------- | ------- | ------------------------------------------------------- |
| `number` | `4` | Documents chunked at the same time. A positive integer. |
## Returns
[Section titled “Returns”](#returns)
A promise of a [`BatchItem[]`](../types/#batchitem), with one item per source, in the same order as `sources`:
| Item | Meaning |
| ---------------------------------------------------------- | ------------------------------------------------------------------- |
| `{ ok: true, result: ChunkResult }` | The document was chunked. `result` is what `chunkDocument` returns. |
| `{ ok: false, error: DocchunkError, sourceIndex: number }` | The document failed. `sourceIndex` is its position in `sources`. |
An empty `sources` array returns an empty array.
## Throws
[Section titled “Throws”](#throws)
A [`DocchunkError`](../docchunk-error/), instead of returning items, in these cases:
| Code | When |
| ----------------- | --------------------------------------------------------------------------------------------------------- |
| `INVALID_OPTIONS` | `sources` isn’t an array, or an option is invalid. Options are checked once, before any document is read. |
| `ABORTED` | `options.signal` was aborted. Results of documents that already finished are not returned. |
Errors from single documents, such as `FILE_NOT_FOUND`, don’t throw. They’re returned as items with `ok: false`.
## Example
[Section titled “Example”](#example)
```ts
import { chunkDocuments } from "docchunk";
const results = await chunkDocuments(
[{ path: "a.docx" }, { path: "b.pdf" }, { path: "notes.md" }],
{ concurrency: 2, metadata: { team: "legal" } },
);
for (const item of results) {
if (item.ok) {
console.log(item.result.document.sourcePath, item.result.chunks.length);
} else {
console.log(`Source ${item.sourceIndex} failed: ${item.error.message}`);
}
}
```
## See also
[Section titled “See also”](#see-also)
* [Chunk many documents](../../guides/chunk-documents/): a guide to batches, concurrency, cancelling, and memory.
# buildChunkTree
> Rebuilds the nested parent and child structure from a flat list of chunks.
Turns a flat list of chunks into a tree, using each chunk’s `parentId`. Use it with the chunks from [`parent-child`](../../strategies/parent-child/) or [`hierarchical`](../../strategies/hierarchical/).
```ts
function buildChunkTree(chunks: Chunk[]): ChunkTreeNode[];
```
## Parameters
[Section titled “Parameters”](#parameters)
| Parameter | Type | Description |
| --------- | ---------------------------- | ---------------------------------------------- |
| `chunks` | [`Chunk[]`](../types/#chunk) | Chunks from one result, or any subset of them. |
## Returns
[Section titled “Returns”](#returns)
The root nodes of the tree, as [`ChunkTreeNode[]`](../types/#chunktreenode). Each node has:
| Field | Type | Description |
| ---------- | ----------------- | ----------------------------------------------------------- |
| `chunk` | `Chunk` | The chunk. |
| `children` | `ChunkTreeNode[]` | Nodes for the chunks whose `parentId` is this chunk’s `id`. |
A chunk is a root when it has no `parentId`, or when its parent isn’t in the list. Roots and children keep the order they have in `chunks`.
`buildChunkTree` doesn’t throw.
## Example
[Section titled “Example”](#example)
```ts
import { buildChunkTree, chunkDocument } from "docchunk";
const { chunks } = await chunkDocument(
{ path: "returns-policy.md" },
{ strategy: "parent-child", parentSize: 300, childSize: 100 },
);
const tree = buildChunkTree(chunks);
for (const node of tree) {
console.log(node.chunk.headingPath.join(" > "));
for (const child of node.children) {
console.log(` ${child.chunk.charCount} chars`);
}
}
```
```txt
Returns policy
71 chars
53 chars
Returns policy > Start a return
89 chars
36 chars
Returns policy > Refunds
95 chars
32 chars
82 chars
```
`returns-policy.md` is the example file used on the [strategy pages](../../strategies/#the-example-document).
## Good to know
[Section titled “Good to know”](#good-to-know)
* **Filtering changes the roots.** If you remove the parents before calling `buildChunkTree`, for example to keep only the children, every remaining chunk becomes a root with no children.
* **Flat strategies give a flat tree.** Chunks from strategies other than `parent-child` and `hierarchical` have no `parentId`, so every chunk is a root.
# DocchunkError
> The error Doc-chunk throws, with a code for each kind of failure.
Every error Doc-chunk throws is a `DocchunkError`. It extends the built-in `Error` with a `code` that tells you what went wrong.
```ts
class DocchunkError extends Error {
readonly code: DocchunkErrorCode;
constructor(code: DocchunkErrorCode, message: string, options?: ErrorOptions);
}
```
## Properties
[Section titled “Properties”](#properties)
| Property | Type | Description |
| --------- | -------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `code` | [`DocchunkErrorCode`](../types/#docchunkerrorcode) | What went wrong: `"INVALID_OPTIONS"`, `"UNSUPPORTED_FORMAT"`, `"CONVERSION_FAILED"`, `"FILE_NOT_FOUND"`, or `"ABORTED"`. |
| `message` | `string` | A description that names the option, file, or format at fault. |
| `name` | `string` | Always `"DocchunkError"`. |
| `cause` | `unknown` | The underlying error, when there is one: the file system error for `FILE_NOT_FOUND`, anydoc’s error for `CONVERSION_FAILED`, or the signal’s `reason` for `ABORTED`. |
[Error codes](../error-codes/) lists every code and when it’s used.
## Handling errors
[Section titled “Handling errors”](#handling-errors)
Check the class with `instanceof`, then branch on `code`. The codes are stable, so you can rely on them in your code. The messages may change between versions.
```ts
import { chunkDocument, DocchunkError } from "docchunk";
try {
const result = await chunkDocument({ path: "report.pdf" });
} catch (error) {
if (!(error instanceof DocchunkError)) {
throw error;
}
if (error.code === "FILE_NOT_FOUND") {
console.log("No such file");
} else if (error.code === "UNSUPPORTED_FORMAT") {
console.log("Doc-chunk can't read this file type");
} else {
console.log(error.code, error.message);
}
}
```
In [`chunkDocuments`](../chunk-documents/), errors for single documents are returned in the result items instead of thrown. Each failed item’s `error` is a `DocchunkError`.
You don’t need to create a `DocchunkError` yourself. The constructor is public so that the class can be used with `instanceof`.
# Options
> Every option of every strategy, with its type, default, and rules.
Options are the second argument of [`chunkDocument`](../chunk-document/) and [`chunkDocuments`](../chunk-documents/). Every option is optional. An option that the chosen strategy doesn’t accept throws an `INVALID_OPTIONS` error, and so does a value that breaks the rules below.
All sizes are in characters.
## Common options
[Section titled “Common options”](#common-options)
These work with every strategy.
| Option | Type | Default | Description |
| --------------- | ------------- | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `strategy` | `string` | `"structure"` | The [strategy](../../strategies/) to use. One of `"structure"`, `"heading"`, `"paragraph"`, `"sentence"`, `"sentence-window"`, `"parent-child"`, `"hierarchical"`, `"recursive"`, `"fixed"`, `"fixed-overlap"`, `"sliding-window"`. |
| `metadata` | `object` | `{}` | Copied onto every chunk’s `metadata`. Doesn’t change chunk ids. Must be an object, not an array. |
| `documentId` | `string` | Hash of the document | Used as `document.id` and in every chunk id. A non-empty string. |
| `headingPrefix` | `boolean` | `false` | Adds the heading path (`A > B > C` and a blank line) to the start of each chunk’s text. Counts toward the size limit. |
| `signal` | `AbortSignal` | None | Stops chunking with an `ABORTED` error when aborted. |
## Strategy options
[Section titled “Strategy options”](#strategy-options)
| Strategy | Option | Type | Default | Rules |
| ------------------------------------------------------ | -------------- | ----------------------- | ------------------------------------------------------ | ----------------------------------------------------------------------- |
| [`structure`](../../strategies/structure/) | `size` | `number` | `1500` | Positive integer. |
| | `minSize` | `number` | `200`, or `size` if smaller | Positive integer, at most `size`. |
| | `overlapChars` | `number` | `0` | Integer from 0, less than `size`. |
| | `headingLevel` | `number` | `3` | Integer from 1 to 6. |
| [`heading`](../../strategies/heading/) | `size` | `number` | No limit | Positive integer. |
| | `headingLevel` | `number` | `3` | Integer from 1 to 6. |
| [`paragraph`](../../strategies/paragraph/) | `size` | `number` | No limit | Positive integer. |
| | `minSize` | `number` | `1` | Positive integer, at most `size`. |
| | `overlapChars` | `number` | `0` | Integer from 0, less than `size`. |
| [`sentence`](../../strategies/sentence/) | `size` | `number` | No limit | Positive integer. |
| | `minSize` | `number` | `1` | Positive integer, at most `size`. |
| | `overlapChars` | `number` | `0` | Integer from 0, less than `size`. |
| [`sentence-window`](../../strategies/sentence-window/) | `windowSize` | `number` | `3` | Integer from 0. |
| [`parent-child`](../../strategies/parent-child/) | `parentSize` | `number` | `4000` | Positive integer. |
| | `childSize` | `number` | `800` | Positive integer, less than `parentSize`. |
| [`hierarchical`](../../strategies/hierarchical/) | `by` | `"size"` or `"heading"` | `"size"` | One of the two values. |
| | `levels` | `number[]` | `[6000, 1500, 400]` | Non-empty array of positive integers, each smaller than the one before. |
| | `headingLevel` | `number` | `3` | Integer from 1 to 6. |
| | `leafSize` | `number` | `1500` | Positive integer. |
| [`recursive`](../../strategies/recursive/) | `size` | `number` | `1500` | Positive integer. |
| | `overlapChars` | `number` | `0` | Integer from 0, less than `size`. |
| | `separators` | `string[]` | `["\n# ", "\n## ", "\n### ", "\n#### ", "\n\n", "\n"]` | Array of non-empty strings. |
| [`fixed`](../../strategies/fixed/) | `size` | `number` | `1500` | Positive integer. |
| | `boundary` | `"word"` or `"char"` | `"word"` | One of the two values. |
| [`fixed-overlap`](../../strategies/fixed-overlap/) | `size` | `number` | `1500` | Positive integer. |
| | `overlapChars` | `number` | `200` | Integer from 0, less than `size`. |
| | `boundary` | `"word"` or `"char"` | `"word"` | One of the two values. |
| [`sliding-window`](../../strategies/sliding-window/) | `size` | `number` | `1500` | Positive integer. |
| | `step` | `number` | `750` | Positive integer, at most `size`. |
| | `boundary` | `"word"` or `"char"` | `"word"` | One of the two values. |
Each strategy page explains what its options do.
### Options that depend on each other
[Section titled “Options that depend on each other”](#options-that-depend-on-each-other)
* **`minSize` and `size`.** `minSize` can’t be larger than `size`. For `structure`, when you set a `size` below 200 and no `minSize`, the default `minSize` becomes equal to `size`.
* **`overlapChars` and `size`.** `overlapChars` must be less than `size`.
* **`childSize` and `parentSize`.** `childSize` must be less than `parentSize`.
* **`step` and `size`.** `step` can’t be larger than `size`.
* **`headingPrefix` and the sizes.** With `headingPrefix`, each size option is reduced by the length of the longest heading path in the document, so that prefixed chunks still fit. If that leaves no room, chunking fails with `INVALID_OPTIONS` after the document is read.
## Batch options
[Section titled “Batch options”](#batch-options)
[`chunkDocuments`](../chunk-documents/) accepts every option above, plus:
| Option | Type | Default | Description |
| ------------- | -------- | ------- | ------------------------------------------------------- |
| `concurrency` | `number` | `4` | Documents chunked at the same time. A positive integer. |
# Types
> Every type Doc-chunk exports.
Doc-chunk exports these types from `docchunk`. Import them with `import type`:
```ts
import type { Chunk, ChunkOptions, ChunkResult } from "docchunk";
```
The definitions below are copied from the source, with their comments.
## Sources
[Section titled “Sources”](#sources)
### `DocumentSource`
[Section titled “DocumentSource”](#documentsource)
```ts
/** Where a document comes from: a file path, bytes, or a string. */
type DocumentSource = PathSource | BytesSource | ContentSource;
```
### `PathSource`
[Section titled “PathSource”](#pathsource)
```ts
/** A document on disk. The format comes from the extension, or from the content. */
interface PathSource {
/** Path to the file. */
path: string;
}
```
### `BytesSource`
[Section titled “BytesSource”](#bytessource)
```ts
/** A document already loaded into memory as bytes. */
interface BytesSource {
/** The file's bytes. */
bytes: Uint8Array;
/** Original file name, used to detect the format from its extension. */
filename?: string;
/** The format, when known. Skips detection. */
format?: DocumentFormat;
}
```
### `ContentSource`
[Section titled “ContentSource”](#contentsource)
```ts
/** Markdown or plain text already in memory as a string. */
interface ContentSource {
/** The document text. */
content: string;
/** Whether `content` is Markdown or plain text. */
format: "markdown" | "text";
}
```
### `DocumentFormat`
[Section titled “DocumentFormat”](#documentformat)
```ts
/** A document format docchunk can read. */
type DocumentFormat =
| "pdf"
| "docx"
| "doc"
| "pptx"
| "ppt"
| "xlsx"
| "xls"
| "odt"
| "ods"
| "odp"
| "rtf"
| "epub"
| "csv"
| "markdown"
| "text";
```
## Options
[Section titled “Options”](#options)
### `ChunkOptions`
[Section titled “ChunkOptions”](#chunkoptions)
The allowed options depend on `strategy`: once you set it, only that strategy’s options are allowed, plus the common options. Without `strategy`, the options of `structure` are allowed. It uses two helper types that are not exported:
```ts
/** Options for one strategy: its name plus only the options that strategy accepts. */
type OptionsForStrategy = {
[Name in StrategyName]: { strategy: Name } & StrategyOptionsByName[Name];
}[StrategyName];
/** Options when no strategy is named: the default strategy, structure, with its options. */
type DefaultStrategyOptions = { strategy?: undefined } & StrategyOptionsByName["structure"];
```
```ts
/** Options for chunkDocument: the strategy and its options, plus the options every strategy shares. */
type ChunkOptions = CommonOptions & (DefaultStrategyOptions | OptionsForStrategy);
```
### `CommonOptions`
[Section titled “CommonOptions”](#commonoptions)
```ts
/** Options shared by every strategy. */
interface CommonOptions {
/** Copied onto every chunk's `metadata`. Does not change chunk ids. Default {}. */
metadata?: Record;
/** Id for the document, used instead of a hash of its Markdown. Changes every chunk id. */
documentId?: string;
/** Prepends the heading path ("A > B > C" and a blank line) to each chunk's text. Counts toward `size`. Default false. */
headingPrefix?: boolean;
/** Stops chunking with an ABORTED error when the signal is aborted. */
signal?: AbortSignal;
}
```
### `StrategyName`
[Section titled “StrategyName”](#strategyname)
```ts
/** Name of a chunking strategy. */
type StrategyName = keyof StrategyOptionsByName;
```
### `StrategyOptionsByName`
[Section titled “StrategyOptionsByName”](#strategyoptionsbyname)
Each strategy’s options, keyed by strategy name. [Options](../options/) lists them in one table, with the rules each value must follow.
```ts
/** Options for each strategy, keyed by strategy name. */
interface StrategyOptionsByName {
/** The default. Packs whole blocks into chunks up to `size`, never across a section. Keeps tables, code, and lists whole when they fit. */
structure: {
/** Maximum characters per chunk. Default 1500. */
size?: number;
/** Chunks smaller than this are merged into a neighbor in the same section when the result fits `size`. Default 200, or `size` if that is smaller. */
minSize?: number;
/** Characters of whole sentences each chunk repeats from the end of the previous chunk in its section. Must be less than `size`. Default 0. */
overlapChars?: number;
/** Headings at this level or higher (1 to 6) start a new section. Default 3. */
headingLevel?: number;
};
/** One chunk per sentence; tables and code blocks count as one sentence. With `size`, packs consecutive sentences. */
sentence: {
/** Maximum characters per chunk. Default: no limit, one sentence per chunk. */
size?: number;
/** Chunks smaller than this are merged into a neighbor in the same section when the result fits `size`. Default 1 (no merging). */
minSize?: number;
/** Characters of whole sentences each chunk repeats from the end of the previous chunk in its section. Default 0. */
overlapChars?: number;
};
/** One chunk per block, with a heading kept with the block after it. With `size`, packs consecutive blocks. */
paragraph: {
/** Maximum characters per chunk. Default: no limit, one block per chunk. */
size?: number;
/** Chunks smaller than this are merged into a neighbor in the same section when the result fits `size`. Default 1 (no merging). */
minSize?: number;
/** Characters of whole sentences each chunk repeats from the end of the previous chunk in its section. Default 0. */
overlapChars?: number;
};
/** One chunk per section, split at headings up to `headingLevel`. With `size`, larger sections are split. */
heading: {
/** Maximum characters per chunk. Default: no limit, one section per chunk. */
size?: number;
/** Headings at this level or higher (1 to 6) start a new section. Default 3. */
headingLevel?: number;
};
/** One chunk per sentence unit, with `contextText` holding the sentences around it in the same section. */
"sentence-window": {
/** Sentence units on each side of the chunk's sentence that go into its contextText. Default 3. */
windowSize?: number;
};
/** Two levels: large parent chunks, each split into small child chunks. Embed children, send parents to the model. */
"parent-child": {
/** Maximum characters per parent chunk. Must be larger than `childSize`. Default 4000. */
parentSize?: number;
/** Maximum characters per child chunk. Default 800. */
childSize?: number;
};
/** Nested chunks at several sizes, or following the heading tree, linked by parentId and childIds. */
hierarchical: {
/** "size": one level per entry in `levels`; "heading": one level per heading depth. Default "size". */
by?: "size" | "heading";
/** Maximum characters per chunk at each level, largest first, each smaller than the one before. Used with by "size". Default [6000, 1500, 400]. */
levels?: number[];
/** Headings at this level or higher (1 to 6) start a new section. Default 3. */
headingLevel?: number;
/** Maximum characters per chunk when a section without subsections is split. Used with by "heading". Default 1500. */
leafSize?: number;
};
/** Cuts the Markdown every `size` characters, ignoring structure. */
fixed: {
/** Maximum characters per chunk. Default 1500. */
size?: number;
/** "word" moves a cut back to whitespace within the last 10% of the chunk; "char" cuts at exactly `size`. Default "word". */
boundary?: "word" | "char";
};
/** Like fixed, but consecutive chunks share `overlapChars` characters. */
"fixed-overlap": {
/** Maximum characters per chunk, including the overlap. Default 1500. */
size?: number;
/** Characters each chunk repeats from the end of the previous one. Must be less than `size`. Default 200. */
overlapChars?: number;
/** "word" moves a cut back to whitespace within the last 10% of the chunk; "char" cuts at exactly `size`. Default "word". */
boundary?: "word" | "char";
};
/** Splits on separators (headings, blank lines, lines), then sentences, then spaces, until pieces fit `size`. */
recursive: {
/** Maximum characters per chunk. Default 1500. */
size?: number;
/** Characters of whole pieces each chunk repeats from the end of the previous one. Must be less than `size`. Default 0. */
overlapChars?: number;
/** Separators tried in order before sentences, spaces, and a hard cut. Default ["\n# ", "\n## ", "\n### ", "\n#### ", "\n\n", "\n"]. */
separators?: string[];
};
/** A window of `size` characters that moves forward `step` characters at a time. */
"sliding-window": {
/** Characters in each window. Default 1500. */
size?: number;
/** Characters the window moves forward each time. At most `size`. Default 750. */
step?: number;
/** "word" moves a cut back to whitespace within the last 10% of the chunk; "char" cuts at exactly `size`. Default "word". */
boundary?: "word" | "char";
};
}
```
### `BatchOptions`
[Section titled “BatchOptions”](#batchoptions)
```ts
/** Options for chunkDocuments: the options for every document, plus how many to chunk at once. */
type BatchOptions = ChunkOptions & {
/** Documents chunked at the same time. Default 4. */
concurrency?: number;
};
```
## Results
[Section titled “Results”](#results)
### `ChunkResult`
[Section titled “ChunkResult”](#chunkresult)
```ts
/** The result of chunking one document. */
interface ChunkResult {
/** The chunks, in order. */
chunks: Chunk[];
/** Information about the document. */
document: DocumentInfo;
/** Summary numbers about the chunks. */
stats: ChunkStats;
/** Problems that did not stop chunking. */
warnings: ChunkWarning[];
}
```
### `Chunk`
[Section titled “Chunk”](#chunk)
```ts
/** One chunk of a document. */
interface Chunk {
/** Stable id: the same document, options, and range always give the same id. */
id: string;
/** The chunk text. */
text: string;
/** Surrounding sentences, for the sentence-window strategy only. */
contextText?: string;
/** Position in the chunk list, starting at 0. Sorted by start offset, then level. */
index: number;
/** Start offset in characters within `document.markdown`. */
start: number;
/** End offset in characters within `document.markdown` (exclusive). */
end: number;
/** Length of `text` in characters. */
charCount: number;
/** Headings above the start of this chunk, outermost first, as plain text. */
headingPath: string[];
/** Block types this chunk touches, in order, without duplicates. */
blockTypes: string[];
/** Id of the chunk that contains this one (parent-child and hierarchical only). */
parentId?: string;
/** Ids of the chunks this one contains (parent-child and hierarchical only). */
childIds?: string[];
/** Nesting level, 0 for the largest chunks (parent-child and hierarchical only). */
level?: number;
/** Hash of `text`, to detect changed chunks. */
contentHash: string;
/** The `metadata` option, copied onto every chunk. */
metadata: Record;
}
```
### `DocumentInfo`
[Section titled “DocumentInfo”](#documentinfo)
```ts
/** Information about the chunked document. */
interface DocumentInfo {
/** The `documentId` option, or a hash of the normalized Markdown. */
id: string;
/** The normalized Markdown that chunk offsets refer to. */
markdown: string;
/** Format of the original document. */
sourceFormat: DocumentFormat;
/** Path of the original file, when the source was a path. */
sourcePath?: string;
/** Length of `markdown` in characters. */
charCount: number;
}
```
### `ChunkStats`
[Section titled “ChunkStats”](#chunkstats)
```ts
/** Summary numbers about the chunks. */
interface ChunkStats {
/** Number of chunks. */
count: number;
/** Characters in the smallest chunk. */
minChars: number;
/** Characters in the largest chunk. */
maxChars: number;
/** Average characters per chunk, rounded to a whole number. */
avgChars: number;
/** Time taken, in milliseconds. */
durationMs: number;
}
```
### `ChunkWarning`
[Section titled “ChunkWarning”](#chunkwarning)
```ts
/** A problem that did not stop chunking. */
interface ChunkWarning {
/** Why the warning was raised. */
code: ChunkWarningCode;
/** Human-readable explanation. */
message: string;
/** Index of the chunk the warning is about, if any. */
chunkIndex?: number;
}
```
### `ChunkWarningCode`
[Section titled “ChunkWarningCode”](#chunkwarningcode)
```ts
/** Why a warning was raised. */
type ChunkWarningCode =
| "NO_TEXT_LAYER"
| "EMPTY_DOCUMENT"
| "LARGE_CHUNK"
| "OVERSIZED_BLOCK";
```
### `BatchItem`
[Section titled “BatchItem”](#batchitem)
One item of the array [`chunkDocuments`](../chunk-documents/) returns. Check `ok` before reading `result` or `error`.
```ts
/** The result for one document in a batch: its chunks, or the error it failed with. */
type BatchItem =
| { ok: true; result: ChunkResult }
| { ok: false; error: DocchunkError; sourceIndex: number };
```
### `ChunkTreeNode`
[Section titled “ChunkTreeNode”](#chunktreenode)
A node of the tree [`buildChunkTree`](../build-chunk-tree/) returns.
```ts
/** A chunk with its child chunks, as built by `buildChunkTree`. */
interface ChunkTreeNode {
/** The chunk. */
chunk: Chunk;
/** Nodes for the chunks this one contains. */
children: ChunkTreeNode[];
}
```
## Errors
[Section titled “Errors”](#errors)
### `DocchunkErrorCode`
[Section titled “DocchunkErrorCode”](#docchunkerrorcode)
The `code` of a [`DocchunkError`](../docchunk-error/). See [Error codes](../error-codes/).
```ts
/** What went wrong, as a stable code callers can check. */
type DocchunkErrorCode =
| "INVALID_OPTIONS"
| "UNSUPPORTED_FORMAT"
| "CONVERSION_FAILED"
| "FILE_NOT_FOUND"
| "ABORTED";
```
# Warnings
> Every warning code: when it happens and what to do about it.
Warnings describe problems that didn’t stop chunking. They’re returned in the result’s `warnings` array. Doc-chunk never logs them.
```ts
interface ChunkWarning {
code: ChunkWarningCode;
message: string;
chunkIndex?: number;
}
```
`chunkIndex` is set when the warning is about one chunk, and is that chunk’s `index`.
## Codes
[Section titled “Codes”](#codes)
| Code | Chunks | `chunkIndex` | When |
| ------------------------------------- | ------ | ------------ | ------------------------------------------------------------------------- |
| [`EMPTY_DOCUMENT`](#empty_document) | None | No | The document has no text. |
| [`NO_TEXT_LAYER`](#no_text_layer) | None | No | A PDF has a page without a text layer, or almost no text. |
| [`OVERSIZED_BLOCK`](#oversized_block) | Normal | Yes | A row, item, line, or word longer than `size` was cut. |
| [`LARGE_CHUNK`](#large_chunk) | Normal | Yes | A strategy with no size limit made a chunk of more than 8,000 characters. |
### `EMPTY_DOCUMENT`
[Section titled “EMPTY\_DOCUMENT”](#empty_document)
The document is empty, or contains only whitespace. The result has no chunks.
Message: `The document has no text to chunk.`
**What to do:** check the source. A Word or PowerPoint file that contains only images also converts to Markdown with little or no text.
### `NO_TEXT_LAYER`
[Section titled “NO\_TEXT\_LAYER”](#no_text_layer)
A PDF has at least one page without a text layer, because it’s scanned or is only an image, or a page mostly covered by an image, or fewer than 100 characters of text in total. The result has no chunks, even if other pages have text. `EMPTY_DOCUMENT` is not added as well. Images on pages that also have text don’t cause this warning: they’re ignored.
Messages:
```txt
This PDF appears to be scanned; OCR is not supported.
This PDF appears to be scanned; OCR is not supported. Pages without a text layer: 3, 4 of 12.
```
The second form lists the pages, when the converter reports them.
**What to do:** Doc-chunk doesn’t do OCR. Run the PDF through an OCR tool, then chunk the text it produces.
### `OVERSIZED_BLOCK`
[Section titled “OVERSIZED\_BLOCK”](#oversized_block)
A single table row, list item, code line, or word was longer than `size`, so it was cut at the size limit instead of at a boundary. The chunk at `chunkIndex` contains one of the pieces.
Message: `Chunk 4 is a hard cut of a row, item, line, or word longer than size.`
**What to do:** usually nothing. This happens with long URLs, base64 data, or minified code. If the pieces are too small to be useful, raise `size`.
### `LARGE_CHUNK`
[Section titled “LARGE\_CHUNK”](#large_chunk)
A strategy without a size limit made a chunk of more than 8,000 characters. This applies to `heading`, `paragraph`, `sentence`, and `sentence-window` without `size`, and to `hierarchical` with `by: "heading"`. Strategies with a size limit never add it.
Message: `Chunk 2 has 12480 characters, more than 8000. Set "size" to split it.`
**What to do:** set `size` to split large sections, paragraphs, or blocks. Most embedding models accept far less than 8,000 characters.
## Check warnings
[Section titled “Check warnings”](#check-warnings)
```ts
import { chunkDocument } from "docchunk";
const { chunks, warnings } = await chunkDocument({ path: "report.pdf" });
for (const warning of warnings) {
console.warn(`${warning.code}: ${warning.message}`);
}
```
# Error codes
> Every error code: when it is thrown and how to handle it.
When Doc-chunk can’t produce a result, it throws a [`DocchunkError`](../docchunk-error/). Its `code` is one of the five below. The messages shown are examples: the parts in angle brackets change with the input.
| Code | Meaning |
| ------------------------------------------- | ------------------------------------------------- |
| [`INVALID_OPTIONS`](#invalid_options) | An option or the source is invalid. |
| [`UNSUPPORTED_FORMAT`](#unsupported_format) | The format isn’t supported, or can’t be detected. |
| [`FILE_NOT_FOUND`](#file_not_found) | A file path can’t be read. |
| [`CONVERSION_FAILED`](#conversion_failed) | A file couldn’t be converted to Markdown. |
| [`ABORTED`](#aborted) | The `signal` was aborted. |
## `INVALID_OPTIONS`
[Section titled “INVALID\_OPTIONS”](#invalid_options)
An option has the wrong type or value, an option isn’t accepted by the chosen strategy, or the source isn’t one of the accepted shapes. Options are checked before the document is read, except for the `headingPrefix` size check, which needs the document’s headings.
Options:
```txt
Options must be an object, got .
Option "strategy" must be one of "structure", "heading", …, got .
Unknown option "" for strategy "".
Option "" must be a positive integer, got .
Option "" must be an integer of 0 or more, got .
Option "" must be an integer from 1 to 6, got .
Option "" must be less than "" (), got .
Option "" must be at most "" (), got .
Option "" must be one of "", "", got .
Option "levels" must be a non-empty array of positive integers, each smaller than the one before, got .
Option "separators" must be an array of non-empty strings, got .
Option "metadata" must be an object, got .
Option "documentId" must be a non-empty string, got .
Option "headingPrefix" must be true or false, got .
Option "signal" must be an AbortSignal, got .
Option "headingPrefix" needs up to characters for heading paths, which leaves no room within "" ().
```
Sources:
```txt
The source must be an object: { path }, { bytes }, or { content, format }.
The source's path must be a non-empty string.
The source's bytes must be a Uint8Array.
The source's filename must be a string.
The source's content must be a string.
The sources must be an array.
```
The last one comes from `chunkDocuments`, as does `Option "concurrency" must be a positive integer`.
**What to do:** fix the option or source named in the message. In TypeScript, most of these are caught by the compiler.
## `UNSUPPORTED_FORMAT`
[Section titled “UNSUPPORTED\_FORMAT”](#unsupported_format)
The format can’t be read.
```txt
Format "" is not supported. Supported formats: pdf, docx, doc, pptx, ppt, xlsx, xls, odt, ods, odp, rtf, epub, csv, markdown, text.
The source's format must be "markdown" or "text".
The document's format could not be detected from its content or file name. Pass `format` to name it.
Could not convert : (unsupported)
```
* The first: the `format` of a bytes source isn’t a supported format.
* The second: a `content` source has a `format` other than `"markdown"` or `"text"`.
* The third: the source has no usable file name or `format`, and its content doesn’t match a known format. This is the usual error for Markdown, text, or CSV passed as bytes without a `filename`.
* The fourth: the converter recognized the file but can’t convert this variant of the format.
**What to do:** pass `format`, or a `filename` with the right extension. See [Formats](../formats/).
## `FILE_NOT_FOUND`
[Section titled “FILE\_NOT\_FOUND”](#file_not_found)
A `path` source couldn’t be read.
```txt
File not found:
Path is a folder, not a file:
File could not be read ():
```
The third form covers other file system errors, such as `EACCES` for missing permissions. `error.cause` holds the original file system error.
**What to do:** check the path. Relative paths are resolved against the current working directory.
## `CONVERSION_FAILED`
[Section titled “CONVERSION\_FAILED”](#conversion_failed)
A file couldn’t be converted to Markdown.
```txt
Could not convert : ()
The anydoc converter could not be loaded. Its native binary may be missing for this platform.
Unexpected error while chunking source :
```
* The first: the converter failed on this file. The code in brackets is the converter’s: `malformed` or `missingPart` for a damaged file, `encrypted` for a password-protected one, and `resourceLimit` for a file that crosses one of the converter’s safety limits, such as its decompression limit. The converter’s error is in `error.cause`.
* The second: the converter’s native binary isn’t available. Binaries exist for macOS, Linux, and Windows x64. Markdown and text files never need the converter.
* The third: only in `chunkDocuments`. An unexpected error inside Doc-chunk is wrapped with this code, so every failed item has a code. The original error is in `error.cause`.
**What to do:** check that the file opens in its usual application. For password-protected files, remove the password first.
## `ABORTED`
[Section titled “ABORTED”](#aborted)
The `signal` option was aborted.
```txt
Chunking was aborted.
```
`error.cause` holds the signal’s `reason`. For `AbortSignal.timeout`, that’s a `TimeoutError`.
**What to do:** nothing, if you aborted on purpose. See [`signal`](../../guides/chunk-document/#signal) for when the signal is checked.
# Formats
> Supported formats, file extensions, and how the format is detected.
## Supported formats
[Section titled “Supported formats”](#supported-formats)
| Format | `format` value | Extensions | Converted | Notes |
| ------------ | ------------------------- | ---------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| PDF | `"pdf"` | `.pdf` | Yes | Text-based PDFs. Images are ignored. A PDF with any page that has no text layer, such as a scanned page, gives a [`NO_TEXT_LAYER`](../warnings/#no_text_layer) warning and no chunks. |
| Word | `"docx"`, `"doc"` | `.docx`, `.doc` | Yes | |
| PowerPoint | `"pptx"`, `"ppt"` | `.pptx`, `.ppt` | Yes | |
| Excel | `"xlsx"`, `"xls"` | `.xlsx`, `.xls` | Yes | Each sheet becomes a Markdown table. |
| OpenDocument | `"odt"`, `"ods"`, `"odp"` | `.odt`, `.ods`, `.odp` | Yes | |
| RTF | `"rtf"` | `.rtf` | Yes | |
| EPUB | `"epub"` | `.epub` | Yes | |
| CSV | `"csv"` | `.csv` | Yes | Becomes a Markdown table. Needs a `.csv` file name or `format: "csv"`. |
| Markdown | `"markdown"` | `.md`, `.markdown` | No | Parsed as GitHub-Flavored Markdown. |
| Plain text | `"text"` | `.txt` | No | Split into paragraphs at blank lines. `#`, `*`, and other Markdown characters stay as text. |
The `format` value is what you pass in a source, and what `document.sourceFormat` contains.
## Detection
[Section titled “Detection”](#detection)
For a `path` or `bytes` source, the format is the first of these that gives an answer:
1. The source’s `format`.
2. A file name ending in `.md`, `.markdown`, `.txt`, or `.csv`: from `path`, or from `filename` for bytes.
3. The file’s content. PDF, Office, OpenDocument, EPUB, and RTF files are recognized by their content, so a missing or wrong extension doesn’t matter.
4. The file’s extension, for the other formats.
If none gives an answer, Doc-chunk throws an [`UNSUPPORTED_FORMAT`](../error-codes/#unsupported_format) error. Markdown, text, and CSV have no recognizable content, so as bytes they need a `filename` or a `format`.
A `content` source always has a `format` of `"markdown"` or `"text"`, so there is no detection.
## Conversion
[Section titled “Conversion”](#conversion)
Every format except Markdown and plain text is converted to Markdown by [`@firecrawl/anydoc`](https://github.com/firecrawl/anydoc), which runs locally:
* Headings, lists, tables, and footnotes come out in the same Markdown form whatever the format, so every strategy works the same way on all of them.
* Embedded images are replaced by their alt text, if they have any. Images linked by URL stay as Markdown images.
* Password-protected, damaged, and extremely large files fail with a [`CONVERSION_FAILED`](../error-codes/#conversion_failed) error.
* anydoc uses native binaries, available for macOS, Linux (glibc and musl), and Windows x64. On other platforms, such as Windows on ARM, only Markdown and plain text can be chunked.
* anydoc is loaded the first time a document needs converting, so Markdown and text never load it.
Doc-chunk never uses anydoc’s hosted OCR option, so documents are never sent over the network.
The converted Markdown is `document.markdown` in the result, and chunk positions refer to it.
# Agent skill
> A skill file that teaches AI coding agents how to use Doc-chunk.
The Doc-chunk skill is a single `SKILL.md` file that tells an AI coding agent how to use the library: how to install it, which strategy to choose, working examples, the error codes, and the mistakes to avoid. With the skill installed, the agent writes correct Doc-chunk code without searching the web or guessing the API.
The file follows the Agent Skills format: Markdown with a short header that tells the agent when to use it. Agents that support skills load it only when a task involves chunking documents.
## Install the skill
[Section titled “Install the skill”](#install-the-skill)
The skill is one file. Copy it from [the end of this page](#the-skill-file), or download it into your project with the commands below.
* Claude Code (project)
Install the skill for everyone working on this project. Commit the file so the whole team gets it.
```sh
mkdir -p .claude/skills/docchunk
curl -fsSL https://thismesandeep.github.io/docchunk/skill/SKILL.md -o .claude/skills/docchunk/SKILL.md
```
* Claude Code (personal)
Install the skill for all your projects.
```sh
mkdir -p ~/.claude/skills/docchunk
curl -fsSL https://thismesandeep.github.io/docchunk/skill/SKILL.md -o ~/.claude/skills/docchunk/SKILL.md
```
* Other agents
For another agent that supports Agent Skills, create a `docchunk` folder in the folder where that agent looks for skills, and save the file in it as `SKILL.md`. Check your agent’s documentation for the location.
For an agent that doesn’t support skills, copy the file’s content, without the header between the `---` lines, into the agent’s instructions file, such as `AGENTS.md`, `CLAUDE.md`, or a Cursor rules file.
Restart the agent, or start a new session, so it finds the new skill. To check that it works, ask the agent something like “Chunk the PDFs in ./docs with docchunk and save the chunks as JSON”.
## What the skill contains
[Section titled “What the skill contains”](#what-the-skill-contains)
* Installation and runtime requirements.
* The three kinds of source, and the fields of the result.
* A table of all 11 strategies, with the goal each one suits and its options.
* Examples for common tasks: setting the size, chunking a string, parent-child retrieval, batches, and re-indexing.
* The error and warning codes.
* The mistakes agents make most often, such as treating sizes as tokens or passing `documentId` to a batch.
* A link to [`llms-full.txt`](../llms-txt/), for anything the skill doesn’t cover.
## Keep it up to date
[Section titled “Keep it up to date”](#keep-it-up-to-date)
The skill describes the current version of Doc-chunk. After you upgrade the library, download the skill again with the same command.
## The skill file
[Section titled “The skill file”](#the-skill-file)
Hover over the code block and select the copy button in its top right corner, or [download `SKILL.md`](../../../skill/SKILL.md).
SKILL.md
````md
---
name: docchunk
description: Split documents into chunks for RAG and embeddings with the docchunk TypeScript library on Node.js 22.12+ or Bun. Use when writing code that chunks PDF, Word, PowerPoint, Excel, OpenDocument, RTF, EPUB, CSV, Markdown, or plain text files, chooses a chunking strategy, or indexes documents into a vector database with docchunk.
---
# docchunk
docchunk turns documents into chunks ready for embedding. It runs locally: no API key, no network requests, no telemetry. PDFs and Office files are converted to Markdown by `@firecrawl/anydoc`; Markdown and plain text are read directly.
Full documentation as one Markdown file: https://thismesandeep.github.io/docchunk/llms-full.txt
## Install
```sh
npm install docchunk # or: pnpm add docchunk, yarn add docchunk, bun add docchunk
```
Requires Node.js 22.12 or later, or Bun 1.x. Works with `import` and `require`. Types are included.
## Basic use
```ts
import { chunkDocument } from "docchunk";
const result = await chunkDocument({ path: "handbook.pdf" });
for (const chunk of result.chunks) {
console.log(chunk.id, chunk.headingPath, chunk.text);
}
```
With no options, the `structure` strategy is used with chunks of up to 1,500 characters.
## Sources
The first argument is one of:
| Source | Use for |
|---|---|
| `{ path }` | A file on disk. |
| `{ bytes, filename?, format? }` | A file in memory, as a `Uint8Array` or `Buffer`. |
| `{ content, format }` | A string. `format` is `"markdown"` or `"text"`. |
Supported formats: `pdf`, `docx`, `doc`, `pptx`, `ppt`, `xlsx`, `xls`, `odt`, `ods`, `odp`, `rtf`, `epub`, `csv`, `markdown`, `text`.
## Result
`chunkDocument` returns `{ chunks, document, stats, warnings }`.
- Each chunk has `id` (stable), `text` (Markdown, what you embed), `index`, `start`, `end`, `charCount`, `headingPath` (headings above the chunk), `blockTypes`, `contentHash` (hash of `text`), and `metadata`.
- `sentence-window` chunks also have `contextText`. `parent-child` and `hierarchical` chunks also have `level`, `parentId`, and `childIds`.
- `document` has `id`, `markdown` (the text that `start` and `end` point into), `sourceFormat`, `sourcePath`, and `charCount`.
- `stats` has `count`, `minChars`, `maxChars`, `avgChars`, and `durationMs`.
- `warnings` is an array of `{ code, message, chunkIndex? }`. docchunk never logs them.
## Choosing a strategy
Pass `strategy` and that strategy's options as the second argument. Start with `structure`.
| Goal | Strategy | Options (defaults) |
|---|---|---|
| General-purpose chunks | `structure` | `size` (1500), `minSize` (200, or `size` if smaller), `overlapChars` (0), `headingLevel` (3) |
| One chunk per section | `heading` | `size` (no limit), `headingLevel` (3) |
| One chunk per paragraph, list, or table | `paragraph` | `size` (no limit), `minSize` (1), `overlapChars` (0) |
| One chunk per sentence | `sentence` | `size` (no limit), `minSize` (1), `overlapChars` (0) |
| Sentences for search, neighbors as context | `sentence-window` | `windowSize` (3) |
| Small chunks for search, large parents for the model | `parent-child` | `parentSize` (4000), `childSize` (800) |
| Three or more nested sizes, or a chunk per section and subsection | `hierarchical` | `by` ("size"), `levels` ([6000, 1500, 400]), `headingLevel` (3), `leafSize` (1500) |
| Match a recursive character splitter | `recursive` | `size` (1500), `overlapChars` (0), `separators` |
| Fixed-length cuts, ignoring structure | `fixed` | `size` (1500), `boundary` ("word") |
| Fixed-length cuts with overlap | `fixed-overlap` | `size` (1500), `overlapChars` (200), `boundary` ("word") |
| Overlapping windows | `sliding-window` | `size` (1500), `step` (750), `boundary` ("word") |
`structure` packs whole paragraphs, lists, tables, and code blocks up to `size`, never puts two sections in one chunk, and splits a block that is too large by rows, items, lines, or sentences.
Options every strategy accepts: `metadata` (copied onto every chunk), `documentId` (used in chunk ids instead of a hash of the content), `headingPrefix` (adds `A > B > C` and a blank line to the start of each chunk's text), and `signal` (an `AbortSignal`).
## Examples
Set the size:
```ts
import { chunkDocument } from "docchunk";
const { chunks } = await chunkDocument({ path: "manual.docx" }, { size: 1000 });
```
Markdown from a string:
```ts
import { chunkDocument } from "docchunk";
const markdown = "# Guide\n\nFirst paragraph.\n\n## Setup\n\nInstall the package.";
const { chunks } = await chunkDocument({ content: markdown, format: "markdown" });
```
Parent-child retrieval: embed the children, send a matching child's parent to the model.
```ts
import { chunkDocument } from "docchunk";
const { chunks } = await chunkDocument({ path: "policy.pdf" }, { strategy: "parent-child" });
const children = chunks.filter((chunk) => chunk.level === 1);
const chunksById = new Map(chunks.map((chunk) => [chunk.id, chunk]));
for (const child of children) {
const parent = chunksById.get(child.parentId ?? "");
console.log(child.text.length, parent?.text.length);
}
```
Many documents. One failed document doesn't stop the others:
```ts
import { chunkDocuments } from "docchunk";
const results = await chunkDocuments(
[{ path: "a.docx" }, { path: "b.pdf" }, { path: "notes.md" }],
{ concurrency: 4 },
);
for (const item of results) {
if (item.ok) {
console.log(item.result.document.sourcePath, item.result.chunks.length);
} else {
console.log(`Source ${item.sourceIndex} failed: ${item.error.code}`);
}
}
```
Re-index only what changed: compare `contentHash` with the stored value.
```ts
import { chunkDocument } from "docchunk";
const storedHashes = new Set(); // load from your vector database
const { chunks } = await chunkDocument(
{ path: "docs/returns.md" },
{ documentId: "docs/returns.md" },
);
const changed = chunks.filter((chunk) => !storedHashes.has(chunk.contentHash));
```
## Errors and warnings
Errors are thrown as `DocchunkError`, with a `code`:
| Code | When |
|---|---|
| `INVALID_OPTIONS` | Bad option value, an option the strategy doesn't accept, or a malformed source. |
| `UNSUPPORTED_FORMAT` | Unknown format, or the format can't be detected. |
| `FILE_NOT_FOUND` | The `path` doesn't exist, is a folder, or can't be read. |
| `CONVERSION_FAILED` | The converter failed (damaged or password-protected file), or isn't available on this platform. |
| `ABORTED` | The `signal` was aborted. |
```ts
import { chunkDocument, DocchunkError } from "docchunk";
try {
await chunkDocument({ path: "report.pdf" });
} catch (error) {
if (error instanceof DocchunkError) {
console.log(error.code, error.message);
}
}
```
Warnings: `EMPTY_DOCUMENT` (no text, no chunks), `NO_TEXT_LAYER` (scanned PDF, no chunks), `OVERSIZED_BLOCK` (a row, item, line, or word longer than `size` was cut), `LARGE_CHUNK` (a strategy without a size limit made a chunk over 8,000 characters).
## Pitfalls
- Sizes are in characters, not tokens. For English prose, use about 3 characters per token: `size: 1500` for a 512-token embedding model. Use less for code and non-Latin scripts.
- Options are specific to the strategy. An option the chosen strategy doesn't accept throws `INVALID_OPTIONS`, and TypeScript flags it.
- Markdown, text, and CSV passed as `bytes` need a `filename` with the extension, or a `format`. Otherwise `UNSUPPORTED_FORMAT` is thrown.
- No OCR. Images on pages with text are ignored, but a PDF with any page that has no text layer (scanned, or only an image) returns no chunks and a `NO_TEXT_LAYER` warning. Always check `result.warnings`.
- With `noUncheckedIndexedAccess`, `chunks[0]` has type `Chunk | undefined`. Use `for...of`, or check for `undefined`.
- Don't pass `documentId` to `chunkDocuments`: every document would get the same id, and chunk ids would collide. For per-document ids, call `chunkDocument` for each document.
- Without `documentId`, two files with the same content get the same chunk ids, and any edit changes every chunk id. Pass a stable `documentId`, such as the file path, when storing chunks from many documents.
- `sentence` and `sentence-window` leave headings out of `text`. Use `headingPath` or `headingPrefix: true` to keep them.
- Not supported: browsers, Deno, HTML input, token-based sizes, and semantic (embedding-based) chunking.
````
# Setup prompt
> A prompt that has an AI agent install Doc-chunk and add a working example to your project.
Copy one of these prompts into your AI coding agent, such as Claude Code, Cursor, or Codex. The agent reads the Doc-chunk documentation, installs the library, writes the code, runs it on a real document, and shows you the result.
Choose the prompt that matches your project:
* **Add to an existing pipeline** when your project already embeds documents, and you want Doc-chunk to do the splitting.
* **Start from scratch** when you want a script that turns a folder of documents into chunks.
- Add to an existing pipeline
```txt
Add the docchunk library to this project's RAG pipeline, to split documents into chunks before they are embedded.
Read the documentation first: https://thismesandeep.github.io/docchunk/llms-full.txt
1. Find where this project loads documents and splits them before embedding. Tell me what you found, and your plan, before changing any code.
2. Check the runtime. docchunk needs Node.js 22.12 or later, or Bun 1.x. If the project uses something else, stop and tell me.
3. Install docchunk with the package manager this project already uses. Look at the lockfile to find it.
4. Replace the current splitting code with chunkDocument, or chunkDocuments for many files. Keep the existing embedding and storage code.
5. Choose the strategy. Use "structure", the default, unless the pipeline searches small chunks and sends larger context to the model; then use "parent-child". Set the size from the embedding model's token limit, at about 3 characters per token.
6. Store chunk.id as the record id, and chunk.headingPath and chunk.contentHash as metadata. Pass a stable documentId for each file, such as its path, and call chunkDocument once per file when you do.
7. Log result.warnings, and handle DocchunkError by its code.
8. Run the pipeline on one real document from this project. Show me the number of chunks, the first two chunks, and any warnings.
Change the embedding and storage code only where the new chunks require it.
```
- Start from scratch
```txt
Set up the docchunk library in this project, to turn documents into chunks for RAG.
Read the documentation first: https://thismesandeep.github.io/docchunk/llms-full.txt
My documents and goal:
1. Check the runtime. docchunk needs Node.js 22.12 or later, or Bun 1.x. If the project uses something else, stop and tell me.
2. Install docchunk with the package manager this project already uses. Look at the lockfile to find it. If there is none, use npm.
3. Choose the strategy for my goal from the "Which strategy to use" table in the documentation. Explain the choice in one sentence.
4. Write a script, in TypeScript or JavaScript to match the project, that finds every supported file in a folder (default: ./documents), chunks them with chunkDocuments, and writes the chunks to chunks.json. Save each chunk's id, text, headingPath, contentHash, and the path of its source file.
5. Print the warnings, and the files that failed with their error codes.
6. Run the script. If the folder is empty, create one short Markdown file in it first. Show me the number of chunks per file, and the first chunk.
Keep the script short and easy to read.
```
## Tips
[Section titled “Tips”](#tips)
* **Fill in your goal.** In the second prompt, replace the text in angle brackets. For example: “PDF contracts, searched by a support chatbot that uses a 512-token embedding model”. The agent uses it to choose the strategy and size.
* **Install the skill as well.** With the [agent skill](../agent-skill/) installed, the agent keeps using Doc-chunk correctly in later tasks, not only during setup.
* **Check the plan.** The first prompt asks the agent to describe its plan before it changes code. Read it, especially what it will replace.
# llms.txt
> The documentation as plain Markdown files, ready to give to an LLM.
The Doc-chunk documentation is also published as plain Markdown files, following the [llms.txt](https://llmstxt.org) convention. Give one of them to an LLM or an AI coding agent, and it has the whole documentation in a form it reads easily, without navigation, scripts, or styling.
## The files
[Section titled “The files”](#the-files)
| File | Contents |
| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| [`/llms.txt`](https://thismesandeep.github.io/docchunk/llms.txt) | A short index: what Doc-chunk is, key facts, and links to the other files. |
| [`/llms-full.txt`](https://thismesandeep.github.io/docchunk/llms-full.txt) | The complete documentation in one file, in the same order as the site. |
| [`/llms-small.txt`](https://thismesandeep.github.io/docchunk/llms-small.txt) | A shorter version of the complete documentation, without notes and with less whitespace. |
`llms.txt` also links to three smaller files, each with one part of the documentation:
| File | Contents |
| --------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
| [Getting started and guides](https://thismesandeep.github.io/docchunk/_llms-txt/getting-started-and-guides.txt) | Introduction, Quickstart, How it works, and the two guides. |
| [Strategies](https://thismesandeep.github.io/docchunk/_llms-txt/strategies.txt) | The 11 strategies, their options, and examples. |
| [Reference](https://thismesandeep.github.io/docchunk/_llms-txt/reference.txt) | Functions, options, types, warnings, error codes, and formats. |
All the files are generated from the documentation every time the site is built, so they always match it.
## Which file to use
[Section titled “Which file to use”](#which-file-to-use)
* **`llms-full.txt`** for coding agents and for questions about any part of Doc-chunk. It fits easily in the context of current models.
* **One of the smaller files** when you only need one part, such as the reference, or want to leave more room in the context.
* **`llms.txt`** for tools that follow links themselves, starting from an index.
## How to use them
[Section titled “How to use them”](#how-to-use-them)
* **In a chat:** paste the link to `llms-full.txt` into your message, if the tool can read web pages. Otherwise, download the file and attach it.
* **In a coding agent:** tell the agent to read `https://thismesandeep.github.io/docchunk/llms-full.txt` before it writes Doc-chunk code. The [setup prompt](../setup-prompt/) does this for you.
* **In an editor that indexes documentation,** such as Cursor, add the site’s address as a documentation source.
For agents you use regularly, the [agent skill](../agent-skill/) is usually a better fit: the agent loads it automatically when a task involves chunking, and it’s much shorter than the full documentation.
# Limitations
> What Doc-chunk does not do, and what to use instead.
Doc-chunk does one job: it turns documents into chunks, on your machine. This page lists what it doesn’t do, so you can decide early whether it fits your project, and what to do instead.
## Input
[Section titled “Input”](#input)
### No OCR
[Section titled “No OCR”](#no-ocr)
Doc-chunk reads the text layer of a PDF. It doesn’t recognize text in images. Pages that have text work as usual, and any images on them are ignored. But if a page has no text layer, because it’s scanned or is only an image, the converter rejects the whole PDF: you get no chunks, even from the other pages, and a [`NO_TEXT_LAYER`](../reference/warnings/#no_text_layer) warning. The same happens with a page that is mostly covered by an image.
**Instead:** run scanned documents through an OCR tool first, then pass the text to Doc-chunk as `content`.
### Images are left out
[Section titled “Images are left out”](#images-are-left-out)
Images in Word files, slides, and PDFs aren’t described or read. An embedded image is replaced by its alt text, if it has any.
**Instead:** if images carry important content, describe them with a vision model, and add the descriptions to the text before chunking.
### No HTML input
[Section titled “No HTML input”](#no-html-input)
Web pages aren’t a supported format.
**Instead:** convert the HTML to Markdown with an HTML-to-Markdown library, then pass it as `{ content, format: "markdown" }`.
### No page or slide numbers
[Section titled “No page or slide numbers”](#no-page-or-slide-numbers)
Chunks don’t record the page or slide they came from. The converted Markdown has no page markers.
**Instead:** if you need page numbers, split the document into pages yourself, chunk each page’s text separately, and add the page number with the `metadata` option.
## Sizes
[Section titled “Sizes”](#sizes)
### Sizes are in characters, not tokens
[Section titled “Sizes are in characters, not tokens”](#sizes-are-in-characters-not-tokens)
There is no tokenizer, and no way to measure chunks with a custom function. A chunk that fits within `size` characters can still go over a token limit, especially for code or text that doesn’t use the Latin alphabet.
**Instead:** leave a margin. For English prose, about 3 characters per token keeps chunks within the limit: a `size` of 1,500 for a model that accepts 512 tokens. If a limit must never be exceeded, count the tokens of each chunk after chunking.
### Sentence boundaries use English rules
[Section titled “Sentence boundaries use English rules”](#sentence-boundaries-use-english-rules)
Sentences are found with `Intl.Segmenter`, set to English for every document, so the chunks are the same on every machine. It can end a sentence after an abbreviation such as “Dr.” or “e.g.”, and may split text in other languages less accurately.
**Instead:** strategies that pack sentences up to a size, such as `structure` or `sentence` with `size`, hide most of these splits.
## Runtimes and platforms
[Section titled “Runtimes and platforms”](#runtimes-and-platforms)
### Node.js and Bun only
[Section titled “Node.js and Bun only”](#nodejs-and-bun-only)
Doc-chunk needs Node.js 22.12 or later, or Bun 1.x. It doesn’t run in browsers, in Deno, or in edge runtimes such as Cloudflare Workers.
**Instead:** chunk documents on a server or in a build step, and send the chunks where you need them.
### Conversion needs a supported platform
[Section titled “Conversion needs a supported platform”](#conversion-needs-a-supported-platform)
PDFs and Office files are converted by a native binary, available for macOS, Linux (glibc and musl), and Windows x64. On other platforms, such as Windows on ARM, Doc-chunk can chunk Markdown and plain text, but converting other formats fails with `CONVERSION_FAILED`.
## Scope
[Section titled “Scope”](#scope)
### No embeddings or vector databases
[Section titled “No embeddings or vector databases”](#no-embeddings-or-vector-databases)
Doc-chunk doesn’t create embeddings, call language models, or connect to vector databases. It gives you chunks, and you store them with the tools you already use.
### No semantic chunking
[Section titled “No semantic chunking”](#no-semantic-chunking)
Chunks follow the document’s structure and size limits. Doc-chunk doesn’t use embeddings to find where topics change.
### No streaming
[Section titled “No streaming”](#no-streaming)
The whole document is converted and parsed in memory before any chunk is returned. Parsing uses about 200 to 240 times the size of the text: roughly 250 MB for 1 MB of Markdown. See [Performance](../performance/).
**Instead:** for very large files, lower `concurrency` in `chunkDocuments`, or split the file before chunking.
### No custom strategies
[Section titled “No custom strategies”](#no-custom-strategies)
The 11 strategies are built in. You can’t register your own yet.
## Cancelling
[Section titled “Cancelling”](#cancelling)
A [`signal`](../guides/chunk-document/#signal) is checked between the steps of chunking, so a step that has started, such as converting a large PDF, runs to the end first. In `chunkDocuments`, the signal is also checked before each document. See [Cancel a batch](../guides/chunk-documents/#cancel-a-batch).
# Privacy
> What fully local means, and how the tests enforce it.
Doc-chunk is fully local: your documents never leave your machine. This page explains what that means in practice, and how the project checks it.
## What fully local means
[Section titled “What fully local means”](#what-fully-local-means)
* **No network requests.** The library doesn’t import any network module, and doesn’t call `fetch`.
* **No API keys or accounts.** There is no service to sign up for.
* **Local conversion.** PDFs and Office files are converted by a native binary that runs in your process.
* **No telemetry.** Doc-chunk doesn’t collect usage data or send error reports.
* **No update checks.** Doc-chunk never checks for new versions.
## Conversion and OCR
[Section titled “Conversion and OCR”](#conversion-and-ocr)
Conversion is done by [`@firecrawl/anydoc`](https://github.com/firecrawl/anydoc), which runs on your machine. anydoc has an optional hosted OCR mode that sends scanned documents to Firecrawl’s servers. It’s off unless a caller turns it on with an option.
Doc-chunk calls anydoc without any options, so the hosted OCR mode is never used. When a PDF has scanned pages, you get a `NO_TEXT_LAYER` warning and no chunks, instead of the document being sent anywhere.
Markdown and plain text never reach anydoc at all: the converter isn’t even loaded for them.
## How it’s enforced
[Section titled “How it’s enforced”](#how-its-enforced)
Three checks run on every commit, in continuous integration, on Node.js 22, Node.js 24, and Bun:
1. **A source check.** A script scans every file in `src/` and fails if any imports `node:net`, `node:http`, `node:https`, or `node:tls`, or mentions `fetch`.
2. **Tests without a network.** Every test runs with the network APIs blocked: `fetch`, `XMLHttpRequest`, `WebSocket`, and the connection functions of `node:net`, `node:http`, `node:https`, and `node:tls`. Any attempt to use them throws and fails the test. The conversion tests, which convert real PDF, Word, PowerPoint, Excel, OpenDocument, RTF, EPUB, and CSV files, pass under these conditions.
3. **A loading test.** A test checks that chunking Markdown and plain text never loads anydoc.
These checks cover JavaScript. They can’t see inside anydoc’s native binary. According to anydoc’s documentation, it only uses the network in hosted OCR mode, which Doc-chunk never turns on.
## What you can check yourself
[Section titled “What you can check yourself”](#what-you-can-check-yourself)
* The library has four runtime dependencies: `@firecrawl/anydoc`, and three packages that parse Markdown (`mdast-util-from-markdown`, `mdast-util-gfm`, and `micromark-extension-gfm`).
* To see the checks, look at `scripts/check-no-network.ts` and `test/setup/no-network.ts` in the repository.
* To confirm it yourself, run Doc-chunk with networking disabled, for example in a container started with `--network none`.
# Performance
> Measured speed and memory use, and how to run the benchmarks.
This page gives measured chunking times and memory use, explains what they depend on, and shows how to run the benchmarks yourself.
## Speed
[Section titled “Speed”](#speed)
Times to chunk 1 MB of Markdown already in memory. Converting a PDF or Office file to Markdown comes on top of this.
| Input | Strategy | Node.js 24 | Bun |
| ----------------------------------------------- | ------------------------------- | ------------ | ------------ |
| 1 MB of prose | `structure` (default) | 0.5 s | 0.7 s |
| 1 MB of prose | each of the other 10 strategies | 0.5 to 0.7 s | 0.5 to 0.6 s |
| 1 MB of one table, like a converted spreadsheet | `structure` (default) | 1.9 s | 1.8 s |
The prose is a real article repeated to 1 MB. The table has five columns and about 18,000 rows.
Times vary with the machine, so treat these as a guide to the relative cost, and run the benchmarks on your own hardware for absolute numbers.
## Memory
[Section titled “Memory”](#memory)
While chunking 1 MB of prose with the default strategy, the process’s peak memory grew by 210 MB on Bun and 250 MB on Node.js: 200 to 240 times the size of the text. Memory use grows with the size of the document.
When you chunk several documents at once with [`chunkDocuments`](../guides/chunk-documents/#large-files), each document in progress needs its own memory. For large files, lower `concurrency`.
## Where the time goes
[Section titled “Where the time goes”](#where-the-time-goes)
Almost all of the time and memory goes to parsing the Markdown into a syntax tree, which happens once per document, for every strategy. That’s why all strategies take about the same time, and why the time for parsing alone is about the same as for the whole `structure` strategy.
Tables are slower than prose, because a megabyte of table has far more cells, and so far more parts to parse, than a megabyte of paragraphs.
For typical documents, from a few pages to a few hundred, chunking takes milliseconds to a fraction of a second. Conversion time depends on the file, and is usually the larger part for PDFs and Office files.
## Run the benchmarks
[Section titled “Run the benchmarks”](#run-the-benchmarks)
The benchmarks are in `bench/run.ts` in the repository. From a clone of the repository:
```sh
bun install
bun run bench # on Bun
bun run bench:node # on Node.js
```
They print the peak memory growth for the default strategy, then the time per run and per megabyte for each task.
# Contributing
> Set up the project, follow its code rules, and run the tests.
Doc-chunk is open source under the MIT license. Bug reports, fixes, and improvements to the documentation are welcome on [GitHub](https://github.com/thisMeSandeep/docchunk).
## Development setup
[Section titled “Development setup”](#development-setup)
You need [Bun](https://bun.sh) for development, and Node.js 22.12 or later to run the tests on Node.
```sh
git clone https://github.com/thisMeSandeep/docchunk.git
cd docchunk
bun install
```
### Scripts
[Section titled “Scripts”](#scripts)
| Command | What it does |
| ----------------------- | ----------------------------------------------------------------------- |
| `bun run test` | Runs the tests on Bun. |
| `bun run test:node` | Runs the tests on Node.js. |
| `bun run typecheck` | Type-checks the source and tests. |
| `bun run lint` | Checks formatting and lint rules with Biome. |
| `bun run check:network` | Fails if the source uses the network. See [Privacy](../privacy/). |
| `bun run build` | Builds the package into `dist/` (ESM, CommonJS, and type declarations). |
| `bun run bench` | Runs the benchmarks. See [Performance](../performance/). |
| `bun run docs:dev` | Starts the documentation site. Run `bun install` in `website/` first. |
## Before you open a pull request
[Section titled “Before you open a pull request”](#before-you-open-a-pull-request)
Run the same checks as continuous integration:
```sh
bun run typecheck && bun run lint && bun run check:network && bun run test && bun run test:node
```
CI runs them on Node.js 22, Node.js 24, and Bun. A change is ready when they all pass.
## Tests
[Section titled “Tests”](#tests)
Tests use Vitest, so the same tests run on Node.js and on Bun. Add tests with every change.
* **Unit tests** live in `test/`, in folders that match `src/`.
* **Property tests** in `test/properties.test.ts` use fast-check to generate many random documents, including other languages and emoji, and check rules that must always hold: no chunk is larger than `size`, all the text ends up in chunks, no chunk crosses a section, and the same input always gives the same output.
* **Snapshot tests** chunk every fixture file with every strategy, and compare the result, including ids, with the files in `test/snapshots/`. They must match on every runtime.
* **README tests** run every TypeScript example in `README.md` against the source.
* **Package test** builds the package and loads it with both `import` and `require`.
### Updating snapshots
[Section titled “Updating snapshots”](#updating-snapshots)
A change that is meant to change chunk boundaries or ids makes the snapshot tests fail. Update the snapshots with:
```sh
bun run test -- -u
```
Check the changed files in `test/snapshots/` before you commit them, and explain in the commit message why the output changed. A changed id means users have to re-embed their documents, so treat it as a breaking change.
## Code rules
[Section titled “Code rules”](#code-rules)
The code is written to be read by someone new to the project. The full rules are in `CLAUDE.md` in the repository. In short:
* **Plain functions.** The only class is `DocchunkError`. No factories, base classes, or generic utility layers. The strategy registry is the one internal pattern.
* **Small units.** Functions under about 40 lines, files under about 250 lines.
* **Obvious code.** Plain `for` loops and early returns, named intermediate values, and full-word names. Boolean names start with `is`, `has`, or `should`.
* **Strict types.** No `any`, no non-null assertions (`!`), and no `as` casts unless unavoidable, with a comment saying why.
* **Short comments.** One line at the top of every file, and one line of JSDoc above every function, saying what it does.
* **File names** in kebab-case, named after what they contain. One strategy per file.
* **No network code** in `src/`, and no new dependencies without a recorded reason.
## Changesets
[Section titled “Changesets”](#changesets)
Changes that affect users need a changeset, which describes the change for the changelog and sets the version bump:
```sh
bun run changeset
```
Choose the bump: `patch` for fixes, `minor` for new features, and `major` for breaking changes, including any change to chunk ids or boundaries.
## Documentation
[Section titled “Documentation”](#documentation)
The documentation site is in `website/`, built with Astro and Starlight. Pages are MDX files in `website/src/content/docs/docs/`. Every example output shown on the site should come from a real run.