@opensaas/stack-rag 0.1.7 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +223 -0
  3. package/dist/config/index.d.ts.map +1 -1
  4. package/dist/config/index.js +9 -0
  5. package/dist/config/index.js.map +1 -1
  6. package/dist/config/plugin.d.ts.map +1 -1
  7. package/dist/config/plugin.js +32 -0
  8. package/dist/config/plugin.js.map +1 -1
  9. package/dist/config/plugin.test.js +70 -14
  10. package/dist/config/plugin.test.js.map +1 -1
  11. package/dist/config/types.d.ts +135 -0
  12. package/dist/config/types.d.ts.map +1 -1
  13. package/dist/fields/embedding.d.ts +4 -4
  14. package/dist/fields/embedding.d.ts.map +1 -1
  15. package/dist/fields/embedding.js.map +1 -1
  16. package/dist/fields/searchable.d.ts +1 -1
  17. package/dist/fields/searchable.d.ts.map +1 -1
  18. package/dist/fields/searchable.js +1 -0
  19. package/dist/fields/searchable.js.map +1 -1
  20. package/dist/fields/searchable.test.js +1 -0
  21. package/dist/fields/searchable.test.js.map +1 -1
  22. package/dist/index.d.ts +2 -1
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/providers/ollama.js +4 -4
  25. package/dist/providers/ollama.js.map +1 -1
  26. package/dist/providers/openai.js +1 -1
  27. package/dist/providers/openai.js.map +1 -1
  28. package/dist/runtime/build-time.d.ts +100 -0
  29. package/dist/runtime/build-time.d.ts.map +1 -0
  30. package/dist/runtime/build-time.js +185 -0
  31. package/dist/runtime/build-time.js.map +1 -0
  32. package/dist/runtime/index.d.ts +3 -0
  33. package/dist/runtime/index.d.ts.map +1 -1
  34. package/dist/runtime/index.js +6 -0
  35. package/dist/runtime/index.js.map +1 -1
  36. package/dist/runtime/markdown.d.ts +33 -0
  37. package/dist/runtime/markdown.d.ts.map +1 -0
  38. package/dist/runtime/markdown.js +94 -0
  39. package/dist/runtime/markdown.js.map +1 -0
  40. package/dist/runtime/provider-helpers.d.ts +56 -0
  41. package/dist/runtime/provider-helpers.d.ts.map +1 -0
  42. package/dist/runtime/provider-helpers.js +95 -0
  43. package/dist/runtime/provider-helpers.js.map +1 -0
  44. package/dist/runtime/types.d.ts +29 -0
  45. package/dist/runtime/types.d.ts.map +1 -0
  46. package/dist/runtime/types.js +6 -0
  47. package/dist/runtime/types.js.map +1 -0
  48. package/dist/storage/index.d.ts +1 -0
  49. package/dist/storage/index.d.ts.map +1 -1
  50. package/dist/storage/index.js +1 -0
  51. package/dist/storage/index.js.map +1 -1
  52. package/dist/storage/json-file.d.ts +53 -0
  53. package/dist/storage/json-file.d.ts.map +1 -0
  54. package/dist/storage/json-file.js +124 -0
  55. package/dist/storage/json-file.js.map +1 -0
  56. package/dist/storage/storage.test.js +1 -0
  57. package/dist/storage/storage.test.js.map +1 -1
  58. package/package.json +11 -10
  59. package/src/config/index.ts +9 -0
  60. package/src/config/plugin.test.ts +70 -14
  61. package/src/config/plugin.ts +37 -0
  62. package/src/config/types.ts +158 -0
  63. package/src/fields/embedding.ts +6 -4
  64. package/src/fields/searchable.test.ts +2 -1
  65. package/src/fields/searchable.ts +2 -1
  66. package/src/index.ts +6 -0
  67. package/src/providers/ollama.ts +5 -5
  68. package/src/providers/openai.ts +1 -1
  69. package/src/runtime/build-time.ts +216 -0
  70. package/src/runtime/index.ts +18 -0
  71. package/src/runtime/markdown.ts +119 -0
  72. package/src/runtime/provider-helpers.ts +115 -0
  73. package/src/runtime/types.ts +30 -0
  74. package/src/storage/index.ts +1 -0
  75. package/src/storage/json-file.ts +157 -0
  76. package/src/storage/storage.test.ts +1 -0
  77. package/tsconfig.tsbuildinfo +1 -1
@@ -155,6 +155,42 @@ export type VectorStorageConfig =
155
155
  | JsonStorageConfig
156
156
  | CustomStorageConfig
157
157
 
158
+ /**
159
+ * Build-time embedding generation configuration
160
+ */
161
+ export type BuildTimeConfig = {
162
+ /**
163
+ * Enable build-time embedding generation
164
+ */
165
+ enabled: boolean
166
+
167
+ /**
168
+ * Output path for embeddings JSON file
169
+ * Relative to project root
170
+ * @default '.embeddings/embeddings.json'
171
+ */
172
+ outputPath?: string
173
+
174
+ /**
175
+ * Chunk size for text splitting (in characters)
176
+ * @default 500
177
+ */
178
+ chunkSize?: number
179
+
180
+ /**
181
+ * Overlap between chunks (in characters)
182
+ * @default 50
183
+ */
184
+ chunkOverlap?: number
185
+
186
+ /**
187
+ * Whether to enable differential updates
188
+ * Only regenerate embeddings for changed content
189
+ * @default true
190
+ */
191
+ differential?: boolean
192
+ }
193
+
158
194
  /**
159
195
  * Main RAG configuration
160
196
  */
@@ -191,6 +227,13 @@ export type RAGConfig = {
191
227
  */
192
228
  chunking?: ChunkingConfig
193
229
 
230
+ /**
231
+ * Build-time embedding generation configuration
232
+ * When enabled, embeddings are generated at build time and stored in a JSON file
233
+ * instead of being generated at runtime via hooks
234
+ */
235
+ buildTime?: BuildTimeConfig
236
+
194
237
  /**
195
238
  * Whether to enable MCP tools for semantic search
196
239
  * Requires MCP to be enabled in main config
@@ -219,6 +262,7 @@ export type NormalizedRAGConfig = {
219
262
  providers: Record<string, EmbeddingProviderConfig>
220
263
  storage: VectorStorageConfig
221
264
  chunking: Required<ChunkingConfig>
265
+ buildTime: Required<BuildTimeConfig> | null
222
266
  enableMcpTools: boolean
223
267
  batchSize: number
224
268
  rateLimit: number
@@ -340,3 +384,117 @@ export type SearchableMetadata = {
340
384
  */
341
385
  chunking?: ChunkingConfig
342
386
  }
387
+
388
+ /**
389
+ * A chunk of text with its embedding
390
+ * Used in build-time generation output
391
+ */
392
+ export type EmbeddingChunk = {
393
+ /**
394
+ * The text content of this chunk
395
+ */
396
+ text: string
397
+
398
+ /**
399
+ * The embedding vector for this chunk
400
+ */
401
+ embedding: number[]
402
+
403
+ /**
404
+ * Metadata about the chunk
405
+ */
406
+ metadata: {
407
+ /**
408
+ * Index of this chunk within the document
409
+ */
410
+ chunkIndex: number
411
+
412
+ /**
413
+ * Start character position in original text
414
+ */
415
+ startOffset: number
416
+
417
+ /**
418
+ * End character position in original text
419
+ */
420
+ endOffset: number
421
+
422
+ /**
423
+ * Whether this chunk represents a document title
424
+ * Title chunks receive boosted scoring during search
425
+ */
426
+ isTitle?: boolean
427
+
428
+ /**
429
+ * Additional custom metadata
430
+ */
431
+ [key: string]: unknown
432
+ }
433
+ }
434
+
435
+ /**
436
+ * Document with embeddings
437
+ * Used in build-time generation output
438
+ */
439
+ export type EmbeddedDocument = {
440
+ /**
441
+ * Document ID or slug
442
+ */
443
+ id: string
444
+
445
+ /**
446
+ * Document title
447
+ */
448
+ title?: string
449
+
450
+ /**
451
+ * The chunks of this document with embeddings
452
+ */
453
+ chunks: EmbeddingChunk[]
454
+
455
+ /**
456
+ * Embedding metadata
457
+ */
458
+ embeddingMetadata: EmbeddingMetadata
459
+
460
+ /**
461
+ * When the embeddings were generated
462
+ */
463
+ generatedAt: string
464
+
465
+ /**
466
+ * Hash of the source content (for differential updates)
467
+ */
468
+ contentHash: string
469
+ }
470
+
471
+ /**
472
+ * Build-time embeddings index file format
473
+ */
474
+ export type EmbeddingsIndex = {
475
+ /**
476
+ * Version of the embeddings format
477
+ */
478
+ version: string
479
+
480
+ /**
481
+ * Embedding configuration used to generate these embeddings
482
+ */
483
+ config: {
484
+ provider: string
485
+ model: string
486
+ dimensions: number
487
+ chunkSize: number
488
+ chunkOverlap: number
489
+ }
490
+
491
+ /**
492
+ * Documents with embeddings
493
+ */
494
+ documents: Record<string, EmbeddedDocument>
495
+
496
+ /**
497
+ * When the index was generated
498
+ */
499
+ generatedAt: string
500
+ }
@@ -1,12 +1,12 @@
1
1
  import { z } from 'zod'
2
- import type { BaseFieldConfig } from '@opensaas/stack-core'
3
- import type { StoredEmbedding, EmbeddingProviderName, ChunkingConfig } from '../config/types.js'
2
+ import type { BaseFieldConfig, TypeInfo } from '@opensaas/stack-core'
3
+ import type { EmbeddingProviderName, ChunkingConfig } from '../config/types.js'
4
4
 
5
5
  /**
6
6
  * Embedding field configuration
7
7
  * Stores vector embeddings as JSON with metadata
8
8
  */
9
- export type EmbeddingField = BaseFieldConfig<StoredEmbedding | null, StoredEmbedding | null> & {
9
+ export type EmbeddingField<TTypeInfo extends TypeInfo = TypeInfo> = BaseFieldConfig<TTypeInfo> & {
10
10
  type: 'embedding'
11
11
 
12
12
  /**
@@ -91,7 +91,9 @@ export type EmbeddingField = BaseFieldConfig<StoredEmbedding | null, StoredEmbed
91
91
  * }
92
92
  * ```
93
93
  */
94
- export function embedding(options?: Omit<EmbeddingField, 'type'>): EmbeddingField {
94
+ export function embedding<TTypeInfo extends TypeInfo = TypeInfo>(
95
+ options?: Omit<EmbeddingField<TTypeInfo>, 'type'>,
96
+ ): EmbeddingField<TTypeInfo> {
95
97
  const dimensions = options?.dimensions || 1536
96
98
  const autoGenerate = options?.autoGenerate ?? options?.sourceField != null
97
99
 
@@ -4,7 +4,8 @@ import type { BaseFieldConfig } from '@opensaas/stack-core'
4
4
  import type { SearchableOptions } from '../config/types.js'
5
5
 
6
6
  // Mock text field for testing
7
- function mockTextField(): BaseFieldConfig {
7
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Mock function for testing
8
+ function mockTextField(): BaseFieldConfig<any> {
8
9
  return {
9
10
  type: 'text',
10
11
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -37,7 +37,8 @@ import type { SearchableOptions, SearchableMetadata } from '../config/types.js'
37
37
  * @param options - Embedding configuration options
38
38
  * @returns The same field with searchable metadata attached
39
39
  */
40
- export function searchable<T extends BaseFieldConfig>(
40
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Searchable must accept any field config
41
+ export function searchable<T extends BaseFieldConfig<any>>(
41
42
  field: T,
42
43
  options: SearchableOptions = {},
43
44
  ): T & { _searchable: SearchableMetadata } {
package/src/index.ts CHANGED
@@ -15,6 +15,9 @@ export {
15
15
  // Plugin export
16
16
  export { ragPlugin } from './config/plugin.js'
17
17
 
18
+ // Runtime type exports
19
+ export type { RAGRuntimeServices } from './runtime/types.js'
20
+
18
21
  export type {
19
22
  RAGConfig,
20
23
  NormalizedRAGConfig,
@@ -30,4 +33,7 @@ export type {
30
33
  EmbeddingMetadata,
31
34
  StoredEmbedding,
32
35
  SearchResult,
36
+ EmbeddingsIndex,
37
+ EmbeddedDocument,
38
+ EmbeddingChunk,
33
39
  } from './config/types.js'
@@ -117,11 +117,6 @@ export class OllamaEmbeddingProvider implements EmbeddingProvider {
117
117
  return []
118
118
  }
119
119
 
120
- // Ensure dimensions are initialized
121
- if (!this.dimensionsInitialized) {
122
- await this.initializeDimensions()
123
- }
124
-
125
120
  // Filter out empty texts and keep track of indices
126
121
  const validTexts: string[] = []
127
122
  const validIndices: number[] = []
@@ -137,6 +132,11 @@ export class OllamaEmbeddingProvider implements EmbeddingProvider {
137
132
  throw new Error('Cannot generate embeddings for all empty texts')
138
133
  }
139
134
 
135
+ // Ensure dimensions are initialized (only after validating we have valid texts)
136
+ if (!this.dimensionsInitialized) {
137
+ await this.initializeDimensions()
138
+ }
139
+
140
140
  try {
141
141
  // Make parallel requests (Ollama doesn't have batch API)
142
142
  const embeddingPromises = validTexts.map((text) => this.embed(text))
@@ -17,7 +17,7 @@ async function getOpenAI() {
17
17
  try {
18
18
  const module = await import('openai')
19
19
  return module.default
20
- } catch (error) {
20
+ } catch {
21
21
  throw new Error(
22
22
  'OpenAI package not found. Install it with: npm install openai\n' +
23
23
  'Make sure to run: pnpm install openai',
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Build-time utilities for generating and managing embeddings
3
+ * Used by CLI tools and custom build scripts
4
+ */
5
+
6
+ import { readFileSync, existsSync } from 'node:fs'
7
+ import { createHash } from 'node:crypto'
8
+ import type { EmbeddingProvider } from '../providers/types.js'
9
+ import type { EmbeddingsIndex, EmbeddedDocument, EmbeddingChunk } from '../config/types.js'
10
+
11
+ /**
12
+ * Simple character-based text chunking for build-time generation
13
+ *
14
+ * Simpler than the runtime chunking strategies, optimized for build-time batch processing.
15
+ * Splits text into fixed-size chunks with overlap.
16
+ *
17
+ * @param text - Text to chunk
18
+ * @param chunkSize - Size of each chunk in characters
19
+ * @param overlap - Overlap between chunks in characters
20
+ * @returns Array of text chunks
21
+ *
22
+ * @example
23
+ * ```typescript
24
+ * import { simpleChunkText } from '@opensaas/stack-rag/runtime'
25
+ *
26
+ * const chunks = simpleChunkText("Long document...", 500, 50)
27
+ * ```
28
+ */
29
+ export function simpleChunkText(text: string, chunkSize: number, overlap: number): string[] {
30
+ const chunks: string[] = []
31
+ let start = 0
32
+
33
+ while (start < text.length) {
34
+ const end = Math.min(start + chunkSize, text.length)
35
+ chunks.push(text.slice(start, end))
36
+ start += chunkSize - overlap
37
+ }
38
+
39
+ return chunks
40
+ }
41
+
42
+ /**
43
+ * Compute SHA256 hash of content for change detection
44
+ *
45
+ * @param content - Content to hash
46
+ * @returns Hexadecimal hash string
47
+ *
48
+ * @example
49
+ * ```typescript
50
+ * import { hashContent } from '@opensaas/stack-rag/runtime'
51
+ *
52
+ * const hash = hashContent("document content")
53
+ * ```
54
+ */
55
+ export function hashContent(content: string): string {
56
+ return createHash('sha256').update(content).digest('hex')
57
+ }
58
+
59
+ /**
60
+ * Load existing embeddings index from file
61
+ *
62
+ * Used for differential updates - only regenerate embeddings for changed content.
63
+ *
64
+ * @param filePath - Path to embeddings JSON file
65
+ * @returns Loaded index or null if file doesn't exist or can't be loaded
66
+ *
67
+ * @example
68
+ * ```typescript
69
+ * import { loadExistingIndex } from '@opensaas/stack-rag/runtime'
70
+ *
71
+ * const existing = loadExistingIndex('.embeddings/docs.json')
72
+ * if (existing) {
73
+ * console.log(`Found ${Object.keys(existing.documents).length} existing documents`)
74
+ * }
75
+ * ```
76
+ */
77
+ export function loadExistingIndex(filePath: string): EmbeddingsIndex | null {
78
+ if (!existsSync(filePath)) {
79
+ return null
80
+ }
81
+
82
+ try {
83
+ const content = readFileSync(filePath, 'utf-8')
84
+ return JSON.parse(content) as EmbeddingsIndex
85
+ } catch {
86
+ console.warn(`Warning: Could not load existing embeddings from ${filePath}`)
87
+ return null
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Generate embeddings for a document with chunking
93
+ *
94
+ * Main utility for build-time embedding generation. Chunks the document,
95
+ * generates embeddings for each chunk, and returns a complete EmbeddedDocument.
96
+ *
97
+ * @param documentId - Unique identifier for the document
98
+ * @param content - Document content (plain text)
99
+ * @param provider - Embedding provider instance
100
+ * @param options - Generation options
101
+ * @returns Complete embedded document ready to be added to index
102
+ *
103
+ * @example
104
+ * ```typescript
105
+ * import { generateDocumentEmbeddings } from '@opensaas/stack-rag/runtime'
106
+ * import { createEmbeddingProvider } from '@opensaas/stack-rag/providers'
107
+ *
108
+ * const provider = createEmbeddingProvider({
109
+ * type: 'openai',
110
+ * apiKey: process.env.OPENAI_API_KEY
111
+ * })
112
+ *
113
+ * const doc = await generateDocumentEmbeddings(
114
+ * 'docs/getting-started',
115
+ * 'Document content here...',
116
+ * provider,
117
+ * {
118
+ * title: 'Getting Started',
119
+ * chunkSize: 500,
120
+ * chunkOverlap: 50,
121
+ * metadata: { section: 'guides' }
122
+ * }
123
+ * )
124
+ * ```
125
+ */
126
+ export async function generateDocumentEmbeddings(
127
+ documentId: string,
128
+ content: string,
129
+ provider: EmbeddingProvider,
130
+ options: {
131
+ title?: string
132
+ chunkSize: number
133
+ chunkOverlap: number
134
+ metadata?: Record<string, unknown>
135
+ },
136
+ ): Promise<EmbeddedDocument> {
137
+ const { title, chunkSize, chunkOverlap, metadata = {} } = options
138
+
139
+ // Hash content for differential updates
140
+ const contentHash = hashContent(content)
141
+
142
+ // Prepare all text chunks to embed
143
+ const allTextChunks: string[] = []
144
+ const chunkTypes: Array<'title' | 'content'> = []
145
+
146
+ // Add title chunk first if title exists
147
+ if (title) {
148
+ allTextChunks.push(title)
149
+ chunkTypes.push('title')
150
+ }
151
+
152
+ // Chunk the content
153
+ const contentChunks = simpleChunkText(content, chunkSize, chunkOverlap)
154
+ allTextChunks.push(...contentChunks)
155
+ contentChunks.forEach(() => chunkTypes.push('content'))
156
+
157
+ // Generate embeddings in batch for all chunks
158
+ const allEmbeddings = await provider.embedBatch(allTextChunks)
159
+
160
+ // Build chunks with embeddings
161
+ const chunks: EmbeddingChunk[] = []
162
+
163
+ let embeddingIndex = 0
164
+ let contentChunkIndex = 0
165
+
166
+ for (let i = 0; i < chunkTypes.length; i++) {
167
+ const type = chunkTypes[i]
168
+
169
+ if (type === 'title') {
170
+ // Title chunk
171
+ chunks.push({
172
+ text: allTextChunks[embeddingIndex],
173
+ embedding: allEmbeddings[embeddingIndex],
174
+ metadata: {
175
+ chunkIndex: -1, // Special index for title
176
+ startOffset: 0,
177
+ endOffset: 0,
178
+ isTitle: true,
179
+ ...metadata,
180
+ },
181
+ })
182
+ } else {
183
+ // Content chunk
184
+ chunks.push({
185
+ text: allTextChunks[embeddingIndex],
186
+ embedding: allEmbeddings[embeddingIndex],
187
+ metadata: {
188
+ chunkIndex: contentChunkIndex,
189
+ startOffset: contentChunkIndex * (chunkSize - chunkOverlap),
190
+ endOffset: Math.min(
191
+ (contentChunkIndex + 1) * chunkSize - contentChunkIndex * chunkOverlap,
192
+ content.length,
193
+ ),
194
+ ...metadata,
195
+ },
196
+ })
197
+ contentChunkIndex++
198
+ }
199
+
200
+ embeddingIndex++
201
+ }
202
+
203
+ return {
204
+ id: documentId,
205
+ title,
206
+ chunks,
207
+ embeddingMetadata: {
208
+ model: provider.model,
209
+ provider: provider.type,
210
+ dimensions: provider.dimensions,
211
+ generatedAt: new Date().toISOString(),
212
+ },
213
+ generatedAt: new Date().toISOString(),
214
+ contentHash,
215
+ }
216
+ }
@@ -49,3 +49,21 @@ export {
49
49
  type BatchError,
50
50
  type BatchProcessResult,
51
51
  } from './batch.js'
52
+
53
+ // Build-time utilities
54
+ export {
55
+ simpleChunkText,
56
+ hashContent,
57
+ loadExistingIndex,
58
+ generateDocumentEmbeddings,
59
+ } from './build-time.js'
60
+
61
+ // Markdown processing
62
+ export { stripMarkdown, extractMarkdownText } from './markdown.js'
63
+
64
+ // Provider helpers
65
+ export {
66
+ createProviderFromEnv,
67
+ getProviderConfigFromEnv,
68
+ type ProviderType,
69
+ } from './provider-helpers.js'
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Markdown processing utilities for content preparation
3
+ */
4
+
5
+ /**
6
+ * Strip markdown formatting for cleaner text suitable for embeddings
7
+ *
8
+ * Removes code blocks, formatting markers, links, images, and HTML tags
9
+ * while preserving the actual content.
10
+ *
11
+ * @param markdown - Markdown text to process
12
+ * @returns Plain text with markdown removed
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * import { stripMarkdown } from '@opensaas/stack-rag/runtime'
17
+ *
18
+ * const markdown = '# Hello\n\nThis is **bold** text with a [link](url).'
19
+ * const plain = stripMarkdown(markdown)
20
+ * // Returns: 'Hello\n\nThis is bold text with a link.'
21
+ * ```
22
+ */
23
+ export function stripMarkdown(markdown: string): string {
24
+ let text = markdown
25
+
26
+ // Remove code blocks
27
+ text = text.replace(/```[\s\S]*?```/g, '')
28
+ text = text.replace(/`[^`]+`/g, '')
29
+
30
+ // Remove headings markers but keep text
31
+ text = text.replace(/^#+\s+/gm, '')
32
+
33
+ // Remove bold/italic markers
34
+ text = text.replace(/\*\*([^*]+)\*\*/g, '$1')
35
+ text = text.replace(/\*([^*]+)\*/g, '$1')
36
+ text = text.replace(/__([^_]+)__/g, '$1')
37
+ text = text.replace(/_([^_]+)_/g, '$1')
38
+
39
+ // Remove links but keep text
40
+ text = text.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
41
+
42
+ // Remove images
43
+ text = text.replace(/!\[([^\]]*)\]\([^)]+\)/g, '')
44
+
45
+ // Remove HTML tags
46
+ text = text.replace(/<[^>]+>/g, '')
47
+
48
+ // Normalize whitespace
49
+ text = text.replace(/\n{3,}/g, '\n\n')
50
+ text = text.replace(/[ \t]+/g, ' ')
51
+
52
+ return text.trim()
53
+ }
54
+
55
+ /**
56
+ * Extract text content from common markdown structures
57
+ *
58
+ * More aggressive than stripMarkdown - extracts only text content,
59
+ * removes all structural elements.
60
+ *
61
+ * @param markdown - Markdown text
62
+ * @returns Extracted plain text
63
+ */
64
+ export function extractMarkdownText(markdown: string): string {
65
+ let text = markdown
66
+
67
+ // Remove YAML frontmatter
68
+ text = text.replace(/^---[\s\S]*?---\n/m, '')
69
+
70
+ // Remove code blocks entirely (including content)
71
+ text = text.replace(/```[\s\S]*?```/g, '')
72
+
73
+ // Remove inline code
74
+ text = text.replace(/`[^`]+`/g, '')
75
+
76
+ // Remove horizontal rules
77
+ text = text.replace(/^[-*_]{3,}$/gm, '')
78
+
79
+ // Remove blockquotes markers
80
+ text = text.replace(/^>\s+/gm, '')
81
+
82
+ // Remove list markers
83
+ text = text.replace(/^[\s]*[-*+]\s+/gm, '')
84
+ text = text.replace(/^[\s]*\d+\.\s+/gm, '')
85
+
86
+ // Remove headings markers
87
+ text = text.replace(/^#+\s+/gm, '')
88
+
89
+ // Remove emphasis markers
90
+ text = text.replace(/\*\*([^*]+)\*\*/g, '$1')
91
+ text = text.replace(/\*([^*]+)\*/g, '$1')
92
+ text = text.replace(/__([^_]+)__/g, '$1')
93
+ text = text.replace(/_([^_]+)_/g, '$1')
94
+
95
+ // Remove strikethrough
96
+ text = text.replace(/~~([^~]+)~~/g, '$1')
97
+
98
+ // Remove links but keep text
99
+ text = text.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
100
+
101
+ // Remove reference-style links
102
+ text = text.replace(/\[([^\]]+)\]\[[^\]]*\]/g, '$1')
103
+
104
+ // Remove images
105
+ text = text.replace(/!\[([^\]]*)\]\([^)]+\)/g, '')
106
+
107
+ // Remove HTML tags
108
+ text = text.replace(/<[^>]+>/g, '')
109
+
110
+ // Remove HTML entities
111
+ text = text.replace(/&[a-z]+;/gi, '')
112
+
113
+ // Normalize whitespace
114
+ text = text.replace(/\n{3,}/g, '\n\n')
115
+ text = text.replace(/[ \t]+/g, ' ')
116
+ text = text.replace(/^\s+|\s+$/gm, '')
117
+
118
+ return text.trim()
119
+ }