Reference: functions, options, types, warnings, error codes, and formats
# 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.