( text: string, maxChunkSize: number = 1500, minChunkSize: number = 500, )
| 559 | * @returns Array of text chunks |
| 560 | */ |
| 561 | export function chunkText( |
| 562 | text: string, |
| 563 | maxChunkSize: number = 1500, |
| 564 | minChunkSize: number = 500, |
| 565 | ): string[] { |
| 566 | const chunks: string[] = []; |
| 567 | |
| 568 | // Split by markdown headings (## Heading) |
| 569 | const headingPattern = /\n(#{1,6}\s+[^\n]+)\n/g; |
| 570 | const sections = text.split(headingPattern); |
| 571 | |
| 572 | let currentChunk = ""; |
| 573 | let headingText = ""; |
| 574 | |
| 575 | // Process each section |
| 576 | for (let i = 0; i < sections.length; i++) { |
| 577 | const section = sections[i]; |
| 578 | |
| 579 | // Check if this is a heading |
| 580 | if (i > 0 && i % 2 === 1) { |
| 581 | headingText = section.trim(); |
| 582 | continue; |
| 583 | } |
| 584 | |
| 585 | // This is content - process it with the preceding heading |
| 586 | const contentWithHeading = headingText |
| 587 | ? `${headingText}\n\n${section}` |
| 588 | : section; |
| 589 | |
| 590 | // If content is short enough, add as single chunk |
| 591 | if (contentWithHeading.length <= maxChunkSize) { |
| 592 | if (contentWithHeading.trim().length > 0) { |
| 593 | chunks.push(contentWithHeading.trim()); |
| 594 | } |
| 595 | headingText = ""; |
| 596 | continue; |
| 597 | } |
| 598 | |
| 599 | // If content is long, split by paragraphs |
| 600 | const paragraphs = contentWithHeading.split(/\n\n+/); |
| 601 | |
| 602 | currentChunk = ""; |
| 603 | |
| 604 | for (const paragraph of paragraphs) { |
| 605 | const trimmedParagraph = paragraph.trim(); |
| 606 | |
| 607 | // Skip empty paragraphs |
| 608 | if (!trimmedParagraph) continue; |
| 609 | |
| 610 | // If adding this paragraph would exceed max size and we already have content |
| 611 | if ( |
| 612 | currentChunk && |
| 613 | currentChunk.length + trimmedParagraph.length + 2 > maxChunkSize |
| 614 | ) { |
| 615 | // Only add the chunk if it meets minimum size |
| 616 | if (currentChunk.length >= minChunkSize) { |
| 617 | chunks.push(currentChunk.trim()); |
| 618 | currentChunk = trimmedParagraph; |
no outgoing calls
no test coverage detected