(content: string)
| 108 | } |
| 109 | |
| 110 | async chunk(content: string): Promise<Chunk[]> { |
| 111 | if (!content?.trim()) { |
| 112 | return [] |
| 113 | } |
| 114 | |
| 115 | const cleaned = cleanText(content) |
| 116 | |
| 117 | if (!this.strictBoundaries && estimateTokens(cleaned) <= this.chunkSize) { |
| 118 | logger.info('Content fits in single chunk') |
| 119 | return buildChunks([cleaned], 0) |
| 120 | } |
| 121 | |
| 122 | this.regex.lastIndex = 0 |
| 123 | const segments = cleaned.split(this.regex).filter((s) => s.trim().length > 0) |
| 124 | |
| 125 | if (segments.length <= 1) { |
| 126 | if (this.strictBoundaries) { |
| 127 | logger.info('Regex pattern produced no splits in strict mode, returning single chunk') |
| 128 | return buildChunks([cleaned.trim()], 0) |
| 129 | } |
| 130 | logger.warn( |
| 131 | 'Regex pattern did not produce any splits, falling back to word-boundary splitting' |
| 132 | ) |
| 133 | const chunkSizeChars = tokensToChars(this.chunkSize) |
| 134 | let chunks = splitAtWordBoundaries(cleaned, chunkSizeChars) |
| 135 | if (this.chunkOverlap > 0) { |
| 136 | const overlapChars = tokensToChars(this.chunkOverlap) |
| 137 | chunks = addOverlap(chunks, overlapChars) |
| 138 | } |
| 139 | return buildChunks(chunks, this.chunkOverlap) |
| 140 | } |
| 141 | |
| 142 | if (this.strictBoundaries) { |
| 143 | const chunks = this.expandOversizedSegments(segments) |
| 144 | logger.info(`Chunked into ${chunks.length} strict-boundary regex chunks`) |
| 145 | return buildChunks(chunks, 0) |
| 146 | } |
| 147 | |
| 148 | const merged = this.mergeSegments(segments) |
| 149 | |
| 150 | let chunks = merged |
| 151 | if (this.chunkOverlap > 0) { |
| 152 | const overlapChars = tokensToChars(this.chunkOverlap) |
| 153 | chunks = addOverlap(chunks, overlapChars) |
| 154 | } |
| 155 | |
| 156 | logger.info(`Chunked into ${chunks.length} regex-based chunks`) |
| 157 | return buildChunks(chunks, this.chunkOverlap) |
| 158 | } |
| 159 | |
| 160 | /** |
| 161 | * In strict-boundary mode each segment becomes its own chunk. Segments that |
nothing calls this directly
no test coverage detected