bluera-knowledge 0.11.18 → 0.11.19
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.
- package/.claude-plugin/plugin.json +1 -1
- package/CHANGELOG.md +27 -0
- package/dist/{chunk-ZDEO4WJT.js → chunk-GOAOBPOA.js} +22 -70
- package/dist/chunk-GOAOBPOA.js.map +1 -0
- package/dist/{chunk-6FHWC36B.js → chunk-HRQD3MPH.js} +8 -6
- package/dist/chunk-HRQD3MPH.js.map +1 -0
- package/dist/{chunk-ZZNABJMQ.js → chunk-QEHSDQTL.js} +79 -13
- package/dist/chunk-QEHSDQTL.js.map +1 -0
- package/dist/{chunk-5NUI6JL6.js → chunk-VP4VZULK.js} +2 -2
- package/dist/index.js +36 -18
- package/dist/index.js.map +1 -1
- package/dist/mcp/server.js +3 -3
- package/dist/watch.service-OPLKIDFQ.js +7 -0
- package/dist/workers/background-worker-cli.js +3 -3
- package/package.json +1 -1
- package/src/cli/commands/crawl.ts +1 -1
- package/src/cli/commands/index-cmd.test.ts +14 -4
- package/src/cli/commands/index-cmd.ts +11 -4
- package/src/cli/commands/store.test.ts +211 -18
- package/src/cli/commands/store.ts +26 -8
- package/src/crawl/article-converter.test.ts +30 -61
- package/src/crawl/article-converter.ts +2 -8
- package/src/crawl/bridge.test.ts +14 -0
- package/src/crawl/bridge.ts +17 -5
- package/src/crawl/intelligent-crawler.test.ts +65 -76
- package/src/crawl/intelligent-crawler.ts +33 -69
- package/src/plugin/git-clone.test.ts +44 -0
- package/src/plugin/git-clone.ts +4 -0
- package/src/services/code-unit.service.test.ts +59 -6
- package/src/services/code-unit.service.ts +47 -2
- package/src/services/index.ts +19 -3
- package/src/services/job.service.test.ts +10 -7
- package/src/services/job.service.ts +12 -6
- package/src/services/services.test.ts +19 -6
- package/src/services/watch.service.test.ts +80 -56
- package/src/services/watch.service.ts +9 -6
- package/dist/chunk-6FHWC36B.js.map +0 -1
- package/dist/chunk-ZDEO4WJT.js.map +0 -1
- package/dist/chunk-ZZNABJMQ.js.map +0 -1
- package/dist/watch.service-BJV3TI3F.js +0 -7
- /package/dist/{chunk-5NUI6JL6.js.map → chunk-VP4VZULK.js.map} +0 -0
- /package/dist/{watch.service-BJV3TI3F.js.map → watch.service-OPLKIDFQ.js.map} +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,33 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project will be documented in this file. See [commit-and-tag-version](https://github.com/absolute-version/commit-and-tag-version) for commit guidelines.
|
|
4
4
|
|
|
5
|
+
## [0.11.19](https://github.com/blueraai/bluera-knowledge/compare/v0.11.6...v0.11.19) (2026-01-10)
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
### Features
|
|
9
|
+
|
|
10
|
+
* **code-unit:** add interface and type extraction support ([190dded](https://github.com/blueraai/bluera-knowledge/commit/190dded78be68985c3f94c0da6ebed03659da313))
|
|
11
|
+
* **commands:** add test-plugin command for comprehensive plugin testing ([c6eb5e7](https://github.com/blueraai/bluera-knowledge/commit/c6eb5e7762376810a9ff3e79f794f05ff0c77b97))
|
|
12
|
+
* **scripts:** add post-release npm validation script ([e4c29a0](https://github.com/blueraai/bluera-knowledge/commit/e4c29a0c83907de4bc293a69a58412629457fb22))
|
|
13
|
+
* **scripts:** add suggest, sync, serve, mcp tests to npm validation ([49d85da](https://github.com/blueraai/bluera-knowledge/commit/49d85dad1a89691060c12f152d644844baf6e6e6))
|
|
14
|
+
* **scripts:** log expected vs installed version in validation script ([c77d039](https://github.com/blueraai/bluera-knowledge/commit/c77d039b27a3ccf54d50006af161ac4dcfea7b21))
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
### Bug Fixes
|
|
18
|
+
|
|
19
|
+
* **bridge:** close readline interfaces on stop to prevent resource leak ([e970bf9](https://github.com/blueraai/bluera-knowledge/commit/e970bf94f74bdba24803eed8714d47ed8e874117))
|
|
20
|
+
* **cli:** plugin-api commands now respect global options ([d3cca02](https://github.com/blueraai/bluera-knowledge/commit/d3cca02ffc679ffc187b76c7682f3cc177eabdea))
|
|
21
|
+
* **commands:** fix test-plugin reliability issues ([2841e9a](https://github.com/blueraai/bluera-knowledge/commit/2841e9aa6438f9fd60c70ab921575088b2921810))
|
|
22
|
+
* **commands:** move test-plugin to commands/ for plugin distribution ([0a3ff5f](https://github.com/blueraai/bluera-knowledge/commit/0a3ff5f91666db7efa213d5abd4c447fb07749fc))
|
|
23
|
+
* **crawl:** throw errors instead of fallback/graceful degradation ([19962c2](https://github.com/blueraai/bluera-knowledge/commit/19962c2114406f2fea22e5973e242f190ab65fb7))
|
|
24
|
+
* **git-clone:** add error handler for spawn failures ([4bf50e2](https://github.com/blueraai/bluera-knowledge/commit/4bf50e2348505dccdc94522cf42f1d4d3471480c))
|
|
25
|
+
* improve error handling and type safety from code review ([61710aa](https://github.com/blueraai/bluera-knowledge/commit/61710aaed48c87c457628b75e3968686377a6c92))
|
|
26
|
+
* **plugin:** properly close services after command execution ([eeaf743](https://github.com/blueraai/bluera-knowledge/commit/eeaf743750be73fd9c7a9e72440b2fd0fb5a53fa))
|
|
27
|
+
* **scripts:** show real-time output in validation script ([8a4bdec](https://github.com/blueraai/bluera-knowledge/commit/8a4bdec8b63c504d34ba35bfe19da795f7f7fd07))
|
|
28
|
+
* **scripts:** use mktemp for temp directories in validation script ([3107861](https://github.com/blueraai/bluera-knowledge/commit/3107861bd7a966016fde2a121469dd84756f39be))
|
|
29
|
+
* **search:** add defaults for env vars so CLI works standalone ([b2d2ce5](https://github.com/blueraai/bluera-knowledge/commit/b2d2ce534e8cd2ba0fc0abdac505c912a1a76035))
|
|
30
|
+
* **services:** throw errors instead of graceful degradation ([ca992b5](https://github.com/blueraai/bluera-knowledge/commit/ca992b5cfa4d9ebad62ee82231cfdd2d3d64012e))
|
|
31
|
+
|
|
5
32
|
## [0.11.18](https://github.com/blueraai/bluera-knowledge/compare/v0.11.6...v0.11.18) (2026-01-10)
|
|
6
33
|
|
|
7
34
|
|
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
createLogger,
|
|
4
4
|
summarizePayload,
|
|
5
5
|
truncateForLog
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-QEHSDQTL.js";
|
|
7
7
|
|
|
8
8
|
// src/crawl/intelligent-crawler.ts
|
|
9
9
|
import { EventEmitter } from "events";
|
|
@@ -201,8 +201,7 @@ ${hashes} ${cleanContent}
|
|
|
201
201
|
);
|
|
202
202
|
return {
|
|
203
203
|
markdown,
|
|
204
|
-
...title !== void 0 && { title }
|
|
205
|
-
success: true
|
|
204
|
+
...title !== void 0 && { title }
|
|
206
205
|
};
|
|
207
206
|
} catch (error) {
|
|
208
207
|
logger.error(
|
|
@@ -212,11 +211,7 @@ ${hashes} ${cleanContent}
|
|
|
212
211
|
},
|
|
213
212
|
"HTML to markdown conversion failed"
|
|
214
213
|
);
|
|
215
|
-
|
|
216
|
-
markdown: "",
|
|
217
|
-
success: false,
|
|
218
|
-
error: error instanceof Error ? error.message : String(error)
|
|
219
|
-
};
|
|
214
|
+
throw error instanceof Error ? error : new Error(String(error));
|
|
220
215
|
}
|
|
221
216
|
}
|
|
222
217
|
|
|
@@ -498,16 +493,7 @@ var IntelligentCrawler = class extends EventEmitter {
|
|
|
498
493
|
*/
|
|
499
494
|
async *crawlIntelligent(seedUrl, crawlInstruction, extractInstruction, maxPages, useHeadless = false) {
|
|
500
495
|
if (!ClaudeClient.isAvailable()) {
|
|
501
|
-
|
|
502
|
-
type: "error",
|
|
503
|
-
pagesVisited: 0,
|
|
504
|
-
totalPages: maxPages,
|
|
505
|
-
message: "Claude CLI not found, using simple crawl mode (install Claude Code for intelligent crawling)",
|
|
506
|
-
error: new Error("Claude CLI not available")
|
|
507
|
-
};
|
|
508
|
-
this.emit("progress", fallbackProgress);
|
|
509
|
-
yield* this.crawlSimple(seedUrl, extractInstruction, maxPages, useHeadless);
|
|
510
|
-
return;
|
|
496
|
+
throw new Error("Claude CLI not available: install Claude Code for intelligent crawling");
|
|
511
497
|
}
|
|
512
498
|
let strategy;
|
|
513
499
|
try {
|
|
@@ -529,16 +515,7 @@ var IntelligentCrawler = class extends EventEmitter {
|
|
|
529
515
|
};
|
|
530
516
|
this.emit("progress", strategyCompleteProgress);
|
|
531
517
|
} catch (error) {
|
|
532
|
-
|
|
533
|
-
type: "error",
|
|
534
|
-
pagesVisited: 0,
|
|
535
|
-
totalPages: maxPages,
|
|
536
|
-
message: "Claude crawl strategy failed, falling back to simple mode",
|
|
537
|
-
error: error instanceof Error ? error : new Error(String(error))
|
|
538
|
-
};
|
|
539
|
-
this.emit("progress", errorProgress);
|
|
540
|
-
yield* this.crawlSimple(seedUrl, extractInstruction, maxPages);
|
|
541
|
-
return;
|
|
518
|
+
throw error instanceof Error ? error : new Error(String(error));
|
|
542
519
|
}
|
|
543
520
|
let pagesVisited = 0;
|
|
544
521
|
for (const url of strategy.urls) {
|
|
@@ -616,12 +593,16 @@ var IntelligentCrawler = class extends EventEmitter {
|
|
|
616
593
|
}
|
|
617
594
|
}
|
|
618
595
|
} catch (error) {
|
|
596
|
+
const errorObj = error instanceof Error ? error : new Error(String(error));
|
|
597
|
+
if (errorObj.message.includes("Extraction failed") || errorObj.message.includes("Claude CLI not available") || errorObj.message.includes("Headless fetch failed")) {
|
|
598
|
+
throw errorObj;
|
|
599
|
+
}
|
|
619
600
|
const simpleErrorProgress = {
|
|
620
601
|
type: "error",
|
|
621
602
|
pagesVisited,
|
|
622
603
|
totalPages: maxPages,
|
|
623
604
|
currentUrl: current.url,
|
|
624
|
-
error:
|
|
605
|
+
error: errorObj
|
|
625
606
|
};
|
|
626
607
|
this.emit("progress", simpleErrorProgress);
|
|
627
608
|
}
|
|
@@ -641,10 +622,6 @@ var IntelligentCrawler = class extends EventEmitter {
|
|
|
641
622
|
this.visited.add(url);
|
|
642
623
|
const html = await this.fetchHtml(url, useHeadless);
|
|
643
624
|
const conversion = await convertHtmlToMarkdown(html, url);
|
|
644
|
-
if (!conversion.success) {
|
|
645
|
-
logger2.error({ url, error: conversion.error }, "HTML to markdown conversion failed");
|
|
646
|
-
throw new Error(`Failed to convert HTML: ${conversion.error ?? "Unknown error"}`);
|
|
647
|
-
}
|
|
648
625
|
logger2.debug(
|
|
649
626
|
{
|
|
650
627
|
url,
|
|
@@ -656,40 +633,16 @@ var IntelligentCrawler = class extends EventEmitter {
|
|
|
656
633
|
let extracted;
|
|
657
634
|
if (extractInstruction !== void 0 && extractInstruction !== "") {
|
|
658
635
|
if (!ClaudeClient.isAvailable()) {
|
|
659
|
-
|
|
660
|
-
type: "error",
|
|
661
|
-
pagesVisited,
|
|
662
|
-
totalPages: 0,
|
|
663
|
-
currentUrl: url,
|
|
664
|
-
message: "Skipping extraction (Claude CLI not available), storing raw markdown",
|
|
665
|
-
error: new Error("Claude CLI not available")
|
|
666
|
-
};
|
|
667
|
-
this.emit("progress", skipProgress);
|
|
668
|
-
} else {
|
|
669
|
-
try {
|
|
670
|
-
const extractionProgress = {
|
|
671
|
-
type: "extraction",
|
|
672
|
-
pagesVisited,
|
|
673
|
-
totalPages: 0,
|
|
674
|
-
currentUrl: url
|
|
675
|
-
};
|
|
676
|
-
this.emit("progress", extractionProgress);
|
|
677
|
-
extracted = await this.claudeClient.extractContent(
|
|
678
|
-
conversion.markdown,
|
|
679
|
-
extractInstruction
|
|
680
|
-
);
|
|
681
|
-
} catch (error) {
|
|
682
|
-
const extractionErrorProgress = {
|
|
683
|
-
type: "error",
|
|
684
|
-
pagesVisited,
|
|
685
|
-
totalPages: 0,
|
|
686
|
-
currentUrl: url,
|
|
687
|
-
message: "Extraction failed, storing raw markdown",
|
|
688
|
-
error: error instanceof Error ? error : new Error(String(error))
|
|
689
|
-
};
|
|
690
|
-
this.emit("progress", extractionErrorProgress);
|
|
691
|
-
}
|
|
636
|
+
throw new Error("Claude CLI not available: install Claude Code for extraction");
|
|
692
637
|
}
|
|
638
|
+
const extractionProgress = {
|
|
639
|
+
type: "extraction",
|
|
640
|
+
pagesVisited,
|
|
641
|
+
totalPages: 0,
|
|
642
|
+
currentUrl: url
|
|
643
|
+
};
|
|
644
|
+
this.emit("progress", extractionProgress);
|
|
645
|
+
extracted = await this.claudeClient.extractContent(conversion.markdown, extractInstruction);
|
|
693
646
|
}
|
|
694
647
|
return {
|
|
695
648
|
url,
|
|
@@ -719,9 +672,8 @@ var IntelligentCrawler = class extends EventEmitter {
|
|
|
719
672
|
);
|
|
720
673
|
return result.html;
|
|
721
674
|
} catch (error) {
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
"Headless fetch failed, falling back to axios"
|
|
675
|
+
throw new Error(
|
|
676
|
+
`Headless fetch failed: ${error instanceof Error ? error.message : String(error)}`
|
|
725
677
|
);
|
|
726
678
|
}
|
|
727
679
|
}
|
|
@@ -801,4 +753,4 @@ var IntelligentCrawler = class extends EventEmitter {
|
|
|
801
753
|
export {
|
|
802
754
|
IntelligentCrawler
|
|
803
755
|
};
|
|
804
|
-
//# sourceMappingURL=chunk-
|
|
756
|
+
//# sourceMappingURL=chunk-GOAOBPOA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/crawl/intelligent-crawler.ts","../src/crawl/article-converter.ts","../src/crawl/markdown-utils.ts","../src/crawl/claude-client.ts"],"sourcesContent":["/**\n * Intelligent web crawler with natural language control\n * Two modes: Intelligent (Claude-driven) and Simple (BFS)\n */\n\nimport { EventEmitter } from 'node:events';\nimport axios from 'axios';\nimport { convertHtmlToMarkdown } from './article-converter.js';\nimport { PythonBridge, type CrawledLink } from './bridge.js';\nimport { ClaudeClient, type CrawlStrategy } from './claude-client.js';\nimport { createLogger, summarizePayload } from '../logging/index.js';\n\nconst logger = createLogger('crawler');\n\nexport interface CrawlOptions {\n crawlInstruction?: string; // Natural language: what to crawl\n extractInstruction?: string; // Natural language: what to extract\n maxPages?: number; // Max pages to crawl (default: 50)\n timeout?: number; // Per-page timeout in ms (default: 30000)\n simple?: boolean; // Force simple BFS mode\n useHeadless?: boolean; // Enable headless browser for JavaScript-rendered sites\n}\n\nexport interface CrawlResult {\n url: string;\n title?: string;\n markdown: string;\n extracted?: string;\n depth?: number;\n}\n\nexport interface CrawlProgress {\n type: 'start' | 'strategy' | 'page' | 'extraction' | 'complete' | 'error';\n pagesVisited: number;\n totalPages: number;\n currentUrl?: string;\n message?: string;\n error?: Error;\n}\n\n/**\n * Intelligent crawler that uses Claude CLI for strategy and extraction\n */\nexport class IntelligentCrawler extends EventEmitter {\n private readonly claudeClient: ClaudeClient;\n private readonly pythonBridge: PythonBridge;\n private readonly visited: Set<string>;\n private stopped: boolean;\n\n constructor() {\n super();\n this.claudeClient = new ClaudeClient();\n this.pythonBridge = new PythonBridge();\n this.visited = new Set();\n this.stopped = false;\n }\n\n /**\n * Crawl a website with intelligent or simple mode\n */\n async *crawl(seedUrl: string, options: CrawlOptions = {}): AsyncIterable<CrawlResult> {\n const { crawlInstruction, extractInstruction, maxPages = 50, simple = false } = options;\n\n this.visited.clear();\n this.stopped = false;\n\n logger.info(\n {\n seedUrl,\n maxPages,\n mode: simple\n ? 'simple'\n : crawlInstruction !== undefined && crawlInstruction !== ''\n ? 'intelligent'\n : 'simple',\n hasExtractInstruction: extractInstruction !== undefined,\n },\n 'Starting crawl'\n );\n\n const startProgress: CrawlProgress = {\n type: 'start',\n pagesVisited: 0,\n totalPages: maxPages,\n };\n this.emit('progress', startProgress);\n\n // Determine mode: intelligent (with crawl instruction) or simple (BFS)\n const useIntelligentMode = !simple && crawlInstruction !== undefined && crawlInstruction !== '';\n\n if (useIntelligentMode) {\n // TypeScript knows crawlInstruction is defined here due to useIntelligentMode check\n yield* this.crawlIntelligent(\n seedUrl,\n crawlInstruction,\n extractInstruction,\n maxPages,\n options.useHeadless ?? false\n );\n } else {\n yield* this.crawlSimple(seedUrl, extractInstruction, maxPages, options.useHeadless ?? false);\n }\n\n logger.info(\n {\n seedUrl,\n pagesVisited: this.visited.size,\n },\n 'Crawl complete'\n );\n\n // Warn if crawl discovered far fewer pages than requested\n if (this.visited.size === 1 && maxPages > 1) {\n const warningProgress: CrawlProgress = {\n type: 'error',\n pagesVisited: this.visited.size,\n totalPages: maxPages,\n message: `Warning: Only crawled 1 page despite maxPages=${String(maxPages)}. Link discovery may have failed. If using --fast mode, try without it for JavaScript-heavy sites.`,\n error: new Error('Low page discovery'),\n };\n this.emit('progress', warningProgress);\n }\n\n const completeProgress: CrawlProgress = {\n type: 'complete',\n pagesVisited: this.visited.size,\n totalPages: this.visited.size,\n };\n this.emit('progress', completeProgress);\n }\n\n /**\n * Intelligent mode: Use Claude to determine which URLs to crawl\n */\n private async *crawlIntelligent(\n seedUrl: string,\n crawlInstruction: string,\n extractInstruction: string | undefined,\n maxPages: number,\n useHeadless: boolean = false\n ): AsyncIterable<CrawlResult> {\n // Check if Claude CLI is available before attempting intelligent mode\n if (!ClaudeClient.isAvailable()) {\n throw new Error('Claude CLI not available: install Claude Code for intelligent crawling');\n }\n\n let strategy: CrawlStrategy;\n\n try {\n // Step 1: Fetch seed page HTML\n const strategyStartProgress: CrawlProgress = {\n type: 'strategy',\n pagesVisited: 0,\n totalPages: maxPages,\n currentUrl: seedUrl,\n message: 'Analyzing page structure with Claude...',\n };\n this.emit('progress', strategyStartProgress);\n\n const seedHtml = await this.fetchHtml(seedUrl, useHeadless);\n\n // Step 2: Ask Claude which URLs to crawl (pass seedUrl for relative URL resolution)\n strategy = await this.claudeClient.determineCrawlUrls(seedUrl, seedHtml, crawlInstruction);\n\n const strategyCompleteProgress: CrawlProgress = {\n type: 'strategy',\n pagesVisited: 0,\n totalPages: maxPages,\n message: `Claude identified ${String(strategy.urls.length)} URLs to crawl: ${strategy.reasoning}`,\n };\n this.emit('progress', strategyCompleteProgress);\n } catch (error) {\n // Re-throw strategy errors - do not fall back silently\n throw error instanceof Error ? error : new Error(String(error));\n }\n\n // Step 3: Crawl each URL from Claude's strategy\n let pagesVisited = 0;\n\n for (const url of strategy.urls) {\n if (this.stopped || pagesVisited >= maxPages) break;\n if (this.visited.has(url)) continue;\n\n try {\n const result = await this.crawlSinglePage(\n url,\n extractInstruction,\n pagesVisited,\n useHeadless\n );\n pagesVisited++;\n yield result;\n } catch (error) {\n const pageErrorProgress: CrawlProgress = {\n type: 'error',\n pagesVisited,\n totalPages: maxPages,\n currentUrl: url,\n error: error instanceof Error ? error : new Error(String(error)),\n };\n this.emit('progress', pageErrorProgress);\n }\n }\n }\n\n /**\n * Simple mode: BFS crawling with depth limit\n */\n private async *crawlSimple(\n seedUrl: string,\n extractInstruction: string | undefined,\n maxPages: number,\n useHeadless: boolean = false\n ): AsyncIterable<CrawlResult> {\n const queue: Array<{ url: string; depth: number }> = [{ url: seedUrl, depth: 0 }];\n const maxDepth = 2; // Default depth limit for simple mode\n let pagesVisited = 0;\n\n while (queue.length > 0 && pagesVisited < maxPages && !this.stopped) {\n const current = queue.shift();\n\n if (!current || this.visited.has(current.url) || current.depth > maxDepth) {\n continue;\n }\n\n try {\n const result = await this.crawlSinglePage(\n current.url,\n extractInstruction,\n pagesVisited,\n useHeadless\n );\n result.depth = current.depth;\n pagesVisited++;\n\n yield result;\n\n // Add links to queue if we haven't reached max depth\n if (current.depth < maxDepth) {\n try {\n const links = await this.extractLinks(current.url, useHeadless);\n\n if (links.length === 0) {\n logger.debug({ url: current.url }, 'No links found - page may be a leaf node');\n } else {\n logger.debug(\n { url: current.url, linkCount: links.length },\n 'Links extracted from page'\n );\n }\n\n for (const link of links) {\n if (!this.visited.has(link) && this.isSameDomain(seedUrl, link)) {\n queue.push({ url: link, depth: current.depth + 1 });\n }\n }\n } catch (error) {\n // Log link extraction failure but continue crawling other pages\n const errorProgress: CrawlProgress = {\n type: 'error',\n pagesVisited,\n totalPages: maxPages,\n currentUrl: current.url,\n message: `Failed to extract links from ${current.url}`,\n error: error instanceof Error ? error : new Error(String(error)),\n };\n this.emit('progress', errorProgress);\n }\n }\n } catch (error) {\n const errorObj = error instanceof Error ? error : new Error(String(error));\n\n // Re-throw non-recoverable errors (extraction failures, Claude CLI not available, headless failures)\n // These represent failures in user-requested functionality that should not be silently skipped\n if (\n errorObj.message.includes('Extraction failed') ||\n errorObj.message.includes('Claude CLI not available') ||\n errorObj.message.includes('Headless fetch failed')\n ) {\n throw errorObj;\n }\n\n // For recoverable errors (page fetch failures), emit progress and continue\n const simpleErrorProgress: CrawlProgress = {\n type: 'error',\n pagesVisited,\n totalPages: maxPages,\n currentUrl: current.url,\n error: errorObj,\n };\n this.emit('progress', simpleErrorProgress);\n }\n }\n }\n\n /**\n * Crawl a single page: fetch, convert to markdown, optionally extract\n */\n private async crawlSinglePage(\n url: string,\n extractInstruction: string | undefined,\n pagesVisited: number,\n useHeadless: boolean = false\n ): Promise<CrawlResult> {\n const pageProgress: CrawlProgress = {\n type: 'page',\n pagesVisited,\n totalPages: 0,\n currentUrl: url,\n };\n this.emit('progress', pageProgress);\n\n // Mark as visited\n this.visited.add(url);\n\n // Fetch HTML\n const html = await this.fetchHtml(url, useHeadless);\n\n // Convert to clean markdown using slurp-ai techniques\n // Note: convertHtmlToMarkdown throws on errors, no need to check success\n const conversion = await convertHtmlToMarkdown(html, url);\n\n logger.debug(\n {\n url,\n title: conversion.title,\n markdownLength: conversion.markdown.length,\n },\n 'Article converted to markdown'\n );\n\n let extracted: string | undefined;\n\n // Optional: Extract specific information using Claude\n if (extractInstruction !== undefined && extractInstruction !== '') {\n // Throw if extraction requested but Claude CLI isn't available\n if (!ClaudeClient.isAvailable()) {\n throw new Error('Claude CLI not available: install Claude Code for extraction');\n }\n\n const extractionProgress: CrawlProgress = {\n type: 'extraction',\n pagesVisited,\n totalPages: 0,\n currentUrl: url,\n };\n this.emit('progress', extractionProgress);\n\n extracted = await this.claudeClient.extractContent(conversion.markdown, extractInstruction);\n }\n\n return {\n url,\n ...(conversion.title !== undefined && { title: conversion.title }),\n markdown: conversion.markdown,\n ...(extracted !== undefined && { extracted }),\n };\n }\n\n /**\n * Fetch HTML content from a URL\n */\n private async fetchHtml(url: string, useHeadless: boolean = false): Promise<string> {\n const startTime = Date.now();\n logger.debug({ url, useHeadless }, 'Fetching HTML');\n\n if (useHeadless) {\n try {\n const result = await this.pythonBridge.fetchHeadless(url);\n const durationMs = Date.now() - startTime;\n logger.info(\n {\n url,\n useHeadless: true,\n durationMs,\n ...summarizePayload(result.html, 'raw-html', url),\n },\n 'Raw HTML fetched'\n );\n return result.html;\n } catch (error) {\n // Wrap with distinctive message so crawlSimple knows not to recover\n throw new Error(\n `Headless fetch failed: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n // Original axios implementation for static sites\n try {\n const response = await axios.get<string>(url, {\n timeout: 30000,\n headers: {\n 'User-Agent': 'Mozilla/5.0 (compatible; bluera-knowledge-crawler/1.0)',\n },\n });\n\n const durationMs = Date.now() - startTime;\n logger.info(\n {\n url,\n useHeadless: false,\n durationMs,\n ...summarizePayload(response.data, 'raw-html', url),\n },\n 'Raw HTML fetched'\n );\n\n return response.data;\n } catch (error) {\n logger.error(\n { url, error: error instanceof Error ? error.message : String(error) },\n 'Failed to fetch HTML'\n );\n throw new Error(\n `Failed to fetch ${url}: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n /**\n * Extract links from a page using Python bridge\n */\n private async extractLinks(url: string, useHeadless: boolean = false): Promise<string[]> {\n try {\n // Use headless mode for link extraction if enabled\n if (useHeadless) {\n const result = await this.pythonBridge.fetchHeadless(url);\n // Extract href strings from link objects (crawl4ai returns objects, not strings)\n return result.links.map((link: CrawledLink | string) => {\n if (typeof link === 'string') return link;\n return link.href;\n });\n }\n\n const result = await this.pythonBridge.crawl(url);\n\n // Validate response structure (handle potential runtime type mismatches)\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- TypeScript types claim pages exists but Python bridge may return invalid structure at runtime\n const firstPage = result.pages?.[0];\n if (!firstPage) {\n throw new Error(`Invalid crawl response structure for ${url}: missing pages array`);\n }\n\n return firstPage.links;\n } catch (error: unknown) {\n // Log the error for debugging\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error({ url, error: errorMessage }, 'Failed to extract links');\n\n // Re-throw the error instead of silently swallowing it\n throw new Error(`Link extraction failed for ${url}: ${errorMessage}`);\n }\n }\n\n /**\n * Check if two URLs are from the same domain\n */\n private isSameDomain(url1: string, url2: string): boolean {\n try {\n const domain1 = new URL(url1).hostname.toLowerCase();\n const domain2 = new URL(url2).hostname.toLowerCase();\n return (\n domain1 === domain2 || domain1.endsWith(`.${domain2}`) || domain2.endsWith(`.${domain1}`)\n );\n } catch {\n return false;\n }\n }\n\n /**\n * Stop the crawler\n */\n async stop(): Promise<void> {\n this.stopped = true;\n await this.pythonBridge.stop();\n }\n}\n","/**\n * Article converter using @extractus/article-extractor and Turndown\n * Produces clean markdown from HTML using slurp-ai techniques\n */\n\nimport { extractFromHtml } from '@extractus/article-extractor';\nimport TurndownService from 'turndown';\nimport { gfm } from 'turndown-plugin-gfm';\nimport { preprocessHtmlForCodeBlocks, cleanupMarkdown } from './markdown-utils.js';\nimport { createLogger, truncateForLog } from '../logging/index.js';\n\nconst logger = createLogger('article-converter');\n\nexport interface ConversionResult {\n markdown: string;\n title?: string;\n}\n\n/**\n * Convert HTML to clean markdown using best practices from slurp-ai\n *\n * Pipeline:\n * 1. Extract main article content (strips navigation, ads, boilerplate)\n * 2. Preprocess HTML (handle MkDocs code blocks)\n * 3. Convert to markdown with Turndown + GFM\n * 4. Cleanup markdown (regex patterns)\n */\nexport async function convertHtmlToMarkdown(html: string, url: string): Promise<ConversionResult> {\n logger.debug({ url, htmlLength: html.length }, 'Starting HTML conversion');\n\n try {\n // Step 1: Extract main article content\n let articleHtml: string;\n let title: string | undefined;\n\n try {\n const article = await extractFromHtml(html, url);\n if (article?.content !== undefined && article.content !== '') {\n articleHtml = article.content;\n title = article.title !== undefined && article.title !== '' ? article.title : undefined;\n logger.debug(\n {\n url,\n title,\n extractedLength: articleHtml.length,\n usedFullHtml: false,\n },\n 'Article content extracted'\n );\n } else {\n // Fallback to full HTML if extraction fails\n articleHtml = html;\n logger.debug(\n { url, usedFullHtml: true },\n 'Article extraction returned empty, using full HTML'\n );\n }\n } catch (extractError) {\n // Fallback to full HTML if extraction fails\n articleHtml = html;\n logger.debug(\n {\n url,\n usedFullHtml: true,\n error: extractError instanceof Error ? extractError.message : String(extractError),\n },\n 'Article extraction failed, using full HTML'\n );\n }\n\n // Step 2: Preprocess HTML for code blocks\n const preprocessed = preprocessHtmlForCodeBlocks(articleHtml);\n\n // Step 3: Configure Turndown with custom rules\n const turndownService = new TurndownService({\n headingStyle: 'atx', // Use # style headings\n codeBlockStyle: 'fenced', // Use ``` style code blocks\n fence: '```',\n emDelimiter: '*',\n strongDelimiter: '**',\n linkStyle: 'inlined',\n });\n\n // Add GitHub Flavored Markdown support (tables, strikethrough, task lists)\n turndownService.use(gfm);\n\n // Custom rule for headings with anchors (from slurp-ai)\n turndownService.addRule('headingsWithAnchors', {\n filter: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'],\n replacement(content: string, node: HTMLElement): string {\n const level = Number(node.nodeName.charAt(1));\n const hashes = '#'.repeat(level);\n const cleanContent = content\n .replace(/\\[\\]\\([^)]*\\)/g, '') // Remove empty links\n .replace(/\\s+/g, ' ') // Normalize whitespace\n .trim();\n return cleanContent !== '' ? `\\n\\n${hashes} ${cleanContent}\\n\\n` : '';\n },\n });\n\n // Convert to markdown\n const rawMarkdown = turndownService.turndown(preprocessed);\n\n // Step 4: Cleanup markdown with comprehensive regex patterns\n const markdown = cleanupMarkdown(rawMarkdown);\n\n logger.debug(\n {\n url,\n title,\n rawMarkdownLength: rawMarkdown.length,\n finalMarkdownLength: markdown.length,\n },\n 'HTML to markdown conversion complete'\n );\n\n // Log markdown preview at trace level\n logger.trace(\n {\n url,\n markdownPreview: truncateForLog(markdown, 1000),\n },\n 'Markdown content preview'\n );\n\n return {\n markdown,\n ...(title !== undefined && { title }),\n };\n } catch (error) {\n logger.error(\n {\n url,\n error: error instanceof Error ? error.message : String(error),\n },\n 'HTML to markdown conversion failed'\n );\n\n // Re-throw errors - do not return graceful degradation\n throw error instanceof Error ? error : new Error(String(error));\n }\n}\n","/**\n * Markdown conversion utilities ported from slurp-ai\n * Source: https://github.com/ratacat/slurp-ai\n *\n * These utilities handle complex documentation site patterns (MkDocs, Sphinx, etc.)\n * and produce clean, well-formatted markdown.\n */\n\nimport * as cheerio from 'cheerio';\n\n/**\n * Detect language from code element class names.\n * Handles various class naming patterns from different highlighters.\n */\nfunction detectLanguageFromClass(className: string | undefined): string {\n if (className === undefined || className === '') return '';\n\n // Common patterns: \"language-python\", \"lang-js\", \"highlight-python\", \"python\", \"hljs language-python\"\n const patterns = [\n /language-(\\w+)/i,\n /lang-(\\w+)/i,\n /highlight-(\\w+)/i,\n /hljs\\s+(\\w+)/i,\n /^(\\w+)$/i,\n ];\n\n for (const pattern of patterns) {\n const match = className.match(pattern);\n if (match?.[1] !== undefined) {\n const lang = match[1].toLowerCase();\n // Filter out common non-language classes\n if (!['hljs', 'highlight', 'code', 'pre', 'block', 'inline'].includes(lang)) {\n return lang;\n }\n }\n }\n\n return '';\n}\n\n/**\n * Escape HTML special characters for safe embedding in HTML.\n */\nfunction escapeHtml(text: string): string {\n return text\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\n/**\n * Preprocess HTML to handle MkDocs/Material theme code blocks.\n *\n * MkDocs wraps code in tables for line numbers:\n * <table><tbody><tr><td>line numbers</td><td><pre><code>code</code></pre></td></tr></tbody></table>\n *\n * This function converts them to standard <pre><code> blocks that Turndown handles correctly.\n * Also strips syntax highlighting spans and empty anchors from code.\n */\nexport function preprocessHtmlForCodeBlocks(html: string): string {\n if (!html || typeof html !== 'string') return html;\n\n const $ = cheerio.load(html);\n\n // Handle MkDocs/Material table-wrapped code blocks\n $('table').each((_i, table) => {\n const $table = $(table);\n\n // Check if this table contains a code block\n const $codeCell = $table.find('td pre code, td div pre code');\n\n if ($codeCell.length > 0) {\n // This is a code block table - extract the code\n const $pre = $codeCell.closest('pre');\n const $code = $codeCell.first();\n\n // Get language from class\n let language = detectLanguageFromClass($code.attr('class'));\n if (!language) {\n language = detectLanguageFromClass($pre.attr('class'));\n }\n\n // Get the text content, stripping all inner HTML tags\n const codeText = $code.text();\n\n // Create a clean pre > code block\n const cleanPre = `<pre><code class=\"language-${language}\">${escapeHtml(codeText)}</code></pre>`;\n\n // Replace the entire table with the clean code block\n $table.replaceWith(cleanPre);\n }\n });\n\n // Strip empty anchor tags used for line numbers\n $('pre a, code a').each((_i, anchor) => {\n const $anchor = $(anchor);\n if (!$anchor.text().trim()) {\n $anchor.remove();\n }\n });\n\n // Strip syntax highlighting spans inside code blocks, keeping only text\n $('pre span, code span').each((_i, span) => {\n const $span = $(span);\n $span.replaceWith($span.text());\n });\n\n // Handle standalone pre blocks that might have spans/anchors\n $('pre').each((_i, pre) => {\n const $pre = $(pre);\n // If this pre has a code child, it was already processed\n if ($pre.find('code').length === 0) {\n // Direct pre without code - get text content\n const text = $pre.text();\n const lang = detectLanguageFromClass($pre.attr('class'));\n $pre.html(`<code class=\"language-${lang}\">${escapeHtml(text)}</code>`);\n }\n });\n\n return $.html();\n}\n\n/**\n * Apply comprehensive cleanup rules to markdown content.\n *\n * Formatting rules:\n * - Double newlines between paragraphs and headings\n * - Double newlines before lists when preceded by normal text\n * - Single newlines between list items\n * - No blank lines inside code blocks\n */\nexport function cleanupMarkdown(markdown: string): string {\n if (!markdown) return '';\n\n const trimmed = markdown.trim();\n if (trimmed === '') return '';\n\n let result = trimmed;\n\n // 0. Fix broken headings where ## is on its own line followed by the text\n // Pattern: \"## \\n\\nSome text\" → \"## Some text\"\n result = result.replace(/^(#{1,6})\\s*\\n\\n+(\\S[^\\n]*)/gm, '$1 $2');\n\n // 0.5. Normalize multiple spaces after heading markers to single space\n // Pattern: \"## Subtitle\" → \"## Subtitle\"\n result = result.replace(/(#{1,6})\\s{2,}/g, '$1 ');\n\n // 1. Fix navigation links with excessive whitespace\n result = result.replace(/\\*\\s+\\[\\s*([^\\n]+?)\\s*\\]\\(([^)]+)\\)/g, '* [$1]($2)');\n\n // 2. Handle headings with specific newline requirements\n\n // Text followed by heading should have a single newline between them (no blank line)\n result = result.replace(/([^\\n])\\n\\n+(#\\s)/g, '$1\\n$2');\n\n // Add double newlines between text and next heading\n result = result.replace(/(Some text\\.)\\n(##\\s)/g, '$1\\n\\n$2');\n\n // Double newlines after a heading when followed by text\n result = result.replace(/(#{1,6}\\s[^\\n]+)\\n([^#\\n])/g, '$1\\n\\n$2');\n\n // Double newlines between headings\n result = result.replace(/(#{1,6}\\s[^\\n]+)\\n(#{1,6}\\s)/g, '$1\\n\\n$2');\n\n // 3. Lists - ensure all list items have single newlines only\n result = result.replace(/(\\* Item 1)\\n\\n+(\\* Item 2)\\n\\n+(\\* Item 3)/g, '$1\\n$2\\n$3');\n\n // 3.5. General list item spacing - ensure single newlines between list items\n result = result.replace(/(^\\*\\s[^\\n]+)\\n{2,}(^\\*\\s)/gm, '$1\\n$2');\n\n // 4. Clean up excessive blank lines (3+ newlines → 2 newlines)\n result = result.replace(/\\n{3,}/g, '\\n\\n');\n\n // 5. Code blocks - no blank lines after opening or before closing backticks\n result = result.replace(/(```[^\\n]*)\\n\\n+/g, '$1\\n');\n result = result.replace(/\\n\\n+```/g, '\\n```');\n\n // 6. Remove empty list items\n result = result.replace(/\\*\\s*\\n\\s*\\*/g, '*');\n\n // 7. Strip any remaining HTML tags that leaked through (common in MkDocs/Material)\n // Remove table structure tags\n result = result.replace(/<\\/?table[^>]*>/gi, '');\n result = result.replace(/<\\/?tbody[^>]*>/gi, '');\n result = result.replace(/<\\/?thead[^>]*>/gi, '');\n result = result.replace(/<\\/?tr[^>]*>/gi, '');\n result = result.replace(/<\\/?td[^>]*>/gi, '');\n result = result.replace(/<\\/?th[^>]*>/gi, '');\n\n // Remove empty anchor tags: <a></a> or <a id=\"...\"></a>\n result = result.replace(/<a[^>]*><\\/a>/gi, '');\n\n // Remove span tags (syntax highlighting remnants)\n result = result.replace(/<\\/?span[^>]*>/gi, '');\n\n // Remove div tags\n result = result.replace(/<\\/?div[^>]*>/gi, '');\n\n // Remove pre/code tags that leaked\n result = result.replace(/<\\/?pre[^>]*>/gi, '');\n result = result.replace(/<\\/?code[^>]*>/gi, '');\n\n // 8. Remove empty markdown links: [](url) and []()\n result = result.replace(/\\[\\]\\([^)]*\\)/g, '');\n\n // 9. Remove codelineno references that leaked into content\n // Pattern: [](_file.md#__codelineno-N-M)\n result = result.replace(/\\[\\]\\([^)]*#__codelineno-[^)]+\\)/g, '');\n\n // Also clean inline codelineno patterns\n result = result.replace(/\\[?\\]?\\([^)]*#__codelineno-[^)]*\\)/g, '');\n\n // 10. Clean up any double-escaped HTML entities that might result\n result = result.replace(/&lt;/g, '<');\n result = result.replace(/&gt;/g, '>');\n result = result.replace(/&amp;/g, '&');\n\n // 11. Final cleanup - normalize excessive whitespace from removed tags\n result = result.replace(/\\n{3,}/g, '\\n\\n');\n result = result.replace(/[ \\t]+\\n/g, '\\n');\n\n return result;\n}\n","/**\n * Claude CLI client for intelligent crawling and extraction\n * Uses `claude -p` programmatically to analyze page structure and extract content\n */\n\nimport { spawn, execSync } from 'node:child_process';\n\n/**\n * Schema for crawl strategy response from Claude\n */\nexport interface CrawlStrategy {\n urls: string[];\n reasoning: string;\n}\n\nconst CRAWL_STRATEGY_SCHEMA = {\n type: 'object',\n properties: {\n urls: {\n type: 'array',\n items: { type: 'string' },\n description: 'List of URLs to crawl based on the instruction',\n },\n reasoning: {\n type: 'string',\n description: 'Brief explanation of why these URLs were selected',\n },\n },\n required: ['urls', 'reasoning'],\n};\n\n/**\n * Client for interacting with Claude Code CLI\n */\nexport class ClaudeClient {\n private readonly timeout: number;\n private static availabilityChecked = false;\n private static available = false;\n\n /**\n * Check if Claude CLI is available in PATH\n * Result is cached after first check for performance\n */\n static isAvailable(): boolean {\n if (!ClaudeClient.availabilityChecked) {\n try {\n execSync('which claude', { stdio: 'ignore' });\n ClaudeClient.available = true;\n } catch {\n ClaudeClient.available = false;\n }\n ClaudeClient.availabilityChecked = true;\n }\n return ClaudeClient.available;\n }\n\n /**\n * Reset availability cache (for testing)\n */\n static resetAvailabilityCache(): void {\n ClaudeClient.availabilityChecked = false;\n ClaudeClient.available = false;\n }\n\n constructor(options: { timeout?: number } = {}) {\n this.timeout = options.timeout ?? 30000; // 30s default\n }\n\n /**\n * Determine which URLs to crawl based on natural language instruction\n *\n * @param seedUrl - The URL of the seed page (for resolving relative URLs)\n * @param seedHtml - HTML content of the seed page\n * @param instruction - Natural language crawl instruction (e.g., \"scrape all Getting Started pages\")\n * @returns List of URLs to crawl with reasoning\n */\n async determineCrawlUrls(\n seedUrl: string,\n seedHtml: string,\n instruction: string\n ): Promise<CrawlStrategy> {\n const prompt = `You are analyzing a webpage to determine which pages to crawl based on the user's instruction.\n\nBase URL: ${seedUrl}\n\nInstruction: ${instruction}\n\nWebpage HTML (analyze the navigation structure, links, and content):\n${this.truncateHtml(seedHtml, 50000)}\n\nBased on the instruction, extract and return a list of absolute URLs that should be crawled. When you encounter relative URLs (starting with \"/\" or without a protocol), resolve them against the Base URL. For example, if Base URL is \"https://example.com/docs\" and you see href=\"/docs/hooks\", return \"https://example.com/docs/hooks\".\n\nLook for navigation menus, sidebars, headers, and link structures that match the instruction.\n\nReturn only URLs that are relevant to the instruction. If the instruction mentions specific sections (e.g., \"Getting Started\"), find links in those sections.`;\n\n try {\n const result = await this.callClaude(prompt, CRAWL_STRATEGY_SCHEMA);\n const rawParsed: unknown = JSON.parse(result);\n\n // Claude CLI with --json-schema returns wrapper: {type, result, structured_output: {...}}\n // Extract structured_output if present, otherwise use raw response\n const parsed = this.extractStructuredOutput(rawParsed);\n\n // Validate and narrow type\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n !('urls' in parsed) ||\n !('reasoning' in parsed) ||\n !Array.isArray(parsed.urls) ||\n parsed.urls.length === 0 ||\n typeof parsed.reasoning !== 'string' ||\n !parsed.urls.every((url) => typeof url === 'string')\n ) {\n throw new Error('Claude returned invalid crawl strategy');\n }\n\n // Type is now properly narrowed - urls is string[] after validation\n return { urls: parsed.urls, reasoning: parsed.reasoning };\n } catch (error) {\n throw new Error(\n `Failed to determine crawl strategy: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n /**\n * Extract specific information from markdown content using natural language\n *\n * @param markdown - Page content in markdown format\n * @param instruction - Natural language extraction instruction (e.g., \"extract pricing info\")\n * @returns Extracted information as text\n */\n async extractContent(markdown: string, instruction: string): Promise<string> {\n const prompt = `${instruction}\n\nContent to analyze:\n${this.truncateMarkdown(markdown, 100000)}`;\n\n try {\n const result = await this.callClaude(prompt);\n return result.trim();\n } catch (error) {\n throw new Error(\n `Failed to extract content: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n /**\n * Call Claude CLI with a prompt\n *\n * @param prompt - The prompt to send to Claude\n * @param jsonSchema - Optional JSON schema for structured output\n * @returns Claude's response as a string\n */\n private async callClaude(prompt: string, jsonSchema?: Record<string, unknown>): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n const args = ['-p'];\n\n // Add JSON schema if provided\n if (jsonSchema) {\n args.push('--json-schema', JSON.stringify(jsonSchema));\n args.push('--output-format', 'json');\n }\n\n const proc = spawn('claude', args, {\n stdio: ['pipe', 'pipe', 'pipe'],\n cwd: process.cwd(),\n env: { ...process.env },\n });\n\n let stdout = '';\n let stderr = '';\n let timeoutId: NodeJS.Timeout | undefined;\n\n // Set timeout\n if (this.timeout > 0) {\n timeoutId = setTimeout(() => {\n proc.kill('SIGTERM');\n reject(new Error(`Claude CLI timed out after ${String(this.timeout)}ms`));\n }, this.timeout);\n }\n\n proc.stdout.on('data', (chunk: Buffer) => {\n stdout += chunk.toString();\n });\n\n proc.stderr.on('data', (chunk: Buffer) => {\n stderr += chunk.toString();\n });\n\n proc.on('close', (code: number | null) => {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n\n if (code === 0) {\n resolve(stdout.trim());\n } else {\n reject(\n new Error(`Claude CLI exited with code ${String(code)}${stderr ? `: ${stderr}` : ''}`)\n );\n }\n });\n\n proc.on('error', (err) => {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n reject(new Error(`Failed to spawn Claude CLI: ${err.message}`));\n });\n\n // Write prompt to stdin\n proc.stdin.write(prompt);\n proc.stdin.end();\n });\n }\n\n /**\n * Truncate HTML to a maximum length (keep important parts)\n */\n private truncateHtml(html: string, maxLength: number): string {\n if (html.length <= maxLength) return html;\n\n // Try to keep the beginning (usually has navigation)\n return `${html.substring(0, maxLength)}\\n\\n[... HTML truncated ...]`;\n }\n\n /**\n * Truncate markdown to a maximum length\n */\n private truncateMarkdown(markdown: string, maxLength: number): string {\n if (markdown.length <= maxLength) return markdown;\n\n return `${markdown.substring(0, maxLength)}\\n\\n[... content truncated ...]`;\n }\n\n /**\n * Type guard to check if value is a record (plain object)\n */\n private isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n }\n\n /**\n * Extract structured_output from Claude CLI wrapper format if present.\n * Claude CLI with --json-schema returns: {type, result, structured_output: {...}}\n * This method extracts the inner structured_output, or returns the raw value if not wrapped.\n */\n private extractStructuredOutput(rawParsed: unknown): unknown {\n if (this.isRecord(rawParsed) && 'structured_output' in rawParsed) {\n const structuredOutput = rawParsed['structured_output'];\n if (typeof structuredOutput === 'object') {\n return structuredOutput;\n }\n }\n return rawParsed;\n }\n}\n"],"mappings":";;;;;;;;AAKA,SAAS,oBAAoB;AAC7B,OAAO,WAAW;;;ACDlB,SAAS,uBAAuB;AAChC,OAAO,qBAAqB;AAC5B,SAAS,WAAW;;;ACCpB,YAAY,aAAa;AAMzB,SAAS,wBAAwB,WAAuC;AACtE,MAAI,cAAc,UAAa,cAAc,GAAI,QAAO;AAGxD,QAAM,WAAW;AAAA,IACf;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,aAAW,WAAW,UA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this.lanceStore = lanceStore;
|
|
11
11
|
}
|
|
12
|
-
async watch(store, debounceMs
|
|
12
|
+
async watch(store, debounceMs, onReindex, onError) {
|
|
13
13
|
if (this.watchers.has(store.id)) {
|
|
14
14
|
return Promise.resolve();
|
|
15
15
|
}
|
|
@@ -28,16 +28,18 @@ var WatchService = class {
|
|
|
28
28
|
await this.lanceStore.initialize(store.id);
|
|
29
29
|
await this.indexService.indexStore(store);
|
|
30
30
|
onReindex?.();
|
|
31
|
-
} catch (
|
|
32
|
-
|
|
31
|
+
} catch (e) {
|
|
32
|
+
const error = e instanceof Error ? e : new Error(String(e));
|
|
33
|
+
onError(error);
|
|
33
34
|
}
|
|
34
35
|
})();
|
|
35
36
|
}, debounceMs);
|
|
36
37
|
this.pendingTimeouts.set(store.id, timeout);
|
|
37
38
|
};
|
|
38
39
|
watcher.on("all", reindexHandler);
|
|
39
|
-
watcher.on("error", (
|
|
40
|
-
|
|
40
|
+
watcher.on("error", (e) => {
|
|
41
|
+
const error = e instanceof Error ? e : new Error(String(e));
|
|
42
|
+
onError(error);
|
|
41
43
|
});
|
|
42
44
|
this.watchers.set(store.id, watcher);
|
|
43
45
|
return Promise.resolve();
|
|
@@ -64,4 +66,4 @@ var WatchService = class {
|
|
|
64
66
|
export {
|
|
65
67
|
WatchService
|
|
66
68
|
};
|
|
67
|
-
//# sourceMappingURL=chunk-
|
|
69
|
+
//# sourceMappingURL=chunk-HRQD3MPH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/services/watch.service.ts"],"sourcesContent":["import { watch, type FSWatcher } from 'chokidar';\nimport type { IndexService } from './index.service.js';\nimport type { LanceStore } from '../db/lance.js';\nimport type { FileStore, RepoStore } from '../types/store.js';\n\nexport class WatchService {\n private readonly watchers: Map<string, FSWatcher> = new Map();\n private readonly pendingTimeouts: Map<string, NodeJS.Timeout> = new Map();\n private readonly indexService: IndexService;\n private readonly lanceStore: LanceStore;\n\n constructor(indexService: IndexService, lanceStore: LanceStore) {\n this.indexService = indexService;\n this.lanceStore = lanceStore;\n }\n\n async watch(\n store: FileStore | RepoStore,\n debounceMs: number,\n onReindex: (() => void) | undefined,\n onError: (error: Error) => void\n ): Promise<void> {\n if (this.watchers.has(store.id)) {\n return Promise.resolve(); // Already watching\n }\n\n let timeout: NodeJS.Timeout | null = null;\n\n const watcher = watch(store.path, {\n ignored: /(^|[/\\\\])\\.(git|node_modules|dist|build)/,\n persistent: true,\n ignoreInitial: true,\n });\n\n const reindexHandler = (): void => {\n if (timeout) clearTimeout(timeout);\n timeout = setTimeout(() => {\n this.pendingTimeouts.delete(store.id);\n void (async (): Promise<void> => {\n try {\n await this.lanceStore.initialize(store.id);\n await this.indexService.indexStore(store);\n onReindex?.();\n } catch (e) {\n const error = e instanceof Error ? e : new Error(String(e));\n onError(error);\n }\n })();\n }, debounceMs);\n this.pendingTimeouts.set(store.id, timeout);\n };\n\n watcher.on('all', reindexHandler);\n\n watcher.on('error', (e) => {\n const error = e instanceof Error ? e : new Error(String(e));\n onError(error);\n });\n\n this.watchers.set(store.id, watcher);\n return Promise.resolve();\n }\n\n async unwatch(storeId: string): Promise<void> {\n // Clear any pending timeout to prevent timer leak\n const pendingTimeout = this.pendingTimeouts.get(storeId);\n if (pendingTimeout) {\n clearTimeout(pendingTimeout);\n this.pendingTimeouts.delete(storeId);\n }\n\n const watcher = this.watchers.get(storeId);\n if (watcher) {\n await watcher.close();\n this.watchers.delete(storeId);\n }\n }\n\n async unwatchAll(): Promise<void> {\n for (const [id] of this.watchers) {\n await this.unwatch(id);\n }\n }\n}\n"],"mappings":";AAAA,SAAS,aAA6B;AAK/B,IAAM,eAAN,MAAmB;AAAA,EACP,WAAmC,oBAAI,IAAI;AAAA,EAC3C,kBAA+C,oBAAI,IAAI;AAAA,EACvD;AAAA,EACA;AAAA,EAEjB,YAAY,cAA4B,YAAwB;AAC9D,SAAK,eAAe;AACpB,SAAK,aAAa;AAAA,EACpB;AAAA,EAEA,MAAM,MACJ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O;AAAA,IAC9B;AAAA,EACF;AAAA,EAEA,MAAM,aAA4B;AAChC,eAAW,CAAC,EAAE,KAAK,KAAK,UAAU;AAChC,YAAM,KAAK,QAAQ,EAAE;AAAA,IACvB;AAAA,EACF;AACF;","names":[]}
|
|
@@ -323,8 +323,9 @@ var JobService = class {
|
|
|
323
323
|
const content = fs.readFileSync(jobFile, "utf-8");
|
|
324
324
|
return JSON.parse(content);
|
|
325
325
|
} catch (error) {
|
|
326
|
-
|
|
327
|
-
|
|
326
|
+
throw new Error(
|
|
327
|
+
`Failed to read job ${jobId}: ${error instanceof Error ? error.message : String(error)}`
|
|
328
|
+
);
|
|
328
329
|
}
|
|
329
330
|
}
|
|
330
331
|
/**
|
|
@@ -352,7 +353,9 @@ var JobService = class {
|
|
|
352
353
|
jobs.push(job);
|
|
353
354
|
}
|
|
354
355
|
} catch (error) {
|
|
355
|
-
|
|
356
|
+
throw new Error(
|
|
357
|
+
`Failed to read job file ${file}: ${error instanceof Error ? error.message : String(error)}`
|
|
358
|
+
);
|
|
356
359
|
}
|
|
357
360
|
}
|
|
358
361
|
jobs.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());
|
|
@@ -413,7 +416,9 @@ var JobService = class {
|
|
|
413
416
|
fs.unlinkSync(jobFile);
|
|
414
417
|
cleaned++;
|
|
415
418
|
} catch (error) {
|
|
416
|
-
|
|
419
|
+
throw new Error(
|
|
420
|
+
`Failed to delete job file ${job.id}: ${error instanceof Error ? error.message : String(error)}`
|
|
421
|
+
);
|
|
417
422
|
}
|
|
418
423
|
}
|
|
419
424
|
}
|
|
@@ -431,8 +436,9 @@ var JobService = class {
|
|
|
431
436
|
fs.unlinkSync(jobFile);
|
|
432
437
|
return true;
|
|
433
438
|
} catch (error) {
|
|
434
|
-
|
|
435
|
-
|
|
439
|
+
throw new Error(
|
|
440
|
+
`Failed to delete job ${jobId}: ${error instanceof Error ? error.message : String(error)}`
|
|
441
|
+
);
|
|
436
442
|
}
|
|
437
443
|
}
|
|
438
444
|
/**
|
|
@@ -2572,6 +2578,16 @@ var CodeUnitService = class {
|
|
|
2572
2578
|
type = "class";
|
|
2573
2579
|
break;
|
|
2574
2580
|
}
|
|
2581
|
+
if (line.match(new RegExp(`interface\\s+${symbolName}(?:\\s|{|<)`))) {
|
|
2582
|
+
startLine = i + 1;
|
|
2583
|
+
type = "interface";
|
|
2584
|
+
break;
|
|
2585
|
+
}
|
|
2586
|
+
if (line.match(new RegExp(`type\\s+${symbolName}(?:\\s|=|<)`))) {
|
|
2587
|
+
startLine = i + 1;
|
|
2588
|
+
type = "type";
|
|
2589
|
+
break;
|
|
2590
|
+
}
|
|
2575
2591
|
if (line.match(new RegExp(`(?:const|let|var)\\s+${symbolName}\\s*=`))) {
|
|
2576
2592
|
startLine = i + 1;
|
|
2577
2593
|
type = "const";
|
|
@@ -2582,6 +2598,23 @@ var CodeUnitService = class {
|
|
|
2582
2598
|
let endLine = startLine;
|
|
2583
2599
|
let braceCount = 0;
|
|
2584
2600
|
let foundFirstBrace = false;
|
|
2601
|
+
if (type === "type") {
|
|
2602
|
+
const firstLine2 = lines[startLine - 1] ?? "";
|
|
2603
|
+
if (!firstLine2.includes("{") && firstLine2.includes(";")) {
|
|
2604
|
+
endLine = startLine;
|
|
2605
|
+
const fullContent2 = firstLine2;
|
|
2606
|
+
const signature2 = this.extractSignature(firstLine2, symbolName, type);
|
|
2607
|
+
return {
|
|
2608
|
+
type,
|
|
2609
|
+
name: symbolName,
|
|
2610
|
+
signature: signature2,
|
|
2611
|
+
fullContent: fullContent2,
|
|
2612
|
+
startLine,
|
|
2613
|
+
endLine,
|
|
2614
|
+
language
|
|
2615
|
+
};
|
|
2616
|
+
}
|
|
2617
|
+
}
|
|
2585
2618
|
let inSingleQuote = false;
|
|
2586
2619
|
let inDoubleQuote = false;
|
|
2587
2620
|
let inTemplateLiteral = false;
|
|
@@ -2672,6 +2705,16 @@ var CodeUnitService = class {
|
|
|
2672
2705
|
if (type === "class") {
|
|
2673
2706
|
return `class ${name}`;
|
|
2674
2707
|
}
|
|
2708
|
+
if (type === "interface") {
|
|
2709
|
+
return `interface ${name}`;
|
|
2710
|
+
}
|
|
2711
|
+
if (type === "type") {
|
|
2712
|
+
const typeMatch = sig.match(new RegExp(`type\\s+(${name}(?:<[^>]+>)?)\\s*=`));
|
|
2713
|
+
if (typeMatch?.[1] !== void 0 && typeMatch[1].length > 0) {
|
|
2714
|
+
return `type ${typeMatch[1]}`;
|
|
2715
|
+
}
|
|
2716
|
+
return `type ${name}`;
|
|
2717
|
+
}
|
|
2675
2718
|
if (type === "const") {
|
|
2676
2719
|
const arrowMatch = sig.match(
|
|
2677
2720
|
new RegExp(
|
|
@@ -3640,6 +3683,9 @@ async function cloneRepository(options) {
|
|
|
3640
3683
|
git.stderr.on("data", (data) => {
|
|
3641
3684
|
stderr += data.toString();
|
|
3642
3685
|
});
|
|
3686
|
+
git.on("error", (error) => {
|
|
3687
|
+
resolve3(err(error));
|
|
3688
|
+
});
|
|
3643
3689
|
git.on("close", (code) => {
|
|
3644
3690
|
if (code === 0) {
|
|
3645
3691
|
resolve3(ok(targetDir));
|
|
@@ -3993,6 +4039,8 @@ var PythonBridge = class {
|
|
|
3993
4039
|
process = null;
|
|
3994
4040
|
pending = /* @__PURE__ */ new Map();
|
|
3995
4041
|
stoppingIntentionally = false;
|
|
4042
|
+
stdoutReadline = null;
|
|
4043
|
+
stderrReadline = null;
|
|
3996
4044
|
start() {
|
|
3997
4045
|
if (this.process) return Promise.resolve();
|
|
3998
4046
|
logger3.debug("Starting Python bridge process");
|
|
@@ -4015,8 +4063,8 @@ var PythonBridge = class {
|
|
|
4015
4063
|
this.stoppingIntentionally = false;
|
|
4016
4064
|
});
|
|
4017
4065
|
if (this.process.stderr) {
|
|
4018
|
-
|
|
4019
|
-
|
|
4066
|
+
this.stderrReadline = createInterface({ input: this.process.stderr });
|
|
4067
|
+
this.stderrReadline.on("line", (line) => {
|
|
4020
4068
|
logger3.warn({ stderr: line }, "Python bridge stderr output");
|
|
4021
4069
|
});
|
|
4022
4070
|
}
|
|
@@ -4025,8 +4073,8 @@ var PythonBridge = class {
|
|
|
4025
4073
|
this.process = null;
|
|
4026
4074
|
return Promise.reject(new Error("Python bridge process stdout is null"));
|
|
4027
4075
|
}
|
|
4028
|
-
|
|
4029
|
-
|
|
4076
|
+
this.stdoutReadline = createInterface({ input: this.process.stdout });
|
|
4077
|
+
this.stdoutReadline.on("line", (line) => {
|
|
4030
4078
|
if (!line.trim().startsWith("{")) {
|
|
4031
4079
|
return;
|
|
4032
4080
|
}
|
|
@@ -4188,6 +4236,14 @@ var PythonBridge = class {
|
|
|
4188
4236
|
return new Promise((resolve3) => {
|
|
4189
4237
|
this.stoppingIntentionally = true;
|
|
4190
4238
|
this.rejectAllPending(new Error("Python bridge stopped"));
|
|
4239
|
+
if (this.stdoutReadline) {
|
|
4240
|
+
this.stdoutReadline.close();
|
|
4241
|
+
this.stdoutReadline = null;
|
|
4242
|
+
}
|
|
4243
|
+
if (this.stderrReadline) {
|
|
4244
|
+
this.stderrReadline.close();
|
|
4245
|
+
this.stderrReadline = null;
|
|
4246
|
+
}
|
|
4191
4247
|
const proc = this.process;
|
|
4192
4248
|
if (proc === null) {
|
|
4193
4249
|
resolve3();
|
|
@@ -4419,18 +4475,28 @@ async function createServices(configPath, dataDir, projectRoot) {
|
|
|
4419
4475
|
}
|
|
4420
4476
|
async function destroyServices(services) {
|
|
4421
4477
|
logger4.info("Shutting down services");
|
|
4478
|
+
const errors = [];
|
|
4422
4479
|
try {
|
|
4423
4480
|
await services.lance.closeAsync();
|
|
4424
4481
|
} catch (e) {
|
|
4425
|
-
|
|
4482
|
+
const error = e instanceof Error ? e : new Error(String(e));
|
|
4483
|
+
logger4.error({ error }, "Error closing LanceStore");
|
|
4484
|
+
errors.push(error);
|
|
4426
4485
|
}
|
|
4427
4486
|
try {
|
|
4428
4487
|
await services.pythonBridge.stop();
|
|
4429
4488
|
} catch (e) {
|
|
4430
|
-
|
|
4489
|
+
const error = e instanceof Error ? e : new Error(String(e));
|
|
4490
|
+
logger4.error({ error }, "Error stopping Python bridge");
|
|
4491
|
+
errors.push(error);
|
|
4431
4492
|
}
|
|
4432
4493
|
await new Promise((resolve3) => setTimeout(resolve3, 100));
|
|
4433
4494
|
await shutdownLogger();
|
|
4495
|
+
if (errors.length === 1 && errors[0] !== void 0) {
|
|
4496
|
+
throw new Error(`Service shutdown failed: ${errors[0].message}`, { cause: errors[0] });
|
|
4497
|
+
} else if (errors.length > 1) {
|
|
4498
|
+
throw new AggregateError(errors, "Multiple errors during service shutdown");
|
|
4499
|
+
}
|
|
4434
4500
|
}
|
|
4435
4501
|
|
|
4436
4502
|
export {
|
|
@@ -4453,4 +4519,4 @@ export {
|
|
|
4453
4519
|
createServices,
|
|
4454
4520
|
destroyServices
|
|
4455
4521
|
};
|
|
4456
|
-
//# sourceMappingURL=chunk-
|
|
4522
|
+
//# sourceMappingURL=chunk-QEHSDQTL.js.map
|