@arabold/docs-mcp-server 3.4.1 → 3.6.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.
- package/README.md +2 -1
- package/db/migrations/020-add-page-chunk-count.sql +51 -0
- package/dist/assets/index-DCTpWPWQ.js +70 -0
- package/dist/assets/index-DCTpWPWQ.js.map +1 -0
- package/dist/index.html +1 -1
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/{main-Cb6JaTXM.js → main-CBgiSgoD.js} +1749 -520
- package/dist/main-CBgiSgoD.js.map +1 -0
- package/package.json +19 -4
- package/public/assets/index-DCTpWPWQ.js +70 -0
- package/public/assets/index-DCTpWPWQ.js.map +1 -0
- package/public/index.html +1 -1
- package/dist/assets/index-DR-3PGgZ.js +0 -70
- package/dist/assets/index-DR-3PGgZ.js.map +0 -1
- package/dist/main-Cb6JaTXM.js.map +0 -1
- package/public/assets/index-DR-3PGgZ.js +0 -70
- package/public/assets/index-DR-3PGgZ.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"main-Cb6JaTXM.js","names":["unhandled","toEnqueueError","fs","fs","URL","element","STRUCTURAL_DECL_TYPES","CONTENT_DECL_TYPES","isCandidateBoundary","isLocalHelper","findDocumentationStart","extractName","classifyBoundaryKind","fs","fsPromises","uuidv4","encodeToToon","t","t","t","t"],"sources":["../src/store/types.ts","../src/store/errors.ts","../src/store/embeddings/EmbeddingConfig.ts","../src/store/embeddings/FixedDimensionEmbeddings.ts","../src/store/embeddings/EmbeddingFactory.ts","../src/telemetry/sanitizer.ts","../src/utils/paths.ts","../src/telemetry/TelemetryConfig.ts","../src/events/types.ts","../src/pipeline/types.ts","../src/telemetry/postHogClient.ts","../src/telemetry/telemetry.ts","../src/telemetry/TelemetryService.ts","../src/events/EventBusService.ts","../src/utils/serverOrigin.ts","../src/utils/config.ts","../src/events/RemoteEventProxy.ts","../src/pipeline/trpc/interfaces.ts","../src/pipeline/PipelineClient.ts","../src/utils/errors.ts","../src/utils/mimeTypeUtils.ts","../src/utils/url.ts","../src/scraper/utils/defaultPatterns.ts","../src/scraper/utils/patternMatcher.ts","../src/utils/accessPolicy.ts","../src/scraper/fetcher/challenge.ts","../src/scraper/fetcher/FingerprintGenerator.ts","../src/scraper/fetcher/headers.ts","../src/utils/timeout.ts","../src/scraper/fetcher/ManagedBrowser.ts","../src/scraper/fetcher/types.ts","../src/scraper/fetcher/BrowserFetcher.ts","../src/scraper/fetcher/FileFetcher.ts","../src/pipeline/errors.ts","../src/scraper/fetcher/HostBackoff.ts","../src/scraper/fetcher/HttpFetcher.ts","../src/scraper/fetcher/AutoDetectFetcher.ts","../src/scraper/types.ts","../src/scraper/utils/llmsTxtParser.ts","../src/scraper/utils/scope.ts","../src/scraper/strategies/BaseScraperStrategy.ts","../src/utils/dom.ts","../src/splitter/GreedySplitter.ts","../src/splitter/errors.ts","../src/splitter/splitters/CodeContentSplitter.ts","../src/splitter/splitters/fenceState.ts","../src/splitter/splitters/TextContentSplitter.ts","../src/splitter/splitters/ListContentSplitter.ts","../src/splitter/splitters/TableContentSplitter.ts","../src/splitter/SemanticMarkdownSplitter.ts","../src/scraper/pipelines/BasePipeline.ts","../src/scraper/pipelines/DocumentPipeline.ts","../src/scraper/middleware/HtmlCheerioParserMiddleware.ts","../src/scraper/middleware/HtmlLinkExtractorMiddleware.ts","../src/scraper/middleware/HtmlMetadataExtractorMiddleware.ts","../src/scraper/middleware/HtmlNormalizationMiddleware.ts","../src/scraper/utils/SimpleMemoryCache.ts","../src/scraper/middleware/subresourceBlocklist.ts","../src/scraper/middleware/HtmlPlaywrightMiddleware.ts","../src/scraper/middleware/HtmlSanitizerMiddleware.ts","../src/scraper/middleware/HtmlToMarkdownMiddleware.ts","../src/scraper/utils/charset.ts","../src/scraper/utils/buffer.ts","../src/scraper/pipelines/HtmlPipeline.ts","../src/splitter/TextDocumentSplitter.ts","../src/splitter/JsonDocumentSplitter.ts","../src/scraper/pipelines/JsonPipeline.ts","../src/scraper/middleware/MarkdownLinkExtractorMiddleware.ts","../src/scraper/middleware/MarkdownMetadataExtractorMiddleware.ts","../src/scraper/pipelines/MarkdownPipeline.ts","../src/splitter/treesitter/parsers/PythonParser.ts","../src/splitter/treesitter/parsers/TypeScriptParser.ts","../src/splitter/treesitter/LanguageParserRegistry.ts","../src/splitter/treesitter/TreesitterSourceCodeSplitter.ts","../src/scraper/pipelines/SourceCodePipeline.ts","../src/scraper/pipelines/TextPipeline.ts","../src/scraper/pipelines/PipelineFactory.ts","../src/scraper/strategies/GitHubRepoProcessor.ts","../src/scraper/strategies/GitHubWikiProcessor.ts","../src/scraper/strategies/github-auth.ts","../src/scraper/strategies/GitHubScraperStrategy.ts","../src/utils/archive/TarAdapter.ts","../src/utils/archive/ZipAdapter.ts","../src/utils/archive/ArchiveFactory.ts","../src/scraper/strategies/LocalFileStrategy.ts","../src/scraper/pipelines/capability.ts","../src/scraper/strategies/WebScraperStrategy.ts","../src/scraper/strategies/NpmScraperStrategy.ts","../src/scraper/strategies/PyPiScraperStrategy.ts","../src/scraper/ScraperRegistry.ts","../src/scraper/ScraperService.ts","../src/pipeline/PipelineWorker.ts","../src/pipeline/PipelineManager.ts","../src/store/DocumentManagementClient.ts","../src/utils/version.ts","../src/store/assembly/strategies/HierarchicalAssemblyStrategy.ts","../src/store/assembly/strategies/MarkdownAssemblyStrategy.ts","../src/store/assembly/ContentAssemblyStrategyFactory.ts","../src/store/DocumentRetrieverService.ts","../src/store/applyMigrations.ts","../src/store/DocumentStore.ts","../src/store/DocumentManagementService.ts","../src/services/apiClient.ts","../src/services/backend.ts","../src/cli/output.ts","../src/cli/utils.ts","../src/cli/commands/compact.ts","../src/cli/commands/config.ts","../src/auth/JwtAccessTokenVerifier.ts","../src/auth/protectedResourceMetadata.ts","../src/app/originPolicy.ts","../src/tools/errors.ts","../src/mcp/defaultInstructions.ts","../src/mcp/utils.ts","../src/mcp/mcpServer.ts","../src/tools/CancelJobTool.ts","../src/tools/FetchUrlTool.ts","../src/tools/FindVersionTool.ts","../src/tools/GetJobInfoTool.ts","../src/tools/ListJobsTool.ts","../src/tools/ListLibrariesTool.ts","../src/tools/ListPagesTool.ts","../src/tools/ReadPageTool.ts","../src/tools/RefreshVersionTool.ts","../src/tools/RemoveTool.ts","../src/tools/ScrapeTool.ts","../src/tools/SearchTool.ts","../src/mcp/tools.ts","../src/services/mcpService.ts","../src/services/systemInfo.ts","../src/events/trpc/router.ts","../src/pipeline/trpc/router.ts","../src/store/trpc/router.ts","../src/services/systemHealthRouter.ts","../src/services/appRouter.ts","../src/services/trpcService.ts","../src/utils/banner.ts","../src/app/basePath.ts","../src/app/AppServer.ts","../src/app/index.ts","../src/mcp/startStdioServer.ts","../src/cli/options.ts","../src/cli/services.ts","../src/cli/commands/default.ts","../src/cli/commands/fetchUrl.ts","../src/cli/commands/findVersion.ts","../src/cli/commands/list.ts","../src/cli/commands/mcp.ts","../src/cli/JobOutputFollower.ts","../src/cli/commands/refresh.ts","../src/cli/commands/remove.ts","../src/cli/commands/scrape.ts","../src/cli/commands/search.ts","../src/cli/commands/web.ts","../src/cli/commands/worker.ts","../src/cli/index.ts","../src/cli/main.ts"],"sourcesContent":["import type { ScrapeMode } from \"../scraper/types\";\n\n/**\n * Database page record type matching the pages table schema\n */\nexport interface DbPage {\n id: number;\n version_id: number;\n url: string;\n title: string | null;\n etag: string | null;\n last_modified: string | null;\n source_content_type: string | null;\n content_type: string | null;\n depth: number | null;\n /**\n * Where this page's content was retrieved from, when that differs from `url`.\n *\n * NULL means the two coincide, which is true of every page whose content came\n * from its own address — and of every row written before representations were\n * resolved to a shared identity. Readers coalesce to `url`.\n */\n content_url: string | null;\n created_at: string;\n updated_at: string;\n}\n\n/**\n * Chunk-level metadata stored with each document chunk.\n * Contains hierarchical information about the chunk's position within the page.\n */\nexport interface DbChunkMetadata {\n level?: number; // Hierarchical level in document\n path?: string[]; // Hierarchical path in document\n // TODO: Check if `types` is properly used\n types?: string[]; // Types of content in this chunk (e.g., \"text\", \"code\", \"table\")\n // TODO: Enable additional metadata fields again once we have a clear schema for what metadata we want to store with each chunk.\n // Allow for additional chunk-specific metadata\n // [key: string]: unknown;\n}\n\n/**\n * Database document record type matching the documents table schema\n */\nexport interface DbChunk {\n id: string;\n page_id: number; // Foreign key to pages table\n content: string;\n metadata: DbChunkMetadata; // Chunk-specific metadata (level, path, etc.)\n sort_order: number;\n created_at: string;\n score: number | null; // Added during search queries\n}\n\n/**\n * Represents the result of a JOIN between the documents and pages tables.\n * It includes all fields from a document chunk plus the relevant page-level metadata.\n */\nexport interface DbPageChunk extends DbChunk {\n url: string;\n title?: string | null;\n source_content_type?: string | null;\n content_type?: string | null;\n content_url?: string | null;\n}\n\n/**\n * Represents the ranking information for a search result, including both\n * vector and full-text search ranks.\n */\nexport interface DbChunkRank {\n score: number;\n vec_rank?: number;\n fts_rank?: number;\n}\n\n/**\n * Utility type for handling SQLite query results that may be undefined\n */\nexport type DbQueryResult<T> = T | undefined;\n\n/**\n * Search result type returned by the DocumentRetrieverService\n */\nexport interface StoreSearchResult {\n url: string;\n /**\n * Where the content was actually retrieved from, when that differs from\n * `url`.\n *\n * `url` is the page's identity, which can be derived rather than observed: a\n * page published as `/guide.md` is recorded as `/guide`, and a site need not\n * serve anything at the latter. Callers showing a link to the source should\n * prefer this when it is set, so the link goes somewhere that answers.\n */\n contentUrl?: string | null;\n content: string;\n score: number | null;\n mimeType?: string | null;\n sourceMimeType?: string | null;\n}\n\n/**\n * Represents the possible states of a version's indexing status.\n * These statuses are stored in the database and persist across server restarts.\n */\nexport enum VersionStatus {\n NOT_INDEXED = \"not_indexed\", // Version created but never indexed\n QUEUED = \"queued\", // Waiting in pipeline queue\n RUNNING = \"running\", // Currently being indexed\n COMPLETED = \"completed\", // Successfully indexed\n FAILED = \"failed\", // Indexing failed\n CANCELLED = \"cancelled\", // Indexing was cancelled\n UPDATING = \"updating\", // Re-indexing existing version\n}\n\n/**\n * Scraper options stored with each version for reproducible indexing.\n * Excludes runtime-only fields like signal, library, version, and url.\n */\nexport interface VersionScraperOptions {\n // Core scraping parameters\n maxPages?: number;\n maxDepth?: number;\n scope?: \"subpages\" | \"hostname\" | \"domain\";\n followRedirects?: boolean;\n maxConcurrency?: number;\n ignoreErrors?: boolean;\n\n // Content filtering\n excludeSelectors?: string[];\n includePatterns?: string[];\n excludePatterns?: string[];\n\n // Processing options\n preserveHashes?: boolean;\n scrapeMode?: ScrapeMode;\n headers?: Record<string, string>;\n}\n\n/**\n * Unified return type for retrieving stored scraping configuration for a version.\n * Includes the original source URL and the parsed scraper options used during indexing.\n */\nexport interface StoredScraperOptions {\n sourceUrl: string;\n options: VersionScraperOptions;\n}\n\n/**\n * Alias for the unified scraping configuration returned by the service.\n * Prefer ScraperConfig in new code; StoredScraperOptions remains for backward-compat.\n */\nexport type ScraperConfig = StoredScraperOptions;\n\n/**\n * Canonical reference to a library version in the domain layer.\n * Version uses empty string for unversioned content.\n */\nexport interface VersionRef {\n library: string;\n version: string; // empty string for unversioned\n}\n\n/** A version found or claimed in the store. */\nexport interface ResolvedVersion {\n versionId: number;\n /** The library's stored display name. */\n library: string;\n}\n\n/**\n * Normalizes a version label for storage and lookup.\n *\n * This is the single write contract for version labels: trim surrounding\n * whitespace, lowercase, and treat an empty result as unversioned. The label is\n * otherwise stored verbatim — it is never validated, coerced or rejected, since\n * a version label is not guaranteed to be a semantic version (`stable` and\n * `1.20` are as legitimate as `1.20.0`).\n *\n * @param version Version label as supplied by a caller, if any.\n * @returns The normalized label, or an empty string for unversioned content.\n */\nexport function normalizeVersionLabel(version?: string | null): string {\n return (version ?? \"\").trim().toLowerCase();\n}\n\n/**\n * Computes a library's lookup key.\n *\n * The counterpart to {@link normalizeVersionLabel}: trim and lowercase (the\n * Unicode default lowercase mapping, without full case folding), so a library\n * is one row however its name was typed. The key is what `libraries.name`\n * stores and every lookup compares; the name as entered lives on as the display\n * name ({@link normalizeLibraryDisplayName}).\n *\n * @param library Library name as supplied by a caller.\n * @returns The lookup key.\n */\nexport function normalizeLibraryName(library: string): string {\n return library.trim().toLowerCase();\n}\n\n/**\n * Whether two library names refer to the same library.\n *\n * The one comparison every caller-facing lookup uses, so the identity rule\n * lives in a single place.\n *\n * @param a A library name in any casing or padding.\n * @param b Another library name.\n */\nexport function libraryNamesMatch(a: string, b: string): boolean {\n return normalizeLibraryName(a) === normalizeLibraryName(b);\n}\n\n/**\n * Computes a library's display name: the name as entered, trimmed only.\n *\n * Case, inner spacing, punctuation and non-ASCII characters are preserved, so\n * `Next.js Docs` is stored and shown exactly that way.\n *\n * @param library Library name as supplied by a caller.\n * @returns The display name to store for a new library.\n */\nexport function normalizeLibraryDisplayName(library: string): string {\n return library.trim();\n}\n\n/** Longest name accepted for a new library, counted in Unicode code points. */\nexport const MAX_LIBRARY_NAME_LENGTH = 100;\n\n/** Unicode general category Cc: C0 controls, DEL and C1 controls such as tab, newline and ESC. */\nexport const CONTROL_CHARACTER = /\\p{Cc}/u;\n\n/**\n * Explains why a name is unacceptable for a new library.\n *\n * Only creation is validated; existing libraries stay reachable under their\n * stored names. Format characters (Cf) are allowed because emoji sequences rely\n * on the zero-width joiner. Pure, so the web client can show the same message.\n *\n * @param displayName Name submitted for a new library; trimmed before checking.\n * @returns The broken rule as a short phrase, or `null` when the name is valid.\n */\nexport function describeLibraryNameProblem(displayName: string): string | null {\n const name = normalizeLibraryDisplayName(displayName);\n if (name.length === 0) {\n return \"is empty\";\n }\n if (CONTROL_CHARACTER.test(name)) {\n return \"contains a control character\";\n }\n if ([...name].length > MAX_LIBRARY_NAME_LENGTH) {\n return `is longer than ${MAX_LIBRARY_NAME_LENGTH} characters`;\n }\n return null;\n}\n\n/**\n * What indexing does when its target library or version already exists.\n *\n * - `reject-library`: fail if the library exists at all (the web UI's \"Add library\").\n * - `reject-version`: fail if that version exists; create the library if needed (the default).\n * - `replace`: rebuild an existing version, or create it (`--replace`, `replace: true`, re-index, retry, refresh).\n */\nexport const EXISTING_TARGET_POLICIES = [\n \"reject-library\",\n \"reject-version\",\n \"replace\",\n] as const;\n\n/** One of {@link EXISTING_TARGET_POLICIES}. */\nexport type ExistingTargetPolicy = (typeof EXISTING_TARGET_POLICIES)[number];\n\n/** Normalize a VersionRef (lowercase, trim; empty string for unversioned). */\nexport function normalizeVersionRef(ref: VersionRef): VersionRef {\n return {\n library: normalizeLibraryName(ref.library),\n version: normalizeVersionLabel(ref.version),\n };\n}\n\n/**\n * Summary of a specific version for API/UI consumption.\n * Aggregates status, progress and document statistics.\n */\nexport interface VersionSummary {\n id: number;\n ref: VersionRef;\n status: VersionStatus;\n /** Error message recorded when the last indexing attempt failed, else null. */\n errorMessage?: string | null;\n /**\n * Progress information while a version is being indexed.\n * Omitted once status is COMPLETED to reduce noise.\n */\n progress?: { pages: number; maxPages: number };\n counts: { documents: number; uniqueUrls: number };\n indexedAt: string | null; // ISO 8601\n sourceUrl?: string | null;\n preserveHashes?: boolean;\n}\n\n/**\n * Summary of a library and its versions for API/UI consumption.\n */\nexport interface LibrarySummary {\n library: string;\n versions: VersionSummary[];\n}\n\n/**\n * Database version record type matching the versions table schema.\n * Uses snake_case naming to match database column names.\n */\nexport interface DbVersion {\n id: number;\n library_id: number;\n name: string | null; // NULL for unversioned content\n created_at: string;\n\n // Status tracking fields (added in migration 005)\n status: VersionStatus;\n progress_pages: number;\n progress_max_pages: number;\n error_message: string | null;\n started_at: string | null; // When the indexing job started\n updated_at: string;\n\n // Scraper options fields (added in migration 006)\n source_url: string | null; // Original scraping URL\n scraper_options: string | null; // JSON string of VersionScraperOptions\n}\n\n/**\n * Version record with library name included from JOIN query.\n * Used when we need both version data and the associated library name.\n */\nexport interface DbVersionWithLibrary extends DbVersion {\n library_name: string;\n}\n\n/**\n * `versions.updated_at` holds whole seconds (SQLite's `CURRENT_TIMESTAMP`), so\n * a write can read up to this much older than it happened.\n */\nexport const UPDATED_AT_RESOLUTION_MS = 1000;\n\n/**\n * How long ago a version was last written, from its `updated_at` (UTC).\n *\n * @param version The version as read from the store.\n * @param now The current time, in milliseconds since the epoch.\n * @returns Milliseconds since the write, or `Infinity` when the version has no\n * readable `updated_at`.\n */\nexport function msSinceWritten(version: DbVersion, now: number): number {\n const writtenAt = version.updated_at\n ? Date.parse(`${version.updated_at.replace(\" \", \"T\")}Z`)\n : Number.NaN;\n return Number.isNaN(writtenAt) ? Number.POSITIVE_INFINITY : now - writtenAt;\n}\n\n/**\n * Helper function to convert NULL version name to empty string for API compatibility.\n * Database stores NULL for unversioned content, but APIs expect empty string.\n */\nexport function normalizeVersionName(name: string | null): string {\n return name ?? \"\";\n}\n\n/**\n * Helper function for version name normalization prior to storage.\n * Policy:\n * - Empty string represents the unversioned variant (stored as '').\n * - Names are lower-cased at call sites (see resolveLibraryAndVersionIds) to enforce\n * case-insensitive uniqueness; this function only preserves the empty-string rule.\n */\nexport function denormalizeVersionName(name: string): string {\n // Store unversioned as empty string to leverage UNIQUE(library_id, name)\n return name === \"\" ? \"\" : name;\n}\n\n/**\n * Result type for findBestVersion, indicating the best semver match\n * and whether unversioned documents exist.\n */\nexport interface FindVersionResult {\n bestMatch: string | null;\n hasUnversioned: boolean;\n}\n\n/**\n * Gets a human-readable description of a version status.\n */\nexport function getStatusDescription(status: VersionStatus): string {\n const descriptions: Record<VersionStatus, string> = {\n [VersionStatus.NOT_INDEXED]: \"Version created but not yet indexed\",\n [VersionStatus.QUEUED]: \"Waiting in queue for indexing\",\n [VersionStatus.RUNNING]: \"Currently being indexed\",\n [VersionStatus.COMPLETED]: \"Successfully indexed\",\n [VersionStatus.FAILED]: \"Indexing failed\",\n [VersionStatus.CANCELLED]: \"Indexing was cancelled\",\n [VersionStatus.UPDATING]: \"Re-indexing in progress\",\n };\n\n return descriptions[status] || \"Unknown status\";\n}\n\n/**\n * Checks if a status represents a final state (job completed).\n */\nexport function isFinalStatus(status: VersionStatus): boolean {\n return [\n VersionStatus.COMPLETED,\n VersionStatus.FAILED,\n VersionStatus.CANCELLED,\n ].includes(status);\n}\n\n/**\n * Checks if a status represents an active state (job in progress).\n */\nexport function isActiveStatus(status: VersionStatus): boolean {\n return [VersionStatus.QUEUED, VersionStatus.RUNNING, VersionStatus.UPDATING].includes(\n status,\n );\n}\n\n/**\n * Library version row returned by queryLibraryVersions.\n * Aggregates version metadata with document counts and indexing status.\n */\nexport interface DbLibraryVersion {\n library: string;\n version: string;\n versionId: number;\n status: VersionStatus;\n errorMessage: string | null;\n /** Items dequeued and given an outcome. */\n progressPages: number;\n /** Items expected to be processed. NOT the configured `maxPages` value. */\n progressMaxPages: number;\n /** Items that produced stored content. Null for rows predating this counter. */\n progressPagesIndexed: number | null;\n sourceUrl: string | null;\n documentCount: number;\n uniqueUrlCount: number;\n indexedAt: string | null;\n}\n\n/**\n * A version row as returned to callers, without the library name that groups it.\n *\n * Derived from {@link DbLibraryVersion} rather than restated, so the query's\n * column list and the shape callers receive cannot drift apart.\n */\nexport type LibraryVersionSummary = Omit<DbLibraryVersion, \"library\">;\n\n/**\n * A single stored chunk as returned by the admin dashboard's chunk explorer.\n * Combines chunk content with its position within the parent page and basic\n * size/embedding metadata, for debugging and insight into how data is stored.\n */\nexport interface VersionChunkListItem {\n /** Stable identifier for the chunk (the underlying row id, as a string). */\n id: string;\n /** URL of the page this chunk belongs to. */\n url: string;\n /** Raw chunk content as stored. */\n content: string;\n /** Processed MIME type of the page (e.g. \"text/html\"), if known. */\n mimeType: string | null;\n /** 1-based position of this chunk within its page (e.g. 3 of 12). */\n chunkIndex: number;\n /** Total number of chunks stored for this chunk's page. */\n pageChunkCount: number;\n /** Character count of `content` (JS string length). */\n charCount: number;\n /**\n * Token count for this chunk, if the store has ever recorded one.\n * The current schema does not persist per-chunk token counts, so this is\n * always `null` today. The field is kept so a future migration can populate\n * it without changing the API shape; consumers must treat `null` as\n * \"unavailable\", never as zero.\n */\n tokenCount: number | null;\n /** Whether this chunk has a stored embedding vector. */\n hasEmbedding: boolean;\n}\n\n/** Options for paginating and filtering {@link VersionChunkListItem} results. */\nexport interface ListVersionChunksOptions {\n /** Maximum number of chunks to return. */\n limit: number;\n /** Number of matching chunks to skip before returning results. Defaults to 0. */\n offset?: number;\n /** Case-insensitive substring filter applied to chunk content. */\n filter?: string;\n}\n\n/** Paginated result of listing a version's stored chunks. */\nexport interface ListVersionChunksResult {\n /** The requested page of chunks. */\n chunks: VersionChunkListItem[];\n /** Total number of chunks matching the filter (ignoring pagination), for computing page counts. */\n total: number;\n}\n\n/**\n * Aggregate chunk/page/embedding statistics for a single library version,\n * used by the chunk explorer's header strip.\n */\n/** One calendar day of indexing activity, derived from row-creation timestamps (UTC). */\nexport interface ActivityDay {\n /** Calendar day in `YYYY-MM-DD` (UTC). */\n date: string;\n /** Pages first indexed on this day. */\n pages: number;\n /** Chunks of the pages first indexed on this day. */\n chunks: number;\n}\n\n/**\n * Per-day indexing activity over a trailing window, derived from the\n * `created_at` timestamps already stored on pages. Days with no\n * activity are present with zero counts, so the series is contiguous and safe\n * to chart directly.\n */\nexport interface ActivityHistory {\n /** One entry per day in the window, oldest first, zero-filled. */\n days: ActivityDay[];\n /** Inclusive lower bound of the window (`YYYY-MM-DD`, UTC). */\n since: string;\n /** Inclusive upper bound of the window — \"today\" in UTC (`YYYY-MM-DD`). */\n until: string;\n /** Total pages indexed across the window. */\n totalPages: number;\n /** Total chunks indexed across the window. */\n totalChunks: number;\n}\n\nexport interface VersionChunkStats {\n /** Number of distinct pages (unique URLs) indexed for this version. */\n pageCount: number;\n /** Total number of stored chunks for this version. */\n chunkCount: number;\n /** Average chunks per page, or `null` when the version has no pages. */\n avgChunksPerPage: number | null;\n /**\n * Average token count per chunk, or `null` when token data isn't tracked.\n * Always `null` today since the schema doesn't persist per-chunk token counts.\n */\n avgTokensPerChunk: number | null;\n /** Number of chunks that have a stored embedding vector. */\n embeddedChunkCount: number;\n}\n\n/**\n * Serializable view of the active embedding model for the system-health\n * snapshot. `provider` is widened to `string` because this may describe a\n * remote worker's configuration fetched over the wire, and it is display-only.\n */\nexport interface EmbeddingConfigInfo {\n provider: string;\n model: string;\n /** Vector dimension, or `null` when the model's size isn't known. */\n dimensions: number | null;\n}\n\n/** One entry in a per-version page breakdown by MIME type. */\nexport interface CompositionBucket {\n /** MIME type (e.g. `text/html`), or `unknown` when the page has none recorded. */\n label: string;\n /** Number of pages of this type. */\n pages: number;\n}\n\n/**\n * Per-version content-type breakdown: pages grouped by MIME type, derived from\n * the stored pages. Powers the library-detail \"Content types\" panel.\n */\nexport interface VersionComposition {\n /** Pages grouped by MIME type, most common first. */\n mimeTypes: CompositionBucket[];\n}\n\n/**\n * Result of reclaiming unused SQLite pages and truncating the WAL.\n */\nexport interface CompactResult {\n /** True when the store is in-memory and cannot reclaim disk space. */\n skipped: boolean;\n /** True when VACUUM ran. */\n vacuumed: boolean;\n /** Combined size of the database, WAL, and SHM files before compaction. */\n beforeBytes: number;\n /** Combined size of the database, WAL, and SHM files after compaction. */\n afterBytes: number;\n /** Bytes reclaimed (`beforeBytes - afterBytes`, floored at 0). */\n reclaimedBytes: number;\n}\n\n/**\n * Options for reading a stored page.\n */\nexport interface PageContentOptions {\n /** Index of the first chunk to return (default 0). */\n startChunk?: number;\n /** Maximum characters to return. Whole chunks only; a single longer chunk is returned on its own. */\n maxChars?: number;\n}\n\n/**\n * A window of consecutive chunks of a stored page, assembled for its content type.\n */\nexport interface PageContentResult {\n url: string;\n title: string | null;\n contentType: string | null;\n content: string;\n /** Index of the first chunk in `content`. */\n startChunk: number;\n totalChunks: number;\n /** `startChunk` for the next call, or null when `content` reaches the end of the page. */\n nextChunk: number | null;\n}\n\n/**\n * Options for listing pages in a library version.\n */\nexport interface ListPagesOptions {\n /** Keeps only pages whose URL contains this text. */\n contains?: string;\n limit?: number;\n offset?: number;\n}\n\n/**\n * Item in the list of pages.\n */\nexport interface PageListItem {\n url: string;\n title: string | null;\n depth: number | null;\n}\n\n/**\n * Result of listing pages for a library version.\n */\nexport interface ListPagesResult {\n library: string;\n version: string;\n total: number;\n pages: PageListItem[];\n limit: number;\n offset: number;\n hasMore: boolean;\n}\n","import { CONTROL_CHARACTER } from \"./types\";\n\n/**\n * Base error class for all store-related errors.\n * Provides consistent error handling with optional cause tracking.\n */\nexport class StoreError extends Error {\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(cause ? `${message} caused by ${cause}` : message);\n this.name = this.constructor.name;\n\n const causeError =\n cause instanceof Error ? cause : cause ? new Error(String(cause)) : undefined;\n if (causeError?.stack) {\n this.stack = causeError.stack;\n }\n }\n}\n\nconst CONTROL_CHARACTERS = new RegExp(CONTROL_CHARACTER.source, \"gu\");\n\nfunction escapeControlCharacter(char: string): string {\n const code = char.charCodeAt(0);\n // C0 controls get JSON's readable escapes (\\n, \\t, \\u001b); DEL and C1 get \\uXXXX\n return code < 0x20\n ? JSON.stringify(char).slice(1, -1)\n : `\\\\u${code.toString(16).padStart(4, \"0\")}`;\n}\n\n/**\n * Escapes every control character (Unicode Cc) in text that an error message\n * repeats, such as a library name or version, so it cannot carry terminal\n * control sequences or forge log lines. Other characters are left as they are.\n */\nexport function escapeControlCharacters(text: string): string {\n return text.replace(CONTROL_CHARACTERS, escapeControlCharacter);\n}\n\n/**\n * Labels a library version as `name@version` for logs and messages, with\n * control characters escaped in both and unversioned documentation shown as\n * `latest`.\n */\nexport function formatVersionLabel(library: string, version: string): string {\n return `${escapeControlCharacters(library)}@${escapeControlCharacters(version) || \"latest\"}`;\n}\n\n/**\n * Quotes a library name (or version) for an error message, with quotes,\n * backslashes and every control character escaped.\n */\nexport function quoteName(name: string): string {\n return escapeControlCharacters(JSON.stringify(name));\n}\n\n/**\n * Error thrown when a requested library cannot be found in the store.\n * Includes suggestions for similar library names if available.\n */\nexport class LibraryNotFoundInStoreError extends StoreError {\n constructor(\n public readonly library: string,\n public readonly similarLibraries: string[] = [],\n ) {\n let text = `Library ${escapeControlCharacters(library)} not found in store.`;\n if (similarLibraries.length > 0) {\n text += ` Did you mean: ${similarLibraries.map(escapeControlCharacters).join(\", \")}?`;\n }\n super(text);\n }\n}\n\n/**\n * Error thrown when a specific version of a library cannot be found in the store.\n * Includes the list of available versions for better context.\n */\nexport class VersionNotFoundInStoreError extends StoreError {\n constructor(\n public readonly library: string,\n public readonly version: string,\n public readonly availableVersions: string[],\n ) {\n const versionText = version\n ? `Version ${escapeControlCharacters(version)}`\n : \"Version\";\n let text = `${versionText} for library ${escapeControlCharacters(library)} not found in store.`;\n if (availableVersions.length > 0) {\n text += ` Available versions: ${availableVersions.map(escapeControlCharacters).join(\", \")}`;\n }\n super(text);\n }\n}\n\n/**\n * Error thrown when a request to create a new library finds that library already exists.\n * Raised only for an explicit \"Add library\" request.\n */\nexport class LibraryAlreadyExistsError extends StoreError {\n constructor(\n /** The existing library's stored display name. */\n public readonly library: string,\n ) {\n super(`Library ${quoteName(library)} already exists. Open it to add a version.`);\n }\n}\n\n/**\n * Error thrown when a scrape would clear an existing version without requesting replacement.\n */\nexport class VersionAlreadyExistsError extends StoreError {\n constructor(\n /** The library's stored display name. */\n public readonly library: string,\n /** The normalized version label; empty for unversioned documentation. */\n public readonly version: string,\n ) {\n const target = version\n ? `Version ${quoteName(version)} of library ${quoteName(library)}`\n : `Unversioned documentation for library ${quoteName(library)}`;\n super(\n `${target} already exists. To rebuild it, scrape again with --replace (CLI) or replace: true (MCP), or refresh it to update in place.`,\n );\n }\n}\n\n/**\n * Error thrown when a new library's name breaks a naming rule.\n */\nexport class InvalidLibraryNameError extends StoreError {\n constructor(\n /** The submitted name. */\n public readonly library: string,\n /** The broken rule, as returned by `describeLibraryNameProblem`. */\n public readonly reason: string,\n ) {\n super(`Invalid library name ${quoteName(library)}: ${reason}.`);\n }\n}\n\n/**\n * Error thrown when a requested page cannot be found in the store for a library/version.\n * Includes suggestions for similar page URLs if available.\n */\nexport class PageNotFoundInStoreError extends StoreError {\n constructor(\n public readonly library: string,\n public readonly version: string,\n public readonly pathOrUrl: string,\n public readonly suggestions: string[] = [],\n ) {\n const versionText = version ? ` (version: ${escapeControlCharacters(version)})` : \"\";\n let text = `Page '${escapeControlCharacters(pathOrUrl)}' for library '${escapeControlCharacters(library)}'${versionText} not found in store.`;\n if (suggestions.length > 0) {\n text += ` Did you mean: ${suggestions.map(escapeControlCharacters).join(\", \")}?`;\n }\n super(text);\n }\n}\n\n/**\n * Error thrown when a page path matches more than one stored page.\n * Lists the matching URLs so the caller can pass the full URL of the intended page.\n */\nexport class AmbiguousPageInStoreError extends StoreError {\n constructor(\n public readonly library: string,\n public readonly version: string,\n public readonly pathOrUrl: string,\n public readonly matches: string[],\n ) {\n const versionText = version ? ` (version: ${escapeControlCharacters(version)})` : \"\";\n super(\n `Page '${escapeControlCharacters(pathOrUrl)}' for library '${escapeControlCharacters(library)}'${versionText} matches more than one page: ${matches.map(escapeControlCharacters).join(\", \")}. Pass the full URL of the page to read.`,\n );\n }\n}\n\n/**\n * Error thrown when an embedding model's vector dimension exceeds the database's fixed dimension.\n * This occurs when trying to use a model that produces vectors larger than the database can store.\n */\nexport class DimensionError extends StoreError {\n constructor(\n public readonly modelName: string,\n public readonly modelDimension: number,\n public readonly dbDimension: number,\n ) {\n super(\n `Model \"${modelName}\" produces ${modelDimension}-dimensional vectors, ` +\n `which exceeds the database's fixed dimension of ${dbDimension}. ` +\n `Please use a model with dimension ≤ ${dbDimension}.`,\n );\n }\n}\n\n/**\n * Error thrown when there's a problem with database connectivity or operations.\n */\nexport class ConnectionError extends StoreError {}\n\n/**\n * Error thrown when the embedding provider fails to embed a page's chunks.\n * Nothing of the page is written when this is thrown.\n */\nexport class EmbeddingError extends ConnectionError {}\n\n/**\n * Error thrown when attempting to retrieve a document that doesn't exist.\n */\nexport class DocumentNotFoundError extends StoreError {\n constructor(public readonly id: string) {\n super(`Document ${id} not found`);\n }\n}\n\n/**\n * Names an embedding model with its vector dimension for model-change messages.\n * @param model - The model specification.\n * @param dimension - The vector dimension, or null when it is not known.\n * @returns The model, followed by its dimension when known.\n */\nexport function describeEmbeddingModel(model: string, dimension: string | null): string {\n return dimension === null ? model : `${model} (${dimension} dimensions)`;\n}\n\n/**\n * Error thrown when the configured embedding model or vector dimension differs from the\n * values stored in the database metadata. This indicates that existing vectors are\n * incompatible with the new configuration and must be invalidated before proceeding.\n *\n * The CLI layer catches this error to accept the change when `--accept-model-change`\n * is set, prompt the user interactively (TTY), or fail startup entirely\n * (non-interactive/MCP/stdio mode). A dimension is null when it is not known.\n */\nexport class EmbeddingModelChangedError extends StoreError {\n constructor(\n public readonly previousModel: string,\n public readonly previousDimension: string | null,\n public readonly currentModel: string,\n public readonly currentDimension: string | null,\n ) {\n super(\n `Embedding model change detected:\\n` +\n ` Previous: ${describeEmbeddingModel(previousModel, previousDimension)}\\n` +\n ` Current: ${describeEmbeddingModel(currentModel, currentDimension)}\\n\\n` +\n `All existing vectors are incompatible and must be invalidated.\\n` +\n `To confirm this change, start the server once with --accept-model-change\\n` +\n `(or DOCS_MCP_ACCEPT_MODEL_CHANGE=true), or start it in a terminal and answer the prompt.`,\n );\n }\n}\n\n/**\n * Error thrown when required credentials for an embedding provider are missing.\n * This allows the system to gracefully degrade to FTS-only search when vectorization is unavailable.\n */\nexport class MissingCredentialsError extends StoreError {\n constructor(\n public readonly provider: string,\n missingCredentials: string[],\n ) {\n super(\n `Missing credentials for ${provider} embedding provider. ` +\n `Required: ${missingCredentials.join(\", \")}`,\n );\n }\n}\n","import { normalizeEnvValue } from \"../../utils/env\";\n\n/**\n * Shared embedding model configuration service.\n * Provides synchronous parsing of embedding model configuration and known dimensions lookup.\n * Eliminates code duplication between DocumentStore and telemetry systems.\n *\n * All model lookups are case-insensitive to handle variations in model name capitalization.\n * Uses class-based approach to avoid mutable global state and improve testability.\n */\n\n/**\n * The complete set of provider prefixes recognized in a model specification.\n * Anything else before the first colon is part of the model name itself.\n *\n * This list is normative rather than descriptive: it decides which prefixes claim\n * the provider slot, so adding an entry changes how existing specifications parse.\n * A model literally named `<new-provider>:<tag>` served by an OpenAI-compatible\n * endpoint would start resolving to the new provider, breaking that configuration\n * on upgrade. Call provider additions out in the release notes.\n *\n * `EmbeddingProvider` is derived from this array so the two cannot drift apart.\n */\nexport const SUPPORTED_PROVIDERS = [\n \"openai\",\n \"vertex\",\n \"gemini\",\n \"aws\",\n \"microsoft\",\n] as const;\n\n/**\n * Supported embedding model providers.\n */\nexport type EmbeddingProvider = (typeof SUPPORTED_PROVIDERS)[number];\n\n/**\n * Split a model specification into its provider prefix and model name.\n *\n * Only a prefix that names a supported provider is treated as a provider, matched\n * case-insensitively and resolved to its canonical lowercase form. Every other\n * specification is an OpenAI-compatible model name, which keeps names that carry a\n * tag or quantization suffix intact (e.g. \"nomic-embed-text:latest\" or\n * \"second-state/jina-embeddings-v3-GGUF:Q4_K_M\").\n *\n * @param spec The full model specification.\n * @returns The resolved provider and model name.\n */\nexport function splitModelSpec(spec: string): {\n provider: EmbeddingProvider;\n model: string;\n} {\n const colonIndex = spec.indexOf(\":\");\n const prefix = spec.substring(0, colonIndex).toLowerCase();\n const provider =\n colonIndex === -1 ? undefined : SUPPORTED_PROVIDERS.find((name) => name === prefix);\n\n return provider\n ? { provider, model: spec.substring(colonIndex + 1) }\n : { provider: \"openai\", model: spec };\n}\n\n/**\n * Embedding model configuration parsed from environment variables.\n */\nexport interface EmbeddingModelConfig {\n /** The provider (e.g., \"openai\", \"gemini\") */\n provider: EmbeddingProvider;\n /** The model name (e.g., \"text-embedding-3-small\") */\n model: string;\n /** Known dimensions for this model, or null if unknown */\n dimensions: number | null;\n /** The full model specification string (e.g., \"openai:text-embedding-3-small\") */\n modelSpec: string;\n}\n\n/**\n * Embedding configuration manager that handles model parsing and dimension caching.\n * Encapsulates state to avoid global variable issues and improve testability.\n */\nexport class EmbeddingConfig {\n private static instance: EmbeddingConfig | null = null;\n\n /**\n * Get the singleton instance of EmbeddingConfig.\n * Creates the instance if it doesn't exist.\n */\n static getInstance(): EmbeddingConfig {\n if (EmbeddingConfig.instance === null) {\n EmbeddingConfig.instance = new EmbeddingConfig();\n }\n return EmbeddingConfig.instance;\n }\n\n /**\n * Reset the singleton instance (useful for testing).\n */\n static resetInstance(): void {\n EmbeddingConfig.instance = null;\n }\n /**\n * Known dimensions for common embedding models.\n * This avoids expensive API calls for dimension detection in telemetry.\n *\n * Note: The \"openai\" provider also supports OpenAI-compatible APIs like:\n * - Ollama (local models)\n * - LMStudio (local models)\n * - Any service implementing OpenAI's embedding API\n */\n private readonly knownModelDimensions: Record<string, number> = {\n // OpenAI models (also works with Ollama, LMStudio, and other OpenAI-compatible APIs)\n \"text-embedding-3-small\": 1536,\n \"text-embedding-3-large\": 3072,\n \"text-embedding-ada-002\": 1536,\n\n // Google Vertex AI models\n \"text-embedding-004\": 768,\n \"text-embedding-005\": 768,\n \"textembedding-gecko@003\": 768,\n \"textembedding-gecko@002\": 768,\n \"textembedding-gecko@001\": 768,\n\n // Google Gemini models (with MRL support)\n \"text-embedding-preview-0409\": 768,\n \"embedding-001\": 768,\n \"gemini-embedding-2-preview\": 3072,\n\n // AWS Bedrock models\n // Amazon Titan models\n \"amazon.titan-embed-text-v1\": 1536,\n \"amazon.titan-embed-text-v2:0\": 1024,\n \"amazon.titan-embed-image-v1\": 1024, // Image embedding model\n\n // Cohere models\n \"cohere.embed-english-v3\": 1024,\n \"cohere.embed-multilingual-v3\": 1024,\n \"Cohere/Cohere-embed-v4.0\": 1536,\n \"embed-v4.0\": 1536,\n\n // Open-weight multilingual models, servable from any OpenAI-compatible endpoint\n \"intfloat/multilingual-e5-large\": 1024,\n \"multilingual-e5-large\": 1024,\n \"text-embedding-multilingual-e5-large\": 1024,\n\n // Additional AWS models that might be supported\n // Note: Some of these might be placeholders - verify dimensions before use\n // \"amazon.nova-embed-multilingual-v1:0\": 4096, // Commented out as noted in source\n\n // MTEB Leaderboard models (source: https://huggingface.co/spaces/mteb/leaderboard)\n // Top performing models from Massive Text Embedding Benchmark\n \"sentence-transformers/all-MiniLM-L6-v2\": 384,\n \"gemini-embedding-001\": 3072,\n \"Qwen/Qwen3-Embedding-8B\": 4096,\n \"Qwen/Qwen3-Embedding-4B\": 2560,\n \"Qwen/Qwen3-Embedding-0.6B\": 1024,\n \"Linq-AI-Research/Linq-Embed-Mistral\": 4096,\n \"Alibaba-NLP/gte-Qwen2-7B-instruct\": 3584,\n \"intfloat/multilingual-e5-large-instruct\": 1024,\n \"Salesforce/SFR-Embedding-Mistral\": 4096,\n \"text-multilingual-embedding-002\": 768,\n \"GritLM/GritLM-7B\": 4096,\n \"GritLM/GritLM-8x7B\": 4096,\n \"intfloat/e5-mistral-7b-instruct\": 4096,\n \"Cohere/Cohere-embed-multilingual-v3.0\": 1024,\n \"Alibaba-NLP/gte-Qwen2-1.5B-instruct\": 8960,\n \"Lajavaness/bilingual-embedding-large\": 1024,\n \"Salesforce/SFR-Embedding-2_R\": 4096,\n \"NovaSearch/stella_en_1.5B_v5\": 8960,\n \"NovaSearch/jasper_en_vision_language_v1\": 8960,\n \"nvidia/NV-Embed-v2\": 4096,\n \"OrdalieTech/Solon-embeddings-large-0.1\": 1024,\n \"BAAI/bge-m3\": 1024,\n \"HIT-TMG/KaLM-embedding-multilingual-mini-v1\": 896,\n \"jinaai/jina-embeddings-v3\": 1024,\n \"Alibaba-NLP/gte-multilingual-base\": 768,\n \"Lajavaness/bilingual-embedding-base\": 768,\n \"HIT-TMG/KaLM-embedding-multilingual-mini-instruct-v1\": 896,\n \"nvidia/NV-Embed-v1\": 4096,\n \"Cohere/Cohere-embed-multilingual-light-v3.0\": 384,\n \"manu/bge-m3-custom-fr\": 1024,\n \"Lajavaness/bilingual-embedding-small\": 384,\n \"Snowflake/snowflake-arctic-embed-l-v2.0\": 1024,\n \"intfloat/multilingual-e5-base\": 768,\n \"voyage-3-lite\": 512,\n \"voyage-3\": 1024,\n \"voyage-3-large\": 1024,\n \"voyage-3.5\": 1024,\n \"voyage-4\": 1024,\n \"voyage-4-large\": 1024,\n \"voyage-4-lite\": 1024,\n \"voyage-code-3\": 1024,\n \"intfloat/multilingual-e5-small\": 384,\n \"Alibaba-NLP/gte-Qwen1.5-7B-instruct\": 4096,\n \"Snowflake/snowflake-arctic-embed-m-v2.0\": 768,\n \"deepvk/USER-bge-m3\": 1024,\n \"Cohere/Cohere-embed-english-v3.0\": 1024,\n \"Omartificial-Intelligence-Space/Arabic-labse-Matryoshka\": 768,\n \"ibm-granite/granite-embedding-278m-multilingual\": 768,\n \"NovaSearch/stella_en_400M_v5\": 4096,\n \"omarelshehy/arabic-english-sts-matryoshka\": 1024,\n \"sentence-transformers/paraphrase-multilingual-mpnet-base-v2\": 768,\n \"Omartificial-Intelligence-Space/Arabic-all-nli-triplet-Matryoshka\": 768,\n \"Haon-Chen/speed-embedding-7b-instruct\": 4096,\n \"sentence-transformers/LaBSE\": 768,\n \"WhereIsAI/UAE-Large-V1\": 1024,\n \"ibm-granite/granite-embedding-107m-multilingual\": 384,\n \"mixedbread-ai/mxbai-embed-large-v1\": 1024,\n \"intfloat/e5-large-v2\": 1024,\n \"avsolatorio/GIST-large-Embedding-v0\": 1024,\n \"sdadas/mmlw-e5-large\": 1024,\n \"nomic-ai/nomic-embed-text-v1\": 768,\n \"nomic-embed-text-v1\": 768,\n \"nomic-ai/nomic-embed-text-v1-ablated\": 768,\n \"nomic-ai/nomic-embed-text-v2-moe\": 768,\n \"nomic-ai/modernbert-embed-base\": 768,\n \"nomic-ai/nomic-embed-code\": 3584,\n \"intfloat/e5-base-v2\": 768,\n \"BAAI/bge-large-en-v1.5\": 1024,\n \"intfloat/e5-large\": 1024,\n \"Omartificial-Intelligence-Space/Arabic-MiniLM-L12-v2-all-nli-triplet\": 384,\n \"Cohere/Cohere-embed-english-light-v3.0\": 384,\n \"sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2\": 768,\n \"Gameselo/STS-multilingual-mpnet-base-v2\": 768,\n \"thenlper/gte-large\": 1024,\n \"avsolatorio/GIST-Embedding-v0\": 768,\n \"nomic-ai/nomic-embed-text-v1-unsupervised\": 768,\n \"infgrad/stella-base-en-v2\": 768,\n \"avsolatorio/NoInstruct-small-Embedding-v0\": 384,\n \"dwzhu/e5-base-4k\": 768,\n \"sdadas/mmlw-e5-base\": 768,\n \"voyage-multilingual-2\": 1024,\n \"McGill-NLP/LLM2Vec-Mistral-7B-Instruct-v2-mntp-supervised\": 4096,\n \"BAAI/bge-base-en-v1.5\": 768,\n \"avsolatorio/GIST-small-Embedding-v0\": 384,\n \"sdadas/mmlw-roberta-large\": 1024,\n \"nomic-ai/nomic-embed-text-v1.5\": 768,\n \"nomic-embed-text-v1.5\": 768,\n \"text-embedding-nomic-embed-text-v1.5\": 768,\n \"minishlab/potion-multilingual-128M\": 256,\n \"shibing624/text2vec-base-multilingual\": 384,\n \"thenlper/gte-base\": 768,\n \"intfloat/e5-small-v2\": 384,\n \"intfloat/e5-base\": 768,\n \"sentence-transformers/static-similarity-mrl-multilingual-v1\": 1024,\n \"manu/sentence_croissant_alpha_v0.3\": 2048,\n \"BAAI/bge-small-en-v1.5\": 512,\n \"thenlper/gte-small\": 384,\n \"sdadas/mmlw-e5-small\": 384,\n \"manu/sentence_croissant_alpha_v0.4\": 2048,\n \"manu/sentence_croissant_alpha_v0.2\": 2048,\n \"abhinand/MedEmbed-small-v0.1\": 384,\n \"ibm-granite/granite-embedding-125m-english\": 768,\n \"intfloat/e5-small\": 384,\n \"voyage-large-2-instruct\": 1024,\n \"sdadas/mmlw-roberta-base\": 768,\n \"Snowflake/snowflake-arctic-embed-l\": 1024,\n \"Mihaiii/Ivysaur\": 384,\n \"Snowflake/snowflake-arctic-embed-m-long\": 768,\n \"bigscience/sgpt-bloom-7b1-msmarco\": 4096,\n \"avsolatorio/GIST-all-MiniLM-L6-v2\": 384,\n \"sergeyzh/LaBSE-ru-turbo\": 768,\n \"sentence-transformers/all-mpnet-base-v2\": 768,\n \"Snowflake/snowflake-arctic-embed-m\": 768,\n \"Snowflake/snowflake-arctic-embed-s\": 384,\n \"sentence-transformers/all-MiniLM-L12-v2\": 384,\n \"Mihaiii/gte-micro-v4\": 384,\n \"Snowflake/snowflake-arctic-embed-m-v1.5\": 768,\n \"cointegrated/LaBSE-en-ru\": 768,\n \"Mihaiii/Bulbasaur\": 384,\n \"ibm-granite/granite-embedding-30m-english\": 384,\n \"deepfile/embedder-100p\": 768,\n \"Jaume/gemma-2b-embeddings\": 2048,\n \"OrlikB/KartonBERT-USE-base-v1\": 768,\n \"izhx/udever-bloom-7b1\": 4096,\n \"izhx/udever-bloom-1b1\": 1024,\n \"brahmairesearch/slx-v0.1\": 384,\n \"Mihaiii/Wartortle\": 384,\n \"izhx/udever-bloom-3b\": 2048,\n \"deepvk/USER-base\": 768,\n \"ai-forever/ru-en-RoSBERTa\": 1024,\n \"McGill-NLP/LLM2Vec-Mistral-7B-Instruct-v2-mntp-unsup-simcse\": 4096,\n \"Mihaiii/Venusaur\": 384,\n \"Snowflake/snowflake-arctic-embed-xs\": 384,\n \"jinaai/jina-embedding-b-en-v1\": 768,\n \"Mihaiii/gte-micro\": 384,\n \"aari1995/German_Semantic_STS_V2\": 1024,\n \"Mihaiii/Squirtle\": 384,\n \"OrlikB/st-polish-kartonberta-base-alpha-v1\": 768,\n \"sergeyzh/rubert-tiny-turbo\": 312,\n \"minishlab/potion-base-8M\": 256,\n \"minishlab/M2V_base_glove_subword\": 256,\n \"jinaai/jina-embedding-s-en-v1\": 512,\n \"minishlab/potion-base-4M\": 128,\n \"minishlab/M2V_base_output\": 256,\n \"DeepPavlov/rubert-base-cased-sentence\": 768,\n \"jinaai/jina-embeddings-v2-small-en\": 512,\n \"cointegrated/rubert-tiny2\": 312,\n \"minishlab/M2V_base_glove\": 256,\n \"cointegrated/rubert-tiny\": 312,\n \"silma-ai/silma-embeddding-matryoshka-v0.1\": 768,\n \"DeepPavlov/rubert-base-cased\": 768,\n \"Omartificial-Intelligence-Space/Arabic-mpnet-base-all-nli-triplet\": 768,\n \"izhx/udever-bloom-560m\": 1024,\n \"minishlab/potion-base-2M\": 64,\n \"DeepPavlov/distilrubert-small-cased-conversational\": 768,\n \"consciousAI/cai-lunaris-text-embeddings\": 1024,\n \"deepvk/deberta-v1-base\": 768,\n \"Omartificial-Intelligence-Space/Arabert-all-nli-triplet-Matryoshka\": 768,\n \"Omartificial-Intelligence-Space/Marbert-all-nli-triplet-Matryoshka\": 768,\n \"ai-forever/sbert_large_mt_nlu_ru\": 1024,\n \"ai-forever/sbert_large_nlu_ru\": 1024,\n \"malenia1/ternary-weight-embedding\": 1024,\n \"jinaai/jina-embeddings-v2-base-en\": 768,\n \"VPLabs/SearchMap_Preview\": 4096,\n \"Hum-Works/lodestone-base-4096-v1\": 768,\n \"jinaai/jina-embeddings-v4\": 2048,\n };\n\n private readonly runtimeDetectedDimensionModels = new Set([\n \"novasearch/stella_en_1.5b_v5\",\n \"stella_en_1.5b_v5\",\n \"novasearch/stella_en_400m_v5\",\n \"dunzhang/stella_en_400m_v5\",\n \"stella_en_400m_v5\",\n \"novasearch/jasper_en_vision_language_v1\",\n \"jasper_en_vision_language_v1\",\n ]);\n\n /**\n * Lowercase lookup map for case-insensitive model dimension queries.\n * Built lazily from knownModelDimensions to ensure consistency.\n */\n private modelLookup: Map<string, number>;\n\n constructor() {\n this.modelLookup = new Map();\n for (const [model, dimensions] of Object.entries(this.knownModelDimensions)) {\n this.modelLookup.set(model.toLowerCase(), dimensions);\n }\n }\n\n /**\n * Build the lookup keys to try for a model name, most specific first:\n * the name itself, then with the namespace dropped, the tag dropped, and both.\n *\n * Dropping a trailing tag lets a quantized or tagged variant reuse the base\n * model's dimensions (e.g. \"nomic-ai/nomic-embed-text-v2-moe:latest\"), which\n * quantization does not change. Exact matches are tried first, so names whose\n * own identifier contains a colon (e.g. \"amazon.titan-embed-text-v2:0\") still\n * resolve to their own entry.\n */\n private dimensionLookupKeys(normalized: string): string[] {\n const slashIndex = normalized.lastIndexOf(\"/\");\n const withoutNamespace =\n slashIndex > -1 ? normalized.substring(slashIndex + 1) : undefined;\n const bases = withoutNamespace ? [normalized, withoutNamespace] : [normalized];\n\n const withoutTag = (key: string) => {\n const colonIndex = key.lastIndexOf(\":\");\n return colonIndex > 0 ? [key.substring(0, colonIndex)] : [];\n };\n\n return [...bases, ...bases.flatMap(withoutTag)];\n }\n\n private findKnownDimension(model: string): number | null {\n for (const key of this.dimensionLookupKeys(model.toLowerCase())) {\n if (this.runtimeDetectedDimensionModels.has(key)) {\n return null;\n }\n\n const dimensions = this.modelLookup?.get(key);\n if (dimensions !== undefined) {\n return dimensions;\n }\n }\n\n return null;\n }\n\n /**\n * Parse embedding model configuration from a provided model specification.\n * This is a synchronous operation that extracts provider, model, and known dimensions.\n *\n * Supports various providers:\n * - openai: OpenAI models and OpenAI-compatible APIs (Ollama, LMStudio, etc.)\n * - vertex: Google Cloud Vertex AI\n * - gemini: Google Generative AI\n * - aws: AWS Bedrock models\n * - microsoft: Azure OpenAI\n *\n * @param modelSpec Model specification (e.g., \"openai:text-embedding-3-small\"), defaults to \"text-embedding-3-small\"\n * @returns Parsed embedding model configuration\n */\n parse(modelSpec?: string): EmbeddingModelConfig {\n const spec = normalizeEnvValue(modelSpec || \"text-embedding-3-small\");\n\n // Parse provider and model from string (e.g., \"gemini:embedding-001\" or just \"text-embedding-3-small\")\n // Handle models that contain colons in their names (e.g., \"aws:amazon.titan-embed-text-v2:0\")\n const { provider, model } = splitModelSpec(spec);\n\n // Look up known dimensions (case-insensitive)\n const dimensions = this.findKnownDimension(model);\n\n return {\n provider,\n model,\n dimensions,\n modelSpec: spec,\n };\n }\n\n /**\n * Get the known dimensions for a specific model.\n * Returns null if the model dimensions are not known.\n * Uses case-insensitive lookup.\n *\n * @param model The model name (e.g., \"text-embedding-3-small\")\n * @returns Known dimensions or null\n */\n getKnownDimensions(model: string): number | null {\n return this.findKnownDimension(model);\n }\n\n /**\n * Add or update known dimensions for a model.\n * This can be used to cache discovered dimensions.\n * Stores both original case and lowercase for consistent lookup.\n *\n * @param model The model name\n * @param dimensions The dimensions to cache\n */\n setKnownDimensions(model: string, dimensions: number): void {\n this.knownModelDimensions[model] = dimensions;\n\n // Update lowercase lookup map\n if (this.modelLookup) {\n this.modelLookup.set(model.toLowerCase(), dimensions);\n }\n }\n\n /**\n * Static method to parse embedding model configuration using the singleton instance.\n * This maintains backward compatibility while using the class-based approach.\n */\n static parseEmbeddingConfig(modelSpec?: string): EmbeddingModelConfig {\n return EmbeddingConfig.getInstance().parse(modelSpec);\n }\n\n /**\n * Static method to get known model dimensions using the singleton instance.\n * This maintains backward compatibility while using the class-based approach.\n */\n static getKnownModelDimensions(model: string): number | null {\n return EmbeddingConfig.getInstance().getKnownDimensions(model);\n }\n\n /**\n * Static method to set known model dimensions using the singleton instance.\n * This maintains backward compatibility while using the class-based approach.\n */\n static setKnownModelDimensions(model: string, dimensions: number): void {\n EmbeddingConfig.getInstance().setKnownDimensions(model, dimensions);\n }\n}\n","import { Embeddings } from \"@langchain/core/embeddings\";\nimport { DimensionError } from \"../errors\";\n\n/**\n * Wrapper around an Embeddings implementation that ensures vectors have a fixed dimension.\n * - If a vector's dimension is greater than the target and truncation is allowed,\n * the vector is truncated (e.g., for models that support MRL - Matryoshka\n * Representation Learning).\n * - If a vector's dimension is greater than the target and truncation is not\n * allowed, a DimensionError is thrown.\n * - If a vector's dimension is less than the target, it is padded with zeros.\n */\nexport class FixedDimensionEmbeddings extends Embeddings {\n constructor(\n private readonly embeddings: Embeddings,\n private readonly targetDimension: number,\n /** The model specification, kept verbatim for error messages. */\n private readonly providerAndModel: string,\n public readonly allowTruncate: boolean = false,\n ) {\n super({});\n }\n\n /**\n * Normalize a vector to the target dimension by truncating (for MRL models) or padding.\n * @throws {DimensionError} If vector is too large and provider doesn't support MRL\n */\n private normalizeVector(vector: number[]): number[] {\n const dimension = vector.length;\n\n if (dimension > this.targetDimension) {\n // If truncation is allowed (e.g., for MRL models like Gemini), truncate the vector\n if (this.allowTruncate) {\n return vector.slice(0, this.targetDimension);\n }\n // Otherwise, throw an error\n throw new DimensionError(this.providerAndModel, dimension, this.targetDimension);\n }\n\n if (dimension < this.targetDimension) {\n // Pad with zeros to reach target dimension\n return [...vector, ...new Array(this.targetDimension - dimension).fill(0)];\n }\n\n return vector;\n }\n\n async embedQuery(text: string): Promise<number[]> {\n const vector = await this.embeddings.embedQuery(text);\n return this.normalizeVector(vector);\n }\n\n async embedDocuments(documents: string[]): Promise<number[][]> {\n const vectors = await this.embeddings.embedDocuments(documents);\n return vectors.map((vector) => this.normalizeVector(vector));\n }\n}\n","import { BedrockEmbeddings } from \"@langchain/aws\";\nimport type { Embeddings } from \"@langchain/core/embeddings\";\nimport { GoogleGenerativeAIEmbeddings } from \"@langchain/google-genai\";\nimport { VertexAIEmbeddings } from \"@langchain/google-vertexai\";\nimport {\n AzureOpenAIEmbeddings,\n type ClientOptions,\n OpenAIEmbeddings,\n type OpenAIEmbeddingsParams,\n} from \"@langchain/openai\";\nimport type { AppConfig } from \"../../utils/config\";\nimport { MissingCredentialsError } from \"../errors\";\nimport {\n type EmbeddingProvider,\n SUPPORTED_PROVIDERS,\n splitModelSpec,\n} from \"./EmbeddingConfig\";\nimport { FixedDimensionEmbeddings } from \"./FixedDimensionEmbeddings\";\n\n/**\n * Error thrown when an invalid or unsupported embedding provider is specified.\n */\nexport class UnsupportedProviderError extends Error {\n constructor(provider: string) {\n super(\n `❌ Unsupported embedding provider: ${provider}\\n` +\n ` Supported providers: ${SUPPORTED_PROVIDERS.join(\", \")}\\n` +\n \" See README.md for configuration options or run with --help for more details.\",\n );\n this.name = \"UnsupportedProviderError\";\n }\n}\n\n/**\n * Error thrown when there's an issue with the model configuration or missing environment variables.\n */\nexport class ModelConfigurationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ModelConfigurationError\";\n }\n}\n\n/**\n * Checks if credentials are available for a specific embedding provider.\n * Returns true if any credentials are found, false if no credentials are provided.\n * Does not validate if the credentials are correct, only if they are present.\n *\n * @param provider The embedding provider to check\n * @returns true if credentials are available, false if no credentials found\n */\nexport function areCredentialsAvailable(provider: EmbeddingProvider): boolean {\n switch (provider) {\n case \"openai\":\n return !!process.env.OPENAI_API_KEY;\n\n case \"vertex\":\n return !!process.env.GOOGLE_APPLICATION_CREDENTIALS;\n\n case \"gemini\":\n return !!process.env.GOOGLE_API_KEY;\n\n case \"aws\": {\n const region = process.env.BEDROCK_AWS_REGION || process.env.AWS_REGION;\n return (\n !!region &&\n (!!process.env.AWS_PROFILE ||\n (!!process.env.AWS_ACCESS_KEY_ID && !!process.env.AWS_SECRET_ACCESS_KEY))\n );\n }\n\n case \"microsoft\":\n return !!(\n process.env.AZURE_OPENAI_API_KEY &&\n process.env.AZURE_OPENAI_API_INSTANCE_NAME &&\n process.env.AZURE_OPENAI_API_DEPLOYMENT_NAME &&\n process.env.AZURE_OPENAI_API_VERSION\n );\n\n // Same exhaustiveness guard as createEmbeddingModel below: a provider added\n // without a credential branch would otherwise read as \"no credentials\" and\n // silently degrade to full-text-only search. The assertion fails the build;\n // the return is the runtime fallback, and it must stay false so that an\n // unrecognized provider is never reported as having credentials.\n default: {\n const _unhandled: never = provider;\n return false;\n }\n }\n}\n\n/**\n * Creates an embedding model instance based on the specified provider and model name.\n * The provider and model name should be specified in the format \"provider:model_name\"\n * (e.g., \"google:text-embedding-004\"). If no provider is specified (i.e., just \"model_name\"),\n * OpenAI is used as the default provider.\n *\n * Environment variables required per provider:\n * - OpenAI: OPENAI_API_KEY (and optionally OPENAI_API_BASE, OPENAI_ORG_ID)\n * - Google Cloud Vertex AI: GOOGLE_APPLICATION_CREDENTIALS (path to service account JSON)\n * - Google GenAI (Gemini): GOOGLE_API_KEY\n * - AWS: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION (or BEDROCK_AWS_REGION)\n * - Microsoft: AZURE_OPENAI_API_KEY, AZURE_OPENAI_API_INSTANCE_NAME, AZURE_OPENAI_API_DEPLOYMENT_NAME, AZURE_OPENAI_API_VERSION\n *\n * @param providerAndModel - The provider and model name in the format \"provider:model_name\"\n * or just \"model_name\" for OpenAI models.\n * @returns A configured instance of the appropriate Embeddings implementation.\n * @throws {UnsupportedProviderError} Runtime backstop for a supported provider\n * that has no construction branch. An unrecognized prefix is not an\n * error — it is treated as an OpenAI-compatible model name.\n * @throws {ModelConfigurationError} If there's an issue with the model configuration.\n */\nexport function createEmbeddingModel(\n providerAndModel: string,\n runtime?: {\n requestTimeoutMs?: number;\n vectorDimension?: number;\n config?: AppConfig[\"embeddings\"];\n },\n): Embeddings {\n const config = runtime?.config;\n const requestTimeoutMs = runtime?.requestTimeoutMs ?? config?.requestTimeoutMs;\n const vectorDimension = runtime?.vectorDimension ?? config?.vectorDimension;\n if (vectorDimension === undefined) {\n throw new ModelConfigurationError(\n \"Embedding vector dimension is required; set DOCS_MCP_EMBEDDINGS_VECTOR_DIMENSION or embeddings.vectorDimension in config.\",\n );\n }\n // Parse provider and model name using the shared specification rules\n const { provider, model } = splitModelSpec(providerAndModel);\n\n // Default configuration for each provider\n const baseConfig = { stripNewLines: true };\n\n switch (provider) {\n case \"openai\": {\n if (!process.env.OPENAI_API_KEY) {\n throw new MissingCredentialsError(\"openai\", [\"OPENAI_API_KEY\"]);\n }\n const apiKey = process.env.OPENAI_API_KEY;\n const baseURL = process.env.OPENAI_API_BASE;\n const config: Partial<OpenAIEmbeddingsParams> & {\n apiKey?: string;\n configuration?: ClientOptions;\n } = {\n ...baseConfig,\n apiKey,\n modelName: model,\n batchSize: 512, // OpenAI supports large batches\n timeout: requestTimeoutMs,\n // Request plain float arrays instead of letting the OpenAI SDK pick its\n // default. Without this the SDK sends `encoding_format: \"base64\"` and then\n // unconditionally base64-decodes the response. OpenAI-compatible providers\n // that ignore the parameter (Mistral, LM Studio, Ollama, ...) return JSON\n // floats, which the decoder mangles into a silently corrupted vector of a\n // quarter the length and every element zero.\n encodingFormat: \"float\",\n configuration: {\n ...(baseURL ? { baseURL } : {}),\n timeout: requestTimeoutMs,\n },\n };\n return new OpenAIEmbeddings(config);\n }\n\n case \"vertex\": {\n if (!process.env.GOOGLE_APPLICATION_CREDENTIALS) {\n throw new MissingCredentialsError(\"vertex\", [\"GOOGLE_APPLICATION_CREDENTIALS\"]);\n }\n return new VertexAIEmbeddings({\n ...baseConfig,\n model: model, // e.g., \"text-embedding-004\"\n });\n }\n\n case \"gemini\": {\n if (!process.env.GOOGLE_API_KEY) {\n throw new MissingCredentialsError(\"gemini\", [\"GOOGLE_API_KEY\"]);\n }\n // Create base embeddings and wrap with FixedDimensionEmbeddings since Gemini\n // supports MRL (Matryoshka Representation Learning) for safe truncation\n const baseEmbeddings = new GoogleGenerativeAIEmbeddings({\n ...baseConfig,\n apiKey: process.env.GOOGLE_API_KEY,\n model: model, // e.g., \"gemini-embedding-exp-03-07\"\n });\n return new FixedDimensionEmbeddings(\n baseEmbeddings,\n vectorDimension,\n providerAndModel,\n true,\n );\n }\n\n case \"aws\": {\n // For AWS, model should be the full Bedrock model ID\n const region = process.env.BEDROCK_AWS_REGION || process.env.AWS_REGION;\n const missingCredentials: string[] = [];\n\n if (!region) {\n missingCredentials.push(\"BEDROCK_AWS_REGION or AWS_REGION\");\n }\n\n // Allow using AWS_PROFILE for credentials if set\n if (\n !process.env.AWS_PROFILE &&\n !process.env.AWS_ACCESS_KEY_ID &&\n !process.env.AWS_SECRET_ACCESS_KEY\n ) {\n missingCredentials.push(\n \"AWS_PROFILE or (AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY)\",\n );\n }\n\n if (missingCredentials.length > 0) {\n throw new MissingCredentialsError(\"aws\", missingCredentials);\n }\n\n // Only pass explicit credentials if present, otherwise let SDK resolve via profile/other means\n const credentials =\n process.env.AWS_ACCESS_KEY_ID && process.env.AWS_SECRET_ACCESS_KEY\n ? {\n accessKeyId: process.env.AWS_ACCESS_KEY_ID,\n secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,\n sessionToken: process.env.AWS_SESSION_TOKEN,\n }\n : undefined;\n\n return new BedrockEmbeddings({\n ...baseConfig,\n model: model, // e.g., \"amazon.titan-embed-text-v1\"\n region,\n ...(credentials ? { credentials } : {}),\n });\n }\n\n case \"microsoft\": {\n // For Azure, model name corresponds to the deployment name\n const missingCredentials: string[] = [];\n\n if (!process.env.AZURE_OPENAI_API_KEY) {\n missingCredentials.push(\"AZURE_OPENAI_API_KEY\");\n }\n if (!process.env.AZURE_OPENAI_API_INSTANCE_NAME) {\n missingCredentials.push(\"AZURE_OPENAI_API_INSTANCE_NAME\");\n }\n if (!process.env.AZURE_OPENAI_API_DEPLOYMENT_NAME) {\n missingCredentials.push(\"AZURE_OPENAI_API_DEPLOYMENT_NAME\");\n }\n if (!process.env.AZURE_OPENAI_API_VERSION) {\n missingCredentials.push(\"AZURE_OPENAI_API_VERSION\");\n }\n\n if (missingCredentials.length > 0) {\n throw new MissingCredentialsError(\"microsoft\", missingCredentials);\n }\n\n return new AzureOpenAIEmbeddings({\n ...baseConfig,\n azureOpenAIApiKey: process.env.AZURE_OPENAI_API_KEY,\n azureOpenAIApiInstanceName: process.env.AZURE_OPENAI_API_INSTANCE_NAME,\n azureOpenAIApiDeploymentName: process.env.AZURE_OPENAI_API_DEPLOYMENT_NAME,\n azureOpenAIApiVersion: process.env.AZURE_OPENAI_API_VERSION,\n deploymentName: model,\n });\n }\n\n // Every supported provider has a branch above, so this is unreachable through\n // splitModelSpec. Assigning to `never` makes adding a provider without a branch\n // fail typecheck rather than a user's startup; the throw is the runtime backstop.\n default: {\n const unhandled: never = provider;\n throw new UnsupportedProviderError(unhandled);\n }\n }\n}\n","/**\n * Data sanitization utilities for privacy-first telemetry.\n * Events carry the host of a URL instead of the URL itself, and error messages\n * and stack traces lose URLs, file paths and credentials before they are sent.\n */\n\n/**\n * Extracts hostname from URL for aggregated analytics without exposing paths.\n * Examples:\n * - https://docs.python.org/3/library/os.html -> docs.python.org\n * - https://github.com/owner/repo -> github.com\n * - http://localhost:3000/api -> localhost\n *\n * @param url - The URL to extract the hostname from.\n * @returns The hostname, an empty string for `file:` URLs, or \"invalid-hostname\".\n */\nexport function extractHostname(url: string): string {\n try {\n const parsed = new URL(url);\n return parsed.hostname;\n } catch {\n return \"invalid-hostname\";\n }\n}\n\n/**\n * Extracts protocol from URL or file path for privacy-safe analytics.\n * Examples:\n * - https://github.com/owner/repo -> \"https\"\n * - file:///local/path -> \"file\"\n * - /local/path -> \"file\" (detected as local file)\n * - C:\\local\\path -> \"file\" (detected as local file)\n *\n * @param urlOrPath - The URL or local path to inspect.\n * @returns The protocol without its trailing colon, \"file\", or \"unknown\".\n */\nexport function extractProtocol(urlOrPath: string): string {\n try {\n const parsed = new URL(urlOrPath);\n return parsed.protocol.replace(\":\", \"\");\n } catch {\n // If URL parsing fails, check if it looks like a local file path\n if (urlOrPath.startsWith(\"/\") || /^[A-Za-z]:/.test(urlOrPath)) {\n return \"file\";\n }\n return \"unknown\";\n }\n}\n\n/**\n * Sanitizes error messages to remove sensitive information while preserving diagnostic value.\n * Examples:\n * - \"Failed to fetch https://secret.com/api\" -> \"Failed to fetch [url]\"\n * - \"File not found: /home/user/secret.txt\" -> \"File not found: [path]\"\n * - \"ENOENT: no such file or directory, scandir '/Users/Jane Doe/docs'\" -> \"... scandir '[path]'\"\n *\n * @param message - The raw error message.\n * @returns The message without URLs, paths or credentials, cut to 200 characters.\n */\nexport function sanitizeErrorMessage(message: string): string {\n return (\n message\n .replace(/https?:\\/\\/[^\\s]+/gi, \"[url]\")\n .replace(/file:\\/\\/[^\\s]+/gi, \"[file-url]\")\n // Quoted paths first, so the whole path goes even when it has spaces\n .replace(/(['\"`])(?:(?:~|\\.{1,2})?\\/|[A-Za-z]:[\\\\/])(?:(?!\\1).)*\\1/g, \"$1[path]$1\")\n // Unquoted absolute paths, continued over a space while the next word\n // holds a separator, as in \"/Users/Jane Doe/docs\"\n .replace(\n /(?<![\\w\\]])(?:(?:~|\\.{1,2})?\\/|[A-Za-z]:[\\\\/])[^\\s'\"`<>()]+(?:\\s+[^\\s'\"`<>()\\\\/]+[\\\\/][^\\s'\"`<>()]*)*/g,\n \"[path]\",\n )\n .replace(/\\/[^\\s]*\\.[a-z]{2,4}/gi, \"[path]\")\n .replace(/Bearer\\s+[^\\s]+/gi, \"Bearer [token]\")\n .replace(/api[_-]?key[=:]\\s*[^\\s]+/gi, \"api_key=[redacted]\")\n .replace(/token[=:]\\s*[^\\s]+/gi, \"token=[redacted]\")\n .substring(0, 200) // Limit length\n );\n}\n\n/**\n * Splits a stack frame into its prefix, location and `:line` or `:line:column`\n * suffix. Matches `at fn (location:1:2)` and `at location:1:2`.\n */\nconst STACK_FRAME = /^(\\s*at (?:.+? \\()?)(.+?)((?::\\d+){1,2}\\)?)$/;\n\n/** Matches stack frames without a file location, such as `at async Promise.all (index 0)`. */\nconst LOCATIONLESS_FRAME = /^\\s*at .+ \\((?:<anonymous>|native|index \\d+)\\)$/;\n\n/**\n * Shortens a stack frame location to the path below the last `node_modules`\n * directory, or to the file name, so no user or directory names, hosts, query\n * strings or fragments remain.\n */\nfunction shortenFrameLocation(location: string): string {\n if (location.startsWith(\"node:\")) return location;\n if (location.startsWith(\"data:\")) return \"data:\";\n const normalized = location\n .replace(/^[a-z][a-z\\d+.-]*:\\/\\//i, \"\")\n .replace(/[?#].*$/, \"\")\n .replace(/\\\\/g, \"/\");\n const marker = \"/node_modules/\";\n const nodeModules = normalized.lastIndexOf(marker);\n if (nodeModules !== -1) return normalized.slice(nodeModules + marker.length);\n return normalized.slice(normalized.lastIndexOf(\"/\") + 1);\n}\n\n/**\n * Returns a stack frame with its location shortened, the frame itself when it\n * has no location, or null for a line that is not a recognizable frame.\n */\nfunction sanitizeStackFrame(line: string): string | null {\n const match = STACK_FRAME.exec(line);\n if (match) {\n const [, prefix, location, suffix] = match;\n return `${prefix}${shortenFrameLocation(location)}${suffix}`;\n }\n return LOCATIONLESS_FRAME.test(line) ? line : null;\n}\n\n/**\n * Creates a copy of an error that is safe to send to error tracking. The message\n * goes through {@link sanitizeErrorMessage}, stack frames keep only the file name\n * (or the package path below `node_modules`), lines that are not recognizable\n * frames are dropped, and causes are sanitized the same way.\n *\n * @param error - The error to sanitize.\n * @returns A new error with the same name and sanitized message, stack and cause.\n */\nexport function sanitizeErrorForTracking(error: Error): Error {\n const message = sanitizeErrorMessage(error.message);\n const cause =\n error.cause instanceof Error ? sanitizeErrorForTracking(error.cause) : undefined;\n const sanitized = new Error(message, cause ? { cause } : undefined);\n sanitized.name = error.name;\n\n const frames = (error.stack ?? \"\")\n .split(\"\\n\")\n .filter((line) => /^\\s*at /.test(line))\n .map(sanitizeStackFrame)\n .filter((frame): frame is string => frame !== null);\n sanitized.stack = [`${error.name}: ${message}`, ...frames].join(\"\\n\");\n\n return sanitized;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport envPaths from \"env-paths\";\nimport { logger } from \"./logger\";\n\nlet projectRoot: string | null = null;\n\n/**\n * Reset the cached project root. For testing purposes only.\n * @internal\n */\nexport function _resetProjectRootCache(): void {\n projectRoot = null;\n}\n\n/**\n * Finds the project root directory by searching upwards from the current file\n * for a directory containing 'package.json'. Caches the result.\n *\n * @returns {string} The absolute path to the project root.\n * @throws {Error} If package.json cannot be found.\n */\nexport function getProjectRoot(): string {\n // Return cached result if available\n if (projectRoot) {\n return projectRoot;\n }\n\n // Start from the directory of the current module\n const currentFilePath = fileURLToPath(import.meta.url);\n let currentDir = path.dirname(currentFilePath);\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const packageJsonPath = path.join(currentDir, \"package.json\");\n if (fs.existsSync(packageJsonPath)) {\n // Cache the found project root directory\n projectRoot = currentDir;\n return currentDir;\n }\n\n const parentDir = path.dirname(currentDir);\n // Check if we have reached the filesystem root\n if (parentDir === currentDir) {\n throw new Error(\"Could not find project root containing package.json.\");\n }\n currentDir = parentDir;\n }\n}\n\n/**\n * Resolves the data storage path using the following priority:\n * 1. Provided storePath parameter\n * 2. Legacy .store directory in project root (if exists)\n * 3. Standard system data directory using env-paths\n *\n * @param storePath Optional custom storage path\n * @returns Resolved absolute path for data storage\n */\nexport function resolveStorePath(storePath?: string): string {\n let dbDir: string;\n\n // 1. Check storePath parameter\n if (storePath) {\n dbDir = path.resolve(storePath);\n } else {\n // 2. Check Old Local Path\n const projectRoot = getProjectRoot();\n const oldDbDir = path.join(projectRoot, \".store\");\n const oldDbPath = path.join(oldDbDir, \"documents.db\");\n const oldDbExists = fs.existsSync(oldDbPath); // Check file existence specifically\n\n if (oldDbExists) {\n dbDir = oldDbDir;\n } else {\n // 3. Use Standard Path\n const standardPaths = envPaths(\"docs-mcp-server\", { suffix: \"\" });\n dbDir = standardPaths.data;\n }\n }\n\n // Ensure the chosen directory exists\n try {\n fs.mkdirSync(dbDir, { recursive: true });\n } catch (error) {\n // Log potential error during directory creation but proceed\n // The DocumentStore constructor might handle DB file creation errors\n logger.warn(`⚠️ Failed to create database directory ${dbDir}: ${error}`);\n }\n\n return dbDir;\n}\n","/**\n * Telemetry configuration management for enabling/disabling analytics collection.\n * Handles CLI flags, environment variables, and default settings.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { resolveStorePath } from \"../utils/paths\";\n\nexport class TelemetryConfig {\n private static instance?: TelemetryConfig;\n private enabled: boolean = true; // Default to enabled\n\n private constructor() {\n // Private constructor for singleton pattern\n }\n\n isEnabled(): boolean {\n return this.enabled;\n }\n\n setEnabled(enabled: boolean): void {\n this.enabled = enabled;\n }\n\n static getInstance(): TelemetryConfig {\n if (!TelemetryConfig.instance) {\n TelemetryConfig.instance = new TelemetryConfig();\n }\n return TelemetryConfig.instance;\n }\n}\n\n/**\n * Generate or retrieve a persistent installation identifier.\n * Creates a UUID and stores it in a file in the user data directory.\n * Supports custom store path override for Docker deployments.\n * This ensures truly unique identification that persists across runs.\n */\nexport function generateInstallationId(storePath?: string): string {\n try {\n // Use centralized path resolution logic\n const dataDir = resolveStorePath(storePath);\n const installationIdPath = path.join(dataDir, \"installation.id\");\n\n // Try to read existing installation ID\n if (fs.existsSync(installationIdPath)) {\n const existingId = fs.readFileSync(installationIdPath, \"utf8\").trim();\n if (existingId) {\n return existingId;\n }\n }\n\n // Generate new UUID and store it\n const newId = randomUUID();\n\n // Ensure directory exists\n fs.mkdirSync(dataDir, { recursive: true });\n\n // Write the installation ID\n fs.writeFileSync(installationIdPath, newId, \"utf8\");\n\n return newId;\n } catch {\n // Fallback to a session-only UUID if file operations fail\n // This ensures analytics always has a valid distinct ID\n return randomUUID();\n }\n}\n\n/**\n * Check if telemetry should be enabled based on environment and CLI flags.\n */\nexport function shouldEnableTelemetry(): boolean {\n return TelemetryConfig.getInstance().isEnabled();\n}\n","/**\n * Centralized event type definitions for the event bus system.\n * This serves as the single source of truth for all events in the application.\n */\n\nimport type { PipelineJob } from \"../pipeline/types\";\nimport type { ScraperProgressEvent } from \"../scraper/types\";\n\n/**\n * Event type enum used by the EventBusService.\n * These are the internal event identifiers.\n */\nexport enum EventType {\n JOB_STATUS_CHANGE = \"JOB_STATUS_CHANGE\",\n JOB_PROGRESS = \"JOB_PROGRESS\",\n LIBRARY_CHANGE = \"LIBRARY_CHANGE\",\n JOB_LIST_CHANGE = \"JOB_LIST_CHANGE\",\n}\n\n/**\n * Type-safe mapping of event types to their payload structures.\n */\nexport interface EventPayloads {\n [EventType.JOB_STATUS_CHANGE]: PipelineJob;\n [EventType.JOB_PROGRESS]: {\n job: PipelineJob;\n progress: ScraperProgressEvent;\n };\n [EventType.LIBRARY_CHANGE]: undefined;\n [EventType.JOB_LIST_CHANGE]: undefined;\n}\n\n/**\n * Type-safe event listener callback.\n */\nexport type EventListener<T extends EventType> = (payload: EventPayloads[T]) => void;\n","import type { ScraperOptions, ScraperProgressEvent } from \"../scraper/types\";\nimport type { VersionStatus } from \"../store/types\";\n\n/**\n * Represents the possible states of a pipeline job.\n */\nexport enum PipelineJobStatus {\n QUEUED = \"queued\",\n RUNNING = \"running\",\n COMPLETED = \"completed\",\n FAILED = \"failed\",\n CANCELLING = \"cancelling\",\n CANCELLED = \"cancelled\",\n}\n\n/**\n * What a pipeline does when it starts with versions that an earlier run left\n * RUNNING or QUEUED:\n * - `recover`: runs them again as refresh jobs.\n * - `fail`: marks them FAILED, so users can retry them.\n * - `leave`: changes nothing, for a command that runs only its own job while\n * the process that hosts the store handles the rest.\n */\nexport type InterruptedJobs = \"recover\" | \"fail\" | \"leave\";\n\n/**\n * Public interface for pipeline jobs exposed through API boundaries.\n * Contains only serializable fields suitable for JSON transport.\n */\nexport interface PipelineJob {\n /** Unique identifier for the job. */\n id: string;\n /** The library name associated with the job. */\n library: string;\n /** The library version associated with the job. */\n version: string | null;\n /** Current pipeline status of the job. */\n status: PipelineJobStatus;\n /** Detailed progress information. */\n progress: ScraperProgressEvent | null;\n /** Error information if the job failed. */\n error: { message: string } | null;\n /** Timestamp when the job was created. */\n createdAt: Date;\n /** Timestamp when the job started running. */\n startedAt: Date | null;\n /** Timestamp when the job finished (completed, failed, or cancelled). */\n finishedAt: Date | null;\n /** Database version ID for direct updates. */\n versionId?: number;\n /** Database version status (authoritative). */\n versionStatus?: VersionStatus;\n /** Items dequeued and given an outcome. */\n progressPages?: number;\n /**\n * Items this job expects to process — queued URLs clamped at the stopping\n * point. NOT the configured `maxPages` value, despite the name.\n */\n progressMaxPages?: number;\n /** Items that produced stored content. Null for jobs predating this counter. */\n progressPagesIndexed?: number | null;\n /** Database error message (more detailed than Error object). */\n errorMessage?: string | null;\n /** Last update timestamp from database. */\n updatedAt?: Date;\n /** Original scraping URL. */\n sourceUrl: string | null;\n /** Stored scraper options for reproducibility. */\n scraperOptions: ScraperOptions | null;\n}\n\n/**\n * Internal pipeline job representation used within PipelineManager.\n * Contains non-serializable fields for job management and control.\n *\n * Note: scraperOptions is required (non-nullable) for internal jobs as they\n * always have complete runtime configuration available.\n */\nexport interface InternalPipelineJob\n extends Omit<PipelineJob, \"version\" | \"error\" | \"scraperOptions\" | \"versionId\"> {\n /** The library version associated with the job (internal uses string). */\n version: string;\n /** Database version ID, claimed when the job is enqueued. */\n versionId: number;\n /** Error object if the job failed. */\n error: Error | null;\n /** Complete scraper options with runtime configuration. */\n scraperOptions: ScraperOptions;\n /** AbortController to signal cancellation. */\n abortController: AbortController;\n /** Promise that resolves/rejects when the job finishes. */\n completionPromise: Promise<void>;\n /** Resolver function for the completion promise. */\n resolveCompletion: () => void;\n /** Rejector function for the completion promise. */\n rejectCompletion: (reason?: unknown) => void;\n}\n","/**\n * PostHog client wrapper for telemetry events.\n * Handles PostHog SDK integration and event capture with privacy-first configuration.\n * Automatically converts camelCase property names to snake_case for PostHog compatibility.\n */\n\nimport { PostHog } from \"posthog-node\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * Convert camelCase string to snake_case\n * Specifically designed for PostHog property name conversion\n */\nfunction camelToSnakeCase(str: string): string {\n return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);\n}\n\n/**\n * Recursively convert object keys from camelCase to snake_case\n * Handles nested objects and arrays while preserving values\n */\nfunction convertPropertiesToSnakeCase(\n obj: Record<string, unknown>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(obj)) {\n const snakeKey = camelToSnakeCase(key);\n\n if (\n value &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n !(value instanceof Date)\n ) {\n // Recursively convert nested objects\n result[snakeKey] = convertPropertiesToSnakeCase(value as Record<string, unknown>);\n } else if (Array.isArray(value)) {\n // Handle arrays - convert elements if they are objects\n result[snakeKey] = value.map((item) =>\n item && typeof item === \"object\" && !(item instanceof Date)\n ? convertPropertiesToSnakeCase(item as Record<string, unknown>)\n : item,\n );\n } else {\n // Primitive values, dates, and null/undefined - keep as-is\n result[snakeKey] = value;\n }\n }\n\n return result;\n}\n\n/**\n * Add PostHog standard properties and remove duplicates\n * Maps our properties to PostHog's expected property names\n */\nfunction addPostHogStandardProperties(\n properties: Record<string, unknown>,\n): Record<string, unknown> {\n const result = { ...properties };\n\n // Add PostHog standard session properties\n if (properties.sessionId) {\n result.$session_id = properties.sessionId;\n delete result.sessionId; // Remove duplicate\n }\n\n if (properties.startTime) {\n result.$start_timestamp = (properties.startTime as Date).toISOString();\n delete result.startTime; // Remove duplicate\n }\n\n // Add PostHog standard app properties\n if (properties.appVersion) {\n result.$app_version = properties.appVersion;\n delete result.appVersion; // Remove duplicate\n }\n\n return result;\n}\n\n/**\n * PostHog client wrapper for telemetry events\n */\nexport class PostHogClient {\n private client?: PostHog;\n private enabled: boolean;\n\n // PostHog configuration\n private static readonly CONFIG = {\n host: \"https://app.posthog.com\",\n\n // Performance optimizations\n flushAt: 20, // Batch size - send after 20 events\n flushInterval: 10000, // 10 seconds - send after time\n\n // Privacy settings\n disableGeoip: true, // Don't collect IP geolocation\n disableSessionRecording: true, // Never record sessions\n disableSurveys: true, // No user surveys\n\n // Data handling\n persistence: \"memory\" as const, // No disk persistence for privacy\n };\n\n constructor(enabled: boolean) {\n this.enabled = enabled;\n\n if (!this.enabled) {\n return; // Early return if analytics is disabled\n }\n\n if (!__POSTHOG_API_KEY__) {\n logger.debug(\"PostHog API key not provided\");\n this.enabled = false;\n return;\n }\n\n try {\n this.client = new PostHog(__POSTHOG_API_KEY__, {\n host: PostHogClient.CONFIG.host,\n flushAt: PostHogClient.CONFIG.flushAt,\n flushInterval: PostHogClient.CONFIG.flushInterval,\n disableGeoip: PostHogClient.CONFIG.disableGeoip,\n });\n logger.debug(\"PostHog client initialized\");\n } catch (error) {\n logger.debug(\n `PostHog initialization failed: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n this.enabled = false;\n }\n }\n\n /**\n * Send event to PostHog\n */\n capture(distinctId: string, event: string, properties: Record<string, unknown>): void {\n if (!this.enabled || !this.client) return;\n\n try {\n // Add PostHog standard properties and remove duplicates\n const enhancedProperties = addPostHogStandardProperties(properties);\n\n // Convert camelCase properties to snake_case for PostHog\n const snakeCaseProperties = convertPropertiesToSnakeCase(enhancedProperties);\n\n this.client.capture({\n distinctId,\n event,\n properties: snakeCaseProperties,\n });\n logger.debug(`PostHog event captured: ${event}`);\n } catch (error) {\n logger.debug(\n `PostHog capture error: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n }\n\n /**\n * Capture exception using PostHog's native error tracking\n */\n captureException(\n distinctId: string,\n error: Error,\n properties?: Record<string, unknown>,\n ): void {\n if (!this.enabled || !this.client) return;\n\n try {\n // Add PostHog standard properties and remove duplicates\n const enhancedProperties = addPostHogStandardProperties(properties || {});\n\n // Convert camelCase properties to snake_case for PostHog\n const snakeCaseProperties = convertPropertiesToSnakeCase(enhancedProperties);\n\n this.client.captureException(error, distinctId, snakeCaseProperties);\n logger.debug(`PostHog exception captured: ${error.constructor.name}`);\n } catch (captureError) {\n logger.debug(\n `PostHog captureException error: ${captureError instanceof Error ? captureError.message : \"Unknown error\"}`,\n );\n }\n }\n\n /**\n * Graceful shutdown with event flushing\n */\n async shutdown(): Promise<void> {\n if (this.client) {\n try {\n await this.client.shutdown();\n logger.debug(\"PostHog client shutdown complete\");\n } catch (error) {\n logger.debug(\n `PostHog shutdown error: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n }\n }\n\n /**\n * Check if client is enabled and ready\n */\n isEnabled(): boolean {\n return this.enabled && !!this.client;\n }\n}\n","/**\n * Telemtry wrapper for privacy-first telemetry using PostHog.\n * Provides global context and automatic data sanitization.\n *\n * Architecture:\n * - PostHogClient: Handles PostHog SDK integration and event capture\n * - Telemtry: High-level coordinator providing public API with global context\n */\n\nimport { logger } from \"../utils/logger\";\nimport type { TelemetryEventPropertiesMap } from \"./eventTypes\";\nimport { PostHogClient } from \"./postHogClient\";\nimport { sanitizeErrorForTracking } from \"./sanitizer\";\nimport { generateInstallationId, TelemetryConfig } from \"./TelemetryConfig\";\n\n/**\n * Event types for structured telemetry tracking\n */\nexport enum TelemetryEvent {\n APP_STARTED = \"app_started\",\n APP_SHUTDOWN = \"app_shutdown\",\n CLI_COMMAND = \"cli_command\",\n TOOL_USED = \"tool_used\",\n PIPELINE_JOB_STARTED = \"pipeline_job_started\",\n PIPELINE_JOB_COMPLETED = \"pipeline_job_completed\",\n PIPELINE_JOB_FAILED = \"pipeline_job_failed\",\n}\n\n/**\n * Main telemetry class providing privacy-first telemetry\n */\nexport class Telemetry {\n private postHogClient: PostHogClient;\n private enabled: boolean;\n private distinctId: string;\n private globalContext: Record<string, unknown> = {};\n\n /**\n * Create a new Telemetry instance with proper initialization\n * This is the recommended way to create Telemetry instances\n *\n * @param storePath - Store directory that holds the installation ID; defaults to the standard data directory.\n * @returns The telemetry instance.\n */\n static create(storePath?: string): Telemetry {\n const config = TelemetryConfig.getInstance();\n\n // Single determination point for enabled status\n const shouldEnable = config.isEnabled() && !!__POSTHOG_API_KEY__;\n\n const telemetry = new Telemetry(shouldEnable, storePath);\n\n // Single log message after everything is initialized with better context\n if (telemetry.isEnabled()) {\n logger.debug(\"Telemetry enabled\");\n } else if (!config.isEnabled()) {\n logger.debug(\"Telemetry disabled (user preference)\");\n } else if (!__POSTHOG_API_KEY__) {\n logger.debug(\"Telemetry disabled (no API key configured)\");\n } else {\n logger.debug(\"Telemetry disabled\");\n }\n\n return telemetry;\n }\n\n /**\n * Private constructor - use Telemetry.create() instead\n */\n private constructor(enabled: boolean, storePath?: string) {\n this.enabled = enabled;\n this.distinctId = generateInstallationId(storePath);\n this.postHogClient = new PostHogClient(this.enabled);\n }\n\n /**\n * Set global application context that will be included in all events\n */\n setGlobalContext(context: Record<string, unknown>): void {\n this.globalContext = { ...context };\n }\n\n /**\n * Track an event with automatic global context inclusion\n *\n * Type-safe overloads for specific events:\n */\n track<T extends keyof TelemetryEventPropertiesMap>(\n event: T,\n properties: TelemetryEventPropertiesMap[T],\n ): void;\n track(event: string, properties?: Record<string, unknown>): void;\n track(event: string, properties: Record<string, unknown> = {}): void {\n if (!this.enabled) return;\n\n // Merge global context and event properties with timestamp\n const enrichedProperties = {\n ...this.globalContext,\n ...properties,\n timestamp: new Date().toISOString(),\n };\n logger.debug(`Tracking event: ${event}`);\n this.postHogClient.capture(this.distinctId, event, enrichedProperties);\n }\n\n /**\n * Capture exception using PostHog's native error tracking with global context.\n * The error is sent without URLs, file paths or credentials in its message and stack.\n */\n captureException(\n error: Error | unknown,\n properties: Record<string, unknown> = {},\n ): void {\n if (!this.enabled) return;\n\n // Merge global context and error properties with timestamp\n const enrichedProperties = {\n ...this.globalContext,\n ...properties,\n timestamp: new Date().toISOString(),\n };\n logger.debug(\n `Capturing exception: ${error instanceof Error ? error.message : String(error)}`,\n );\n this.postHogClient.captureException(\n this.distinctId,\n sanitizeErrorForTracking(error instanceof Error ? error : new Error(String(error))),\n enrichedProperties,\n );\n }\n\n /**\n * Graceful shutdown with event flushing\n */\n async shutdown(): Promise<void> {\n if (!this.enabled) return;\n\n await this.postHogClient.shutdown();\n }\n\n /**\n * Check if telemetry is enabled\n */\n isEnabled(): boolean {\n return this.enabled;\n }\n}\n\n/**\n * Global telemetry instance - initialized lazily\n */\nlet telemetryInstance: Telemetry | null = null;\n\n/**\n * Get the global telemetry instance, initializing it if needed\n */\nexport function getTelemetryInstance(): Telemetry {\n if (!telemetryInstance) {\n // Create a basic telemetry instance if not yet initialized\n telemetryInstance = Telemetry.create();\n }\n return telemetryInstance;\n}\n\n/**\n * Initialize telemetry system with proper configuration.\n * This should be called once at application startup.\n */\nexport function initTelemetry(options: { enabled: boolean; storePath?: string }): void {\n // Configure telemetry enabled state\n TelemetryConfig.getInstance().setEnabled(options.enabled);\n\n // Create the telemetry instance, reading the installation ID from the store path\n telemetryInstance = Telemetry.create(options.storePath);\n}\n\n// Export a proxy object that always delegates to the current telemetry instance.\n// This ensures configuration changes (like disabling telemetry via initTelemetry)\n// are always reflected, avoiding stale cached state.\nexport const telemetry = new Proxy({} as Telemetry, {\n get(_target, prop) {\n const instance = getTelemetryInstance();\n const value = instance[prop as keyof Telemetry];\n\n // Bind methods to the instance to preserve 'this' context\n if (typeof value === \"function\") {\n return value.bind(instance);\n }\n return value;\n },\n});\n","/**\n * TelemetryService listens to events from the EventBusService and tracks them to analytics.\n * This decouples telemetry concerns from the PipelineManager, following the event-driven architecture.\n * A local backend starts one with its pipeline, so only the process that runs a\n * job reports it; relayed copies of a remote worker's events are not reported.\n */\n\nimport type { EventBusService } from \"../events/EventBusService\";\nimport { EventType } from \"../events/types\";\nimport { type PipelineJob, PipelineJobStatus } from \"../pipeline/types\";\nimport type { ScraperProgressEvent } from \"../scraper/types\";\nimport { logger } from \"../utils/logger\";\nimport { sanitizeErrorMessage } from \"./sanitizer\";\nimport { TelemetryEvent, telemetry } from \"./telemetry\";\n\nexport class TelemetryService {\n private eventBus: EventBusService;\n private unsubscribers: (() => void)[] = [];\n\n constructor(eventBus: EventBusService) {\n this.eventBus = eventBus;\n this.setupEventListeners();\n }\n\n /**\n * Sets up event listeners for pipeline events.\n */\n private setupEventListeners(): void {\n // Listen to job status changes\n const unsubStatusChange = this.eventBus.on(\n EventType.JOB_STATUS_CHANGE,\n this.handleJobStatusChange.bind(this),\n );\n\n // Listen to job progress events for error tracking\n const unsubProgress = this.eventBus.on(\n EventType.JOB_PROGRESS,\n this.handleJobProgress.bind(this),\n );\n\n this.unsubscribers.push(unsubStatusChange, unsubProgress);\n\n logger.debug(\"TelemetryService initialized and listening to events\");\n }\n\n /**\n * Handles job status change events and tracks them to analytics.\n * Only tracks events for meaningful state transitions: started, completed, and failed.\n */\n private handleJobStatusChange(job: PipelineJob): void {\n const duration = job.startedAt ? Date.now() - job.startedAt.getTime() : null;\n const queueWaitTime =\n job.startedAt && job.createdAt\n ? job.startedAt.getTime() - job.createdAt.getTime()\n : null;\n\n switch (job.status) {\n case PipelineJobStatus.RUNNING:\n telemetry.track(TelemetryEvent.PIPELINE_JOB_STARTED, {\n jobId: job.id,\n library: job.library,\n hasVersion: !!job.version,\n maxPagesConfigured: job.scraperOptions?.maxPages ?? null,\n queueWaitTimeMs: queueWaitTime,\n });\n break;\n\n case PipelineJobStatus.COMPLETED:\n telemetry.track(TelemetryEvent.PIPELINE_JOB_COMPLETED, {\n jobId: job.id,\n library: job.library,\n durationMs: duration,\n pagesProcessed: job.progressPages || 0,\n maxPagesConfigured: job.scraperOptions?.maxPages ?? null,\n hasVersion: !!job.version,\n throughputPagesPerSecond:\n duration && job.progressPages\n ? Math.round((job.progressPages / duration) * 1000)\n : 0,\n });\n break;\n\n case PipelineJobStatus.FAILED:\n telemetry.track(TelemetryEvent.PIPELINE_JOB_FAILED, {\n jobId: job.id,\n library: job.library,\n durationMs: duration,\n pagesProcessed: job.progressPages || 0,\n maxPagesConfigured: job.scraperOptions?.maxPages ?? null,\n hasVersion: !!job.version,\n hasError: !!job.error,\n errorMessage: job.error ? sanitizeErrorMessage(job.error.message) : undefined,\n });\n break;\n\n // Ignore queued, cancelling, and cancelled states - no telemetry needed\n default:\n break;\n }\n }\n\n /**\n * Handles job progress events. Currently a no-op but can be extended\n * for progress-specific telemetry tracking.\n */\n private handleJobProgress(_event: {\n job: PipelineJob;\n progress: ScraperProgressEvent;\n }): void {\n // Currently no telemetry needed for progress events\n // This handler is here for future extensibility\n }\n\n /**\n * Cleans up event listeners.\n */\n shutdown(): void {\n for (const unsubscribe of this.unsubscribers) {\n unsubscribe();\n }\n this.unsubscribers = [];\n logger.debug(\"TelemetryService shut down\");\n }\n}\n","/**\n * Central event bus service for application-wide event distribution.\n *\n * This service provides a pub/sub mechanism that can be used by any service\n * to emit and listen for events. Events emitted here can be:\n * - Consumed locally by in-process subscribers\n * - Broadcast to remote processes via tRPC subscriptions\n * - Forwarded to SSE clients via the web service\n *\n * This decouples event producers (like DocumentManagementService) from\n * consumers (like the Web UI), enabling a clean, scalable architecture.\n */\n\nimport EventEmitter from \"node:events\";\nimport { logger } from \"../utils/logger\";\nimport type { EventListener, EventPayloads, EventType } from \"./types\";\n\n/**\n * Central event bus for application-wide events.\n */\nexport class EventBusService {\n private emitter: EventEmitter;\n\n constructor() {\n this.emitter = new EventEmitter();\n // Increase max listeners to support multiple subscribers\n this.emitter.setMaxListeners(100);\n }\n\n /**\n * Emit an event to all subscribers.\n */\n emit<T extends EventType>(eventType: T, payload: EventPayloads[T]): void {\n logger.debug(`Event emitted: ${eventType}`);\n this.emitter.emit(eventType, payload);\n }\n\n /**\n * Subscribe to events of a specific type.\n * Returns an unsubscribe function.\n */\n on<T extends EventType>(eventType: T, listener: EventListener<T>): () => void {\n this.emitter.on(eventType, listener);\n return () => this.emitter.off(eventType, listener);\n }\n\n /**\n * Remove a specific listener.\n */\n off<T extends EventType>(eventType: T, listener: EventListener<T>): void {\n this.emitter.off(eventType, listener);\n }\n}\n","import type { AppConfig } from \"./config\";\n\n/**\n * Normalize a configured origin (`scheme://host[:port]`) into its canonical form.\n *\n * Empty strings are treated as absent so container environments can leave the\n * variable declared but unset.\n *\n * @param origin - The configured value.\n * @param settingName - The setting named in error messages.\n * @returns The canonical origin, or `undefined` when absent.\n * @throws Error naming the setting when the value is not an HTTP(S) origin.\n */\nexport function normalizePublicOrigin(\n origin: string | undefined,\n settingName = \"server.publicOrigin\",\n): string | undefined {\n const configured = parseConfiguredUrl(\n origin,\n settingName,\n \"origin without path, query, or fragment\",\n );\n if (!configured) {\n return undefined;\n }\n const { parsed } = configured;\n\n if (parsed.pathname !== \"/\" || parsed.search || parsed.hash) {\n throw new Error(`${settingName} must not include a path, query string, or fragment.`);\n }\n\n return parsed.origin;\n}\n\n/**\n * First path segments of the server's own root routes, plus `oauth` for the\n * removed OAuth proxy endpoints. A public URL must not start with one:\n * stripping such a base path from a request the proxy already stripped would\n * remove the route itself (`/mcp` under a base path of `/mcp` would become\n * `/`). These paths also never fall back to the web UI, so clients probing the\n * removed endpoints get a clean 404 instead of an HTML page.\n */\nexport const RESERVED_ROOT_SEGMENTS: readonly string[] = [\n \"mcp\",\n \"api\",\n \"assets\",\n \".well-known\",\n \"sse\",\n \"messages\",\n \"oauth\",\n];\n\n/**\n * Normalize a configured public URL: an absolute HTTP(S) URL that may carry a\n * path, returned without a trailing slash.\n *\n * Empty strings are treated as absent so container environments can leave the\n * variable declared but unset.\n *\n * @param value - The configured `server.publicUrl` value.\n * @returns The canonical URL (e.g. `https://example.com/docs`), or `undefined` when absent.\n * @throws Error naming `server.publicUrl` when the value has credentials, a query\n * string, a fragment, a non-HTTP(S) protocol, an empty path segment (`//`),\n * or a first path segment that collides with a route or file the server\n * serves at its root.\n */\nexport function normalizePublicUrl(value: string | undefined): string | undefined {\n const configured = parseConfiguredUrl(\n value,\n \"server.publicUrl\",\n \"URL without query string or fragment\",\n );\n if (!configured) {\n return undefined;\n }\n const { parsed, trimmed } = configured;\n\n if (trimmed.includes(\"?\") || trimmed.includes(\"#\")) {\n throw new Error(\"server.publicUrl must not include a query string or fragment.\");\n }\n\n // A path starting with \"//\" would become a scheme-relative URL in the web\n // UI's <base href>, pointing the browser at another host. The check runs\n // before the trailing slash is dropped, so \"/docs//\" is refused too.\n if (parsed.pathname.includes(\"//\")) {\n throw new Error(\n `server.publicUrl path must not contain an empty segment (\"//\"): \"${parsed.pathname}\".`,\n );\n }\n const path = parsed.pathname.replace(/\\/$/, \"\");\n\n // Root files such as favicon.ico or manifest.json are the only dotted\n // first segments the server serves; a base path must not shadow them.\n const firstSegment = path.split(\"/\")[1]?.toLowerCase();\n if (\n firstSegment &&\n (RESERVED_ROOT_SEGMENTS.includes(firstSegment) || firstSegment.includes(\".\"))\n ) {\n throw new Error(\n `server.publicUrl path must not start with \"/${firstSegment}\": the server reserves that path for its own routes and files, so requests could not be told apart. Choose a different path, such as \"/docs\".`,\n );\n }\n\n return `${parsed.origin}${path}`;\n}\n\n/**\n * Parse a configured HTTP(S) URL and apply the checks every such setting shares.\n * Empty values count as absent.\n * @returns The parsed URL and the trimmed input, or `undefined` when absent.\n * @throws Error naming the setting when the value is not an HTTP(S) URL or has credentials.\n */\nfunction parseConfiguredUrl(\n value: string | undefined,\n settingName: string,\n expectedShape: string,\n): { parsed: URL; trimmed: string } | undefined {\n const trimmed = value?.trim();\n if (!trimmed) {\n return undefined;\n }\n\n let parsed: URL;\n try {\n parsed = new URL(trimmed);\n } catch {\n throw new Error(`${settingName} must be an absolute HTTP(S) ${expectedShape}.`);\n }\n\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n throw new Error(`${settingName} must use the http or https protocol.`);\n }\n\n if (parsed.username || parsed.password) {\n throw new Error(`${settingName} must not include credentials.`);\n }\n\n return { parsed, trimmed };\n}\n\n/**\n * Where clients reach the server, split into the parts that URL generation and\n * request routing need.\n */\nexport interface PublicLocation {\n /**\n * Whether an operator configured the location (`server.publicUrl` or the\n * deprecated `server.publicOrigin`), rather than it being derived from the bind address.\n */\n configured: boolean;\n /** Canonical base URL without a trailing slash, e.g. `https://example.com/docs`. */\n url: string;\n /** Scheme, host and port, e.g. `https://example.com`. */\n origin: string;\n /** Path prefix without a trailing slash: `\"\"` or e.g. `/docs`. */\n basePath: string;\n}\n\n/**\n * Resolve the public location from configuration: `server.publicUrl` first,\n * then the deprecated `server.publicOrigin`, then the bind-derived origin.\n *\n * @param config - The loaded application configuration.\n * @param port - The port this process listens on (used for the bind fallback).\n * @returns The resolved public location.\n * @throws Error when a configured value is invalid (configuration loading\n * normally rejects those earlier).\n */\nexport function resolvePublicLocation(config: AppConfig, port: number): PublicLocation {\n const configuredUrl =\n normalizePublicUrl(config.server.publicUrl) ??\n normalizePublicOrigin(config.server.publicOrigin);\n const url = configuredUrl ?? buildBindOrigin(config.server.host, port);\n const origin = new URL(url).origin;\n return {\n configured: configuredUrl !== undefined,\n url,\n origin,\n basePath: url.slice(origin.length),\n };\n}\n\n/**\n * Describe deprecation problems with the configured public location, for the\n * caller to log at startup.\n *\n * @param config - The loaded application configuration.\n * @returns Warning messages; empty when nothing needs attention.\n */\nexport function describePublicLocationWarnings(config: AppConfig): string[] {\n const hasUrl = Boolean(config.server.publicUrl?.trim());\n const hasOrigin = Boolean(config.server.publicOrigin?.trim());\n if (hasUrl && hasOrigin) {\n return [\n \"server.publicOrigin is ignored because server.publicUrl is also set. Remove server.publicOrigin.\",\n ];\n }\n if (hasOrigin) {\n return [\"server.publicOrigin is deprecated. Use server.publicUrl instead.\"];\n }\n return [];\n}\n\n/**\n * Build an HTTP origin from the local bind host and port.\n *\n * The server itself listens over HTTP; deployments that terminate TLS should\n * configure server.publicUrl to advertise an HTTPS URL.\n */\nexport function buildBindOrigin(host: string, port: number): string {\n const formattedHost = formatHostForUrl(host);\n return new URL(`http://${formattedHost}:${port}`).origin;\n}\n\nfunction formatHostForUrl(host: string): string {\n const trimmed = host.trim();\n const unbracketed = stripIpv6Brackets(trimmed);\n if (unbracketed.includes(\":\")) {\n return `[${unbracketed}]`;\n }\n return trimmed;\n}\n\n/**\n * Remove the brackets around an IPv6 address literal, as URLs and `Host`\n * headers write it. Other values are returned unchanged.\n * @param host - A host, e.g. `[::1]` or `example.com`.\n * @returns The host without brackets, e.g. `::1`.\n */\nexport function stripIpv6Brackets(host: string): string {\n return host.startsWith(\"[\") && host.endsWith(\"]\") ? host.slice(1, -1) : host;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport envPaths from \"env-paths\";\nimport yaml from \"yaml\";\nimport { z } from \"zod\";\nimport { normalizeEnvValue } from \"./env\";\nimport { logger } from \"./logger\";\nimport { normalizePublicOrigin, normalizePublicUrl } from \"./serverOrigin\";\n\nconst managedConfigVectorDimensionOmissionMarker =\n \"docs-mcp-server-managed-vector-dimension-omitted\";\nconst managedConfigHeader = [\n `# ${managedConfigVectorDimensionOmissionMarker}`,\n \"# embeddings.vectorDimension is omitted when it comes from generated defaults.\",\n \"# Add embeddings.vectorDimension explicitly to override native model dimensions.\",\n \"\",\n].join(\"\\n\");\nconst vectorDimensionPath = [\"embeddings\", \"vectorDimension\"];\n\nconst envStringArray = z\n .union([z.array(z.string()), z.string()])\n .transform((value) => {\n if (Array.isArray(value)) {\n return value;\n }\n\n const parsed = yaml.parse(value);\n if (Array.isArray(parsed)) {\n return parsed.map((item) => String(item));\n }\n\n return [value];\n })\n .pipe(z.array(z.string()));\n\n/**\n * Custom zod schema for boolean values that properly handles string representations.\n * Unlike z.coerce.boolean() which treats any non-empty string as true,\n * this schema correctly parses \"false\", \"0\", \"no\", \"off\" as false.\n */\nconst envBoolean = z\n .union([z.boolean(), z.string()])\n .transform((val) => {\n if (typeof val === \"boolean\") return val;\n const lower = val.toLowerCase().trim();\n return (\n lower !== \"false\" &&\n lower !== \"0\" &&\n lower !== \"no\" &&\n lower !== \"off\" &&\n lower !== \"\"\n );\n })\n .pipe(z.boolean());\n\n/**\n * Parses a boolean environment variable the way configuration settings are\n * parsed: \"false\", \"0\", \"no\", \"off\" and blank are false, anything else true.\n * @param value - The variable's value.\n * @returns The boolean, or undefined when the variable is unset.\n */\nexport function parseEnvBoolean(value: string | undefined): boolean | undefined {\n return value === undefined ? undefined : envBoolean.parse(value);\n}\n\n/**\n * Treats blank strings (empty env vars, `--flag \"\"`) as an absent value so that\n * defaults and fallbacks apply instead of an empty string.\n */\nconst blankToUndefined = (value: unknown): unknown => {\n if (typeof value !== \"string\") {\n return value;\n }\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n};\n\n/** Report a normalizer's error as the validation issue of the setting. */\nfunction addNormalizationIssue(ctx: z.RefinementCtx, error: unknown): void {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: error instanceof Error ? error.message : String(error),\n });\n}\n\n/**\n * An optional string setting that `normalize` validates and canonicalizes.\n * The normalizer treats empty values as absent and throws a message naming\n * the setting for invalid ones.\n */\nfunction normalizedStringSchema<T>(normalize: (value: string | undefined) => T) {\n return z\n .string()\n .optional()\n .transform((value, ctx) => {\n try {\n return normalize(value);\n } catch (error) {\n addNormalizationIssue(ctx, error);\n return z.NEVER;\n }\n });\n}\n\nconst publicOriginSchema = normalizedStringSchema(normalizePublicOrigin);\nconst publicUrlSchema = normalizedStringSchema(normalizePublicUrl);\n\n/**\n * Browser origins allowed to call the MCP endpoint in addition to loopback and\n * the public URL's origin. Each entry must be an exact origin\n * (`scheme://host[:port]`); a trailing slash is ignored.\n */\nconst allowedOriginsSchema = envStringArray.transform((values, ctx) => {\n const origins: string[] = [];\n for (const value of values) {\n try {\n const origin = normalizePublicOrigin(value, \"server.allowedOrigins\");\n if (origin) {\n origins.push(origin);\n }\n } catch (error) {\n addNormalizationIssue(ctx, error);\n return z.NEVER;\n }\n }\n return origins;\n});\n\n// --- Default Global Configuration ---\n\nexport const DEFAULT_CONFIG = {\n app: {\n storePath: \"\",\n telemetryEnabled: true,\n readOnly: false,\n embeddingModel: \"text-embedding-3-small\",\n },\n server: {\n name: \"docs-mcp-server\",\n title: undefined as string | undefined,\n instructions: undefined as string | undefined,\n instructionsFile: undefined as string | undefined,\n protocol: \"auto\",\n host: \"127.0.0.1\",\n publicUrl: undefined as string | undefined,\n publicOrigin: undefined as string | undefined,\n allowedOrigins: [] as string[],\n ports: {\n default: 6280,\n worker: 8080,\n mcp: 6280,\n web: 6281,\n },\n heartbeatMs: 30_000,\n },\n auth: {\n enabled: false,\n issuerUrl: \"\",\n audience: \"\",\n },\n scraper: {\n maxPages: 1000,\n maxDepth: 3,\n maxConcurrency: 3,\n // How often a pipeline marks its unfinished jobs alive in the store. A\n // server starting on the same store treats a job as interrupted only after\n // four intervals without a mark.\n jobHeartbeatMs: 15_000,\n abortOnFailureRate: 0.5,\n preserveHashes: false,\n skipKnownTrackers: true,\n pageTimeoutMs: 5000,\n browserTimeoutMs: 30_000,\n htmlExtractor: \"cheerio\",\n fetcher: {\n maxRetries: 3,\n baseDelayMs: 1000,\n // A server that accepts the connection and then stalls would otherwise\n // hold a worker forever: axios has no default timeout, so nothing else\n // bounds the wait. Generous enough for a slow docs host rendering a\n // large page, short enough that one bad URL cannot park a crawl.\n timeoutMs: 30_000,\n maxCacheItems: 200,\n maxCacheItemSizeBytes: 500 * 1024,\n },\n document: {\n maxSize: 10 * 1024 * 1024, // 10MB max size for PDF/Office documents\n },\n security: {\n network: {\n mode: \"open\",\n allowPrivateNetworks: false,\n allowedHosts: [] as string[],\n allowedCidrs: [] as string[],\n allowInvalidTls: false,\n },\n fileAccess: {\n mode: \"allowedRoots\",\n allowedRoots: [\"$DOCUMENTS\"] as string[],\n followSymlinks: false,\n includeHidden: false,\n },\n },\n },\n splitter: {\n minChunkSize: 500,\n preferredChunkSize: 1500,\n maxChunkSize: 5000,\n treeSitterSizeLimit: 30_000,\n json: {\n maxNestingDepth: 5,\n maxChunks: 1000,\n },\n },\n embeddings: {\n batchSize: 100,\n batchChars: 50_000,\n requestTimeoutMs: 30_000,\n initTimeoutMs: 30_000,\n vectorDimension: 1536,\n },\n db: {\n migrationMaxRetries: 5,\n migrationRetryDelayMs: 300,\n },\n search: {\n overfetchFactor: 2,\n weightVec: 1,\n weightFts: 1,\n vectorMultiplier: 10,\n },\n assembly: {\n maxParentChainDepth: 10,\n childLimit: 3,\n precedingSiblingsLimit: 1,\n subsequentSiblingsLimit: 2,\n maxChunkDistance: 3,\n },\n} as const;\n\n// --- Configuration Schema (Nested) ---\n\nexport const AppConfigSchema = z.object({\n app: z\n .object({\n storePath: z.string().default(DEFAULT_CONFIG.app.storePath),\n telemetryEnabled: envBoolean.default(DEFAULT_CONFIG.app.telemetryEnabled),\n readOnly: envBoolean.default(DEFAULT_CONFIG.app.readOnly),\n embeddingModel: z.string().default(DEFAULT_CONFIG.app.embeddingModel),\n })\n .default(DEFAULT_CONFIG.app),\n server: z\n .object({\n name: z.preprocess(\n blankToUndefined,\n z.string().default(DEFAULT_CONFIG.server.name),\n ),\n title: z.preprocess(blankToUndefined, z.string().optional()),\n instructions: z.preprocess(blankToUndefined, z.string().optional()),\n instructionsFile: z.preprocess(blankToUndefined, z.string().optional()),\n protocol: z.string().default(DEFAULT_CONFIG.server.protocol),\n host: z.string().default(DEFAULT_CONFIG.server.host),\n publicUrl: publicUrlSchema.optional(),\n publicOrigin: publicOriginSchema.optional(),\n allowedOrigins: allowedOriginsSchema.default(DEFAULT_CONFIG.server.allowedOrigins),\n ports: z\n .object({\n default: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.default),\n worker: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.worker),\n mcp: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.mcp),\n web: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.web),\n })\n .default(DEFAULT_CONFIG.server.ports),\n heartbeatMs: z.coerce.number().int().default(DEFAULT_CONFIG.server.heartbeatMs),\n })\n .default({\n name: DEFAULT_CONFIG.server.name,\n protocol: DEFAULT_CONFIG.server.protocol,\n host: DEFAULT_CONFIG.server.host,\n allowedOrigins: DEFAULT_CONFIG.server.allowedOrigins,\n ports: DEFAULT_CONFIG.server.ports,\n heartbeatMs: DEFAULT_CONFIG.server.heartbeatMs,\n }),\n auth: z\n .object({\n enabled: envBoolean.default(DEFAULT_CONFIG.auth.enabled),\n issuerUrl: z.string().default(DEFAULT_CONFIG.auth.issuerUrl),\n audience: z.string().default(DEFAULT_CONFIG.auth.audience),\n })\n .default(DEFAULT_CONFIG.auth),\n scraper: z\n .object({\n maxPages: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.maxPages),\n maxDepth: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.maxDepth),\n maxConcurrency: z.coerce\n .number()\n .int()\n .default(DEFAULT_CONFIG.scraper.maxConcurrency),\n jobHeartbeatMs: z.coerce\n .number()\n .int()\n .positive()\n .default(DEFAULT_CONFIG.scraper.jobHeartbeatMs),\n abortOnFailureRate: z.coerce\n .number()\n .min(0)\n .max(1)\n .default(DEFAULT_CONFIG.scraper.abortOnFailureRate),\n preserveHashes: envBoolean.default(DEFAULT_CONFIG.scraper.preserveHashes),\n skipKnownTrackers: envBoolean.default(DEFAULT_CONFIG.scraper.skipKnownTrackers),\n pageTimeoutMs: z.coerce\n .number()\n .int()\n .default(DEFAULT_CONFIG.scraper.pageTimeoutMs),\n browserTimeoutMs: z.coerce\n .number()\n .int()\n .default(DEFAULT_CONFIG.scraper.browserTimeoutMs),\n htmlExtractor: z\n .enum([\"cheerio\", \"defuddle\"])\n .default(DEFAULT_CONFIG.scraper.htmlExtractor),\n fetcher: z\n .object({\n maxRetries: z.coerce\n .number()\n .int()\n .default(DEFAULT_CONFIG.scraper.fetcher.maxRetries),\n baseDelayMs: z.coerce\n .number()\n .int()\n .default(DEFAULT_CONFIG.scraper.fetcher.baseDelayMs),\n timeoutMs: z.coerce\n .number()\n .int()\n .default(DEFAULT_CONFIG.scraper.fetcher.timeoutMs),\n maxCacheItems: z.coerce\n .number()\n .int()\n .default(DEFAULT_CONFIG.scraper.fetcher.maxCacheItems),\n maxCacheItemSizeBytes: z.coerce\n .number()\n .int()\n .default(DEFAULT_CONFIG.scraper.fetcher.maxCacheItemSizeBytes),\n })\n .default(DEFAULT_CONFIG.scraper.fetcher),\n document: z\n .object({\n maxSize: z.coerce\n .number()\n .int()\n .default(DEFAULT_CONFIG.scraper.document.maxSize),\n })\n .default(DEFAULT_CONFIG.scraper.document),\n security: z\n .object({\n network: z\n .object({\n mode: z\n .enum([\"open\", \"allowlist\"])\n .default(DEFAULT_CONFIG.scraper.security.network.mode),\n allowPrivateNetworks: envBoolean.default(\n DEFAULT_CONFIG.scraper.security.network.allowPrivateNetworks,\n ),\n allowedHosts: envStringArray.default(\n DEFAULT_CONFIG.scraper.security.network.allowedHosts,\n ),\n allowedCidrs: envStringArray.default(\n DEFAULT_CONFIG.scraper.security.network.allowedCidrs,\n ),\n allowInvalidTls: envBoolean.default(\n DEFAULT_CONFIG.scraper.security.network.allowInvalidTls,\n ),\n })\n .default(DEFAULT_CONFIG.scraper.security.network),\n fileAccess: z\n .object({\n mode: z\n .enum([\"disabled\", \"allowedRoots\", \"unrestricted\"])\n .default(DEFAULT_CONFIG.scraper.security.fileAccess.mode),\n allowedRoots: envStringArray.default(\n DEFAULT_CONFIG.scraper.security.fileAccess.allowedRoots,\n ),\n followSymlinks: envBoolean.default(\n DEFAULT_CONFIG.scraper.security.fileAccess.followSymlinks,\n ),\n includeHidden: envBoolean.default(\n DEFAULT_CONFIG.scraper.security.fileAccess.includeHidden,\n ),\n })\n .default(DEFAULT_CONFIG.scraper.security.fileAccess),\n })\n .default(DEFAULT_CONFIG.scraper.security),\n })\n .default(DEFAULT_CONFIG.scraper),\n splitter: z\n .object({\n minChunkSize: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.minChunkSize),\n preferredChunkSize: z.coerce\n .number()\n .int()\n .default(DEFAULT_CONFIG.splitter.preferredChunkSize),\n maxChunkSize: z.coerce.number().int().default(DEFAULT_CONFIG.splitter.maxChunkSize),\n treeSitterSizeLimit: z.coerce\n .number()\n .int()\n .default(DEFAULT_CONFIG.splitter.treeSitterSizeLimit),\n json: z\n .object({\n maxNestingDepth: z.coerce\n .number()\n .int()\n .default(DEFAULT_CONFIG.splitter.json.maxNestingDepth),\n maxChunks: z.coerce\n .number()\n .int()\n .default(DEFAULT_CONFIG.splitter.json.maxChunks),\n })\n .default(DEFAULT_CONFIG.splitter.json),\n })\n .default(DEFAULT_CONFIG.splitter),\n embeddings: z\n .object({\n batchSize: z.coerce.number().int().default(DEFAULT_CONFIG.embeddings.batchSize),\n batchChars: z.coerce.number().int().default(DEFAULT_CONFIG.embeddings.batchChars),\n requestTimeoutMs: z.coerce\n .number()\n .int()\n .default(DEFAULT_CONFIG.embeddings.requestTimeoutMs),\n initTimeoutMs: z.coerce\n .number()\n .int()\n .default(DEFAULT_CONFIG.embeddings.initTimeoutMs),\n vectorDimension: z.coerce\n .number()\n .int()\n .min(1, \"embedding dimension must be at least 1\")\n .default(DEFAULT_CONFIG.embeddings.vectorDimension),\n })\n .default(DEFAULT_CONFIG.embeddings),\n db: z\n .object({\n migrationMaxRetries: z.coerce\n .number()\n .int()\n .default(DEFAULT_CONFIG.db.migrationMaxRetries),\n migrationRetryDelayMs: z.coerce\n .number()\n .int()\n .default(DEFAULT_CONFIG.db.migrationRetryDelayMs),\n })\n .default(DEFAULT_CONFIG.db),\n search: z\n .object({\n overfetchFactor: z.coerce.number().default(DEFAULT_CONFIG.search.overfetchFactor),\n weightVec: z.coerce.number().default(DEFAULT_CONFIG.search.weightVec),\n weightFts: z.coerce.number().default(DEFAULT_CONFIG.search.weightFts),\n vectorMultiplier: z.coerce\n .number()\n .int()\n .default(DEFAULT_CONFIG.search.vectorMultiplier),\n })\n .default(DEFAULT_CONFIG.search),\n assembly: z\n .object({\n maxParentChainDepth: z.coerce\n .number()\n .int()\n .default(DEFAULT_CONFIG.assembly.maxParentChainDepth),\n childLimit: z.coerce.number().int().default(DEFAULT_CONFIG.assembly.childLimit),\n precedingSiblingsLimit: z.coerce\n .number()\n .int()\n .default(DEFAULT_CONFIG.assembly.precedingSiblingsLimit),\n subsequentSiblingsLimit: z.coerce\n .number()\n .int()\n .default(DEFAULT_CONFIG.assembly.subsequentSiblingsLimit),\n maxChunkDistance: z.coerce\n .number()\n .int()\n .min(0)\n .default(DEFAULT_CONFIG.assembly.maxChunkDistance),\n })\n .default(DEFAULT_CONFIG.assembly),\n});\n\nconst vectorDimensionExplicit = Symbol(\"vectorDimensionExplicit\");\n\ntype ParsedAppConfig = z.infer<typeof AppConfigSchema>;\n\nexport type AppConfig = Omit<ParsedAppConfig, \"embeddings\"> & {\n embeddings: ParsedAppConfig[\"embeddings\"] & {\n [vectorDimensionExplicit]?: boolean;\n };\n};\n\n// Get defaults from the schema\nexport const defaults = AppConfigSchema.parse({}) as AppConfig;\n\n// --- Mapping Configuration ---\n// Maps flat env vars and CLI args to the nested config structure\n\ninterface ConfigMapping {\n path: string[]; // Path in AppConfig\n env?: string[]; // Environment variables\n cli?: string; // CLI argument name (yargs)\n}\n\nconst configMappings: ConfigMapping[] = [\n { path: [\"server\", \"protocol\"], env: [\"DOCS_MCP_PROTOCOL\"], cli: \"protocol\" },\n { path: [\"app\", \"storePath\"], env: [\"DOCS_MCP_STORE_PATH\"], cli: \"storePath\" },\n { path: [\"app\", \"telemetryEnabled\"], env: [\"DOCS_MCP_TELEMETRY\"] }, // Handled via --no-telemetry in CLI usually\n { path: [\"app\", \"readOnly\"], env: [\"DOCS_MCP_READ_ONLY\"], cli: \"readOnly\" },\n // Ports - Special handling for shared env vars is done in mapping logic\n {\n path: [\"server\", \"ports\", \"default\"],\n env: [\"DOCS_MCP_PORT\", \"PORT\"],\n cli: \"port\",\n },\n {\n path: [\"server\", \"ports\", \"worker\"],\n env: [\"DOCS_MCP_PORT\", \"PORT\"],\n cli: \"port\",\n },\n {\n path: [\"server\", \"ports\", \"mcp\"],\n env: [\"DOCS_MCP_PORT\", \"PORT\"],\n cli: \"port\",\n },\n {\n path: [\"server\", \"ports\", \"web\"],\n env: [\"DOCS_MCP_WEB_PORT\", \"DOCS_MCP_PORT\", \"PORT\"],\n cli: \"port\",\n },\n { path: [\"server\", \"host\"], env: [\"DOCS_MCP_HOST\", \"HOST\"], cli: \"host\" },\n {\n path: [\"server\", \"publicUrl\"],\n env: [\"DOCS_MCP_SERVER_PUBLIC_URL\"],\n cli: \"publicUrl\",\n },\n {\n path: [\"server\", \"publicOrigin\"],\n env: [\"DOCS_MCP_SERVER_PUBLIC_ORIGIN\"],\n cli: \"publicOrigin\",\n },\n { path: [\"server\", \"name\"], env: [\"DOCS_MCP_SERVER_NAME\"], cli: \"serverName\" },\n { path: [\"server\", \"title\"], env: [\"DOCS_MCP_SERVER_TITLE\"], cli: \"serverTitle\" },\n {\n path: [\"server\", \"instructions\"],\n env: [\"DOCS_MCP_SERVER_INSTRUCTIONS\"],\n cli: \"serverInstructions\",\n },\n {\n path: [\"server\", \"instructionsFile\"],\n env: [\"DOCS_MCP_SERVER_INSTRUCTIONS_FILE\"],\n cli: \"serverInstructionsFile\",\n },\n {\n path: [\"app\", \"embeddingModel\"],\n env: [\"DOCS_MCP_EMBEDDING_MODEL\"],\n cli: \"embeddingModel\",\n },\n { path: [\"auth\", \"enabled\"], env: [\"DOCS_MCP_AUTH_ENABLED\"], cli: \"authEnabled\" },\n {\n path: [\"auth\", \"issuerUrl\"],\n env: [\"DOCS_MCP_AUTH_ISSUER_URL\"],\n cli: \"authIssuerUrl\",\n },\n {\n path: [\"auth\", \"audience\"],\n env: [\"DOCS_MCP_AUTH_AUDIENCE\"],\n cli: \"authAudience\",\n },\n // Add other mappings as needed for CLI/Env overrides\n];\n\n/**\n * CLI option keys (camelCase) that map onto a configuration setting.\n *\n * An option with one of these keys must not declare a yargs `default`: yargs\n * would put that value into argv even when the flag is omitted, and it would\n * then override the environment and the config file.\n *\n * @returns The mapped keys, e.g. `authEnabled`, `readOnly`, `protocol`.\n */\nexport function getConfigMappedCliKeys(): ReadonlySet<string> {\n return new Set(configMappings.flatMap((mapping) => (mapping.cli ? [mapping.cli] : [])));\n}\n\n// --- Loader Logic ---\n\nexport interface LoadConfigOptions {\n configPath?: string; // Explicit config path\n searchDir?: string; // Search directory (store path)\n}\n\n// System-specific paths\nconst systemPaths = envPaths(\"docs-mcp-server\", { suffix: \"\" });\n\nexport function loadConfig(\n cliArgs: Record<string, unknown> = {},\n options: LoadConfigOptions = {},\n): AppConfig {\n // 1. Determine Config File Path & Mode\n // Priority: CLI > Options > Env > Default System Path\n const explicitPath =\n (cliArgs.config as string) || options.configPath || process.env.DOCS_MCP_CONFIG;\n\n let configPath: string;\n let isReadOnlyConfig = false;\n\n if (explicitPath) {\n configPath = explicitPath;\n isReadOnlyConfig = true; // User provided specific config, do not overwrite\n } else {\n // Default: strict system config path\n configPath = path.join(systemPaths.config, \"config.yaml\");\n isReadOnlyConfig = false; // Auto-update default config\n }\n\n logger.debug(`Using config file: ${configPath}`);\n\n // 2. Load Config File (if exists) or use empty object\n const fileConfig = loadConfigFile(configPath) || {};\n const hasManagedVectorDimensionOmissionMarker =\n hasManagedConfigVectorDimensionOmissionMarker(configPath);\n\n // 3. Merge Defaults < File\n const baseConfig = deepMerge(defaults, fileConfig) as ConfigObject;\n\n // 4. Map Env Vars and CLI Args\n const envConfig = mapEnvToConfig();\n const cliConfig = mapCliToConfig(cliArgs);\n const vectorDimensionWasExplicit = wasVectorDimensionExplicit(\n fileConfig,\n envConfig,\n cliConfig,\n isReadOnlyConfig,\n hasManagedVectorDimensionOmissionMarker,\n );\n const fileVectorDimensionWasExplicit = wasVectorDimensionExplicit(\n fileConfig,\n {},\n {},\n isReadOnlyConfig,\n hasManagedVectorDimensionOmissionMarker,\n );\n\n // 5. Write back to file (Auto-Update) - ONLY if using default path\n if (!isReadOnlyConfig) {\n try {\n saveConfigFile(configPath, baseConfig, {\n managedDefaultConfig: true,\n omitVectorDimension: !fileVectorDimensionWasExplicit,\n });\n } catch (error) {\n logger.warn(`Failed to save config file to ${configPath}: ${error}`);\n }\n }\n\n // 6. Merge: Base < Env < CLI\n const mergedInput = deepMerge(\n baseConfig,\n deepMerge(envConfig, cliConfig),\n ) as ConfigObject;\n\n // Special handling for embedding model fallback\n if (!getAtPath(mergedInput, [\"app\", \"embeddingModel\"]) && process.env.OPENAI_API_KEY) {\n setAtPath(mergedInput, [\"app\", \"embeddingModel\"], \"text-embedding-3-small\");\n }\n\n const parseResult = AppConfigSchema.safeParse(mergedInput);\n if (parseResult.success) {\n return markVectorDimensionSource(\n parseResult.data as AppConfig,\n vectorDimensionWasExplicit,\n );\n }\n\n // Invalid public-location settings are operator errors, not a corrupted\n // file: fail loudly instead of quietly resetting to defaults below.\n for (const setting of [\"publicUrl\", \"publicOrigin\", \"allowedOrigins\"]) {\n if (hasParseIssueAtPath(parseResult.error, [\"server\", setting])) {\n throw new Error(\n `Invalid configuration for server.${setting}: ${parseResult.error.message}`,\n );\n }\n }\n\n // The file on disk is structurally wrong (e.g., array fields saved as\n // objects by a prior buggy version, or a hand-edit with a typo). Rather\n // than refusing to start, fall back to env-and-CLI-on-defaults and replace\n // the corrupted file so the next load is clean. The original file is moved\n // aside to `<configPath>.invalid-<timestamp>` so hand-edits aren't lost.\n if (!isReadOnlyConfig && fs.existsSync(configPath)) {\n const quarantinePath = `${configPath}.invalid-${Date.now()}`;\n try {\n fs.renameSync(configPath, quarantinePath);\n logger.warn(\n `Configuration file has invalid shape and was moved to ${quarantinePath}; resetting to defaults. Reason: ${parseResult.error.message}`,\n );\n } catch (renameError) {\n logger.warn(\n `Configuration file has invalid shape; resetting to defaults (could not quarantine original: ${renameError}). Reason: ${parseResult.error.message}`,\n );\n }\n } else {\n logger.warn(\n `Configuration file has invalid shape; resetting to defaults. Reason: ${parseResult.error.message}`,\n );\n }\n const fallbackInput = deepMerge(\n defaults,\n deepMerge(envConfig, cliConfig),\n ) as ConfigObject;\n if (\n !getAtPath(fallbackInput, [\"app\", \"embeddingModel\"]) &&\n process.env.OPENAI_API_KEY\n ) {\n setAtPath(fallbackInput, [\"app\", \"embeddingModel\"], \"text-embedding-3-small\");\n }\n const fallback = AppConfigSchema.parse(fallbackInput);\n const fallbackConfig = markVectorDimensionSource(\n fallback as AppConfig,\n wasVectorDimensionExplicit({}, envConfig, cliConfig, false, false),\n );\n if (!isReadOnlyConfig) {\n try {\n saveConfigFile(configPath, fallbackConfig as unknown as ConfigObject, {\n managedDefaultConfig: true,\n omitVectorDimension: true,\n });\n } catch (error) {\n logger.warn(`Failed to write fresh config file ${configPath}: ${error}`);\n }\n }\n return fallbackConfig;\n}\n\nfunction hasManagedConfigVectorDimensionOmissionMarker(filePath: string): boolean {\n if (!fs.existsSync(filePath)) return false;\n\n try {\n return fs\n .readFileSync(filePath, \"utf8\")\n .includes(managedConfigVectorDimensionOmissionMarker);\n } catch {\n return false;\n }\n}\n\n/**\n * Returns true when the embedding vector dimension was set by user config,\n * environment, or CLI rather than coming from generated defaults.\n */\nexport function isVectorDimensionExplicit(config: AppConfig): boolean {\n return config.embeddings[vectorDimensionExplicit] === true;\n}\n\n/**\n * Marks an AppConfig as having an explicit or default-derived vector dimension.\n */\nexport function markVectorDimensionSource(\n config: AppConfig,\n explicit: boolean,\n): AppConfig {\n Object.defineProperty(config.embeddings, vectorDimensionExplicit, {\n value: explicit,\n enumerable: false,\n configurable: true,\n });\n return config;\n}\n\nfunction loadConfigFile(filePath: string): Record<string, unknown> | null {\n if (!fs.existsSync(filePath)) return null;\n\n try {\n const content = fs.readFileSync(filePath, \"utf8\");\n if (filePath.endsWith(\".json\")) {\n return JSON.parse(content);\n }\n\n return yaml.parse(content) || {};\n } catch (error) {\n logger.warn(`Failed to parse config file ${filePath}: ${error}`);\n return null;\n }\n}\n\nfunction wasVectorDimensionExplicit(\n fileConfig: ConfigObject,\n envConfig: ConfigObject,\n cliConfig: ConfigObject,\n isReadOnlyConfig: boolean,\n hasManagedVectorDimensionOmissionMarker: boolean,\n): boolean {\n if (\n getAtPath(envConfig, vectorDimensionPath) !== undefined ||\n getAtPath(cliConfig, vectorDimensionPath) !== undefined\n ) {\n return true;\n }\n\n const fileValue = getAtPath(fileConfig, vectorDimensionPath);\n if (fileValue === undefined) {\n return false;\n }\n\n if (\n isReadOnlyConfig ||\n fileValue !== DEFAULT_CONFIG.embeddings.vectorDimension ||\n hasManagedVectorDimensionOmissionMarker\n ) {\n return true;\n }\n\n return !looksLikeLegacyGeneratedEmbeddingDefaults(fileConfig);\n}\n\nfunction looksLikeLegacyGeneratedEmbeddingDefaults(fileConfig: ConfigObject): boolean {\n const embeddings = fileConfig.embeddings;\n if (\n typeof embeddings !== \"object\" ||\n embeddings === null ||\n Array.isArray(embeddings)\n ) {\n return false;\n }\n\n return Object.keys(DEFAULT_CONFIG.embeddings).every((key) =>\n Object.hasOwn(embeddings, key),\n );\n}\n\ninterface SaveConfigOptions {\n managedDefaultConfig?: boolean;\n omitVectorDimension?: boolean;\n}\n\nfunction saveConfigFile(\n filePath: string,\n config: Record<string, unknown>,\n options: SaveConfigOptions = {},\n): void {\n const dir = path.dirname(filePath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n const configToWrite = cloneConfigValue(config) as ConfigObject;\n if (options.omitVectorDimension) {\n unsetAtPath(configToWrite, vectorDimensionPath);\n }\n\n let content: string;\n if (filePath.endsWith(\".json\")) {\n content = JSON.stringify(configToWrite, null, 2);\n } else {\n // Default to YAML\n content = yaml.stringify(configToWrite);\n if (options.managedDefaultConfig) {\n content = `${managedConfigHeader}${content}`;\n }\n }\n\n logger.debug(`Updating config file at ${filePath}`);\n fs.writeFileSync(filePath, content, \"utf8\");\n}\n\nfunction mapEnvToConfig(): Record<string, unknown> {\n const config: Record<string, unknown> = {};\n\n // 1. Apply explicit mappings first (for aliases like PORT, HOST)\n for (const mapping of configMappings) {\n if (mapping.env) {\n for (const envVar of mapping.env) {\n if (process.env[envVar] !== undefined) {\n setAtPath(\n config,\n mapping.path,\n normalizeEnvValue(process.env[envVar] as string),\n );\n break; // First match wins\n }\n }\n }\n }\n\n // 2. Apply auto-generated env vars (takes precedence over explicit mappings)\n for (const pathArr of ALL_CONFIG_LEAF_PATHS) {\n const envVar = pathToEnvVar(pathArr);\n if (process.env[envVar] !== undefined) {\n setAtPath(config, pathArr, normalizeEnvValue(process.env[envVar] as string));\n }\n }\n\n return config;\n}\n\nfunction mapCliToConfig(args: Record<string, unknown>): Record<string, unknown> {\n const config: Record<string, unknown> = {};\n for (const mapping of configMappings) {\n if (mapping.cli && args[mapping.cli] !== undefined) {\n setAtPath(config, mapping.path, args[mapping.cli]);\n }\n }\n return config;\n}\n\n// --- Helpers ---\n\n// Helper type for nested objects\ntype ConfigObject = Record<string, unknown>;\n\n/**\n * Convert camelCase to UPPER_SNAKE_CASE\n * Example: \"maxSize\" → \"MAX_SIZE\", \"maxNestingDepth\" → \"MAX_NESTING_DEPTH\"\n */\nfunction camelToUpperSnake(str: string): string {\n return str.replace(/([a-z])([A-Z])/g, \"$1_$2\").toUpperCase();\n}\n\n/**\n * Convert config path to environment variable name\n * Example: [\"scraper\", \"document\", \"maxSize\"] → \"DOCS_MCP_SCRAPER_DOCUMENT_MAX_SIZE\"\n */\nfunction pathToEnvVar(pathArr: string[]): string {\n return `DOCS_MCP_${pathArr.map(camelToUpperSnake).join(\"_\")}`;\n}\n\n/**\n * Recursively collect all leaf paths from a config object\n */\nfunction collectLeafPaths(obj: object, prefix: string[] = []): string[][] {\n const paths: string[][] = [];\n for (const [key, value] of Object.entries(obj)) {\n const currentPath = [...prefix, key];\n if (value !== null && typeof value === \"object\" && !Array.isArray(value)) {\n paths.push(...collectLeafPaths(value, currentPath));\n } else {\n paths.push(currentPath);\n }\n }\n return paths;\n}\n\n// Cache leaf paths at module init since DEFAULT_CONFIG is constant\nconst ALL_CONFIG_LEAF_PATHS = collectLeafPaths(DEFAULT_CONFIG);\n\nfunction setAtPath(obj: ConfigObject, pathArr: string[], value: unknown) {\n let current = obj;\n for (let i = 0; i < pathArr.length - 1; i++) {\n const key = pathArr[i];\n if (\n current[key] === undefined ||\n typeof current[key] !== \"object\" ||\n current[key] === null\n ) {\n current[key] = {};\n }\n current = current[key] as ConfigObject;\n }\n current[pathArr[pathArr.length - 1]] = value;\n}\n\nfunction getAtPath(obj: ConfigObject, pathArr: string[]): unknown {\n let current: unknown = obj;\n for (const key of pathArr) {\n if (typeof current !== \"object\" || current === null) return undefined;\n current = (current as ConfigObject)[key];\n }\n return current;\n}\n\nfunction unsetAtPath(obj: ConfigObject, pathArr: string[]): void {\n let current: unknown = obj;\n for (const key of pathArr.slice(0, -1)) {\n if (typeof current !== \"object\" || current === null) {\n return;\n }\n current = (current as ConfigObject)[key];\n }\n\n if (typeof current === \"object\" && current !== null) {\n delete (current as ConfigObject)[pathArr[pathArr.length - 1]];\n }\n}\n\nfunction cloneConfigValue(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map((item) => cloneConfigValue(item));\n }\n\n if (typeof value === \"object\" && value !== null) {\n const output: ConfigObject = {};\n for (const [key, child] of Object.entries(value)) {\n output[key] = cloneConfigValue(child);\n }\n return output;\n }\n\n return value;\n}\n\nfunction hasPath(obj: ConfigObject, pathArr: string[]): boolean {\n let current: unknown = obj;\n for (const key of pathArr) {\n if (typeof current !== \"object\" || current === null || !Object.hasOwn(current, key)) {\n return false;\n }\n current = (current as ConfigObject)[key];\n }\n return true;\n}\nfunction hasParseIssueAtPath(error: z.ZodError, pathArr: string[]): boolean {\n return error.issues.some((issue) => issue.path.join(\".\") === pathArr.join(\".\"));\n}\n\nfunction deepMerge(target: unknown, source: unknown): unknown {\n if (typeof target !== \"object\" || target === null) return source;\n if (typeof source !== \"object\" || source === null) return target;\n // Arrays are scalars from a merge standpoint: source replaces target entirely.\n // Recursing into arrays would either splice into a wrong shape (spreading an\n // array into a plain object) or silently union by index, neither of which\n // matches user expectations for list-shaped config values.\n if (Array.isArray(target) || Array.isArray(source)) return source;\n\n const t = target as ConfigObject;\n const s = source as ConfigObject;\n const output = { ...t };\n\n for (const key of Object.keys(s)) {\n const sValue = s[key];\n const tValue = t[key];\n\n if (\n typeof sValue === \"object\" &&\n sValue !== null &&\n !Array.isArray(sValue) &&\n typeof tValue === \"object\" &&\n tValue !== null &&\n !Array.isArray(tValue) &&\n key in t\n ) {\n output[key] = deepMerge(tValue, sValue);\n } else {\n output[key] = sValue;\n }\n }\n return output;\n}\n\n// --- CLI Helper Functions ---\n\n/**\n * Check if a config path is valid by verifying it exists in DEFAULT_CONFIG\n */\nexport function isValidConfigPath(path: string): boolean {\n const pathArr = path.split(\".\");\n return hasPath(DEFAULT_CONFIG as ConfigObject, pathArr);\n}\n\n/**\n * Get a config value by dot-separated path\n */\nexport function getConfigValue(config: AppConfig, path: string): unknown {\n const pathArr = path.split(\".\");\n return getAtPath(config as unknown as ConfigObject, pathArr);\n}\n\n/**\n * Parse a string value to the appropriate type (number, boolean, or string)\n */\nexport function parseConfigValue(value: string): unknown {\n // Try number first\n const num = Number(value);\n if (!Number.isNaN(num) && value.trim() !== \"\") {\n return num;\n }\n\n // Try boolean\n const lower = value.toLowerCase();\n if (lower === \"true\") return true;\n if (lower === \"false\") return false;\n\n // Default to string\n return value;\n}\n\n/**\n * Set a config value and persist to file.\n * Returns the path to the config file that was updated.\n * Validates the updated config against the schema before saving.\n */\nexport function setConfigValue(path: string, value: string): string {\n const configPath = getDefaultConfigPath();\n const fileConfig = loadConfigFile(configPath) || {};\n const pathArr = path.split(\".\");\n const parsedValue = parseConfigValue(value);\n\n // Apply change to a copy so we can validate before persisting\n const updatedConfig = JSON.parse(JSON.stringify(fileConfig));\n setAtPath(updatedConfig, pathArr, parsedValue);\n\n // Validate against schema before saving\n try {\n AppConfigSchema.parse(updatedConfig);\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n throw new Error(`Invalid config value for \"${path}\": ${errorMsg}`);\n }\n\n saveConfigFile(configPath, updatedConfig);\n\n return configPath;\n}\n\n/**\n * Get the default system config path\n */\nexport function getDefaultConfigPath(): string {\n return path.join(systemPaths.config, \"config.yaml\");\n}\n","/**\n * Relays a remote worker's events onto the local {@link EventBusService}, so\n * code that listens on the bus sees the worker's jobs as it would see jobs it\n * runs itself.\n */\n\nimport type { Unsubscribable } from \"@trpc/server/observable\";\nimport type { ApiClient } from \"../services/apiClient\";\nimport { logger } from \"../utils/logger\";\nimport type { EventBusService } from \"./EventBusService\";\nimport { EventType } from \"./types\";\n\n/** First delay before subscribing again after the subscription itself ended. */\nconst RESUBSCRIBE_BASE_DELAY_MS = 1000;\n\n/** Longest delay between attempts to subscribe again. */\nconst RESUBSCRIBE_MAX_DELAY_MS = 30_000;\n\n/**\n * Keeps one subscription to the worker's `events.subscribe` on a shared API\n * client and re-emits every event locally.\n *\n * A dropped connection is reconnected and resubscribed by the client's\n * WebSocket; a subscription that ends with an error or is stopped by the worker\n * is subscribed again here, with backoff. When the stream becomes live again\n * after having been live, the relay emits `JOB_LIST_CHANGE` and\n * `LIBRARY_CHANGE` locally, so views refetch what they missed while it was down.\n */\nexport class RemoteEventProxy {\n private subscription: Unsubscribable | null = null;\n /** Identifies the current subscription, so callbacks from an ended one are ignored. */\n private generation = 0;\n private live = false;\n private wasLive = false;\n private stopped = true;\n private attempts = 0;\n private retryTimer: ReturnType<typeof setTimeout> | undefined;\n private pending: { promise: Promise<boolean>; settle: (live: boolean) => void } | null =\n null;\n\n /**\n * @param api The worker's API client; it must have been created with subscriptions.\n * @param eventBus The local bus to re-emit the worker's events on.\n */\n constructor(\n private readonly api: ApiClient,\n private readonly eventBus: EventBusService,\n ) {}\n\n /**\n * Starts the subscription if it is not running and waits until it is live.\n * Calls made while an earlier call still waits share its result.\n *\n * @param timeoutMs How long to wait for the subscription to become live.\n * @returns `true` once the subscription is live; `false` when the connection\n * fails or nothing is live within `timeoutMs`. Never rejects; the relay\n * keeps trying in the background.\n */\n connect(timeoutMs: number): Promise<boolean> {\n if (this.stopped) {\n this.stopped = false;\n this.subscribe();\n }\n if (this.live) {\n return Promise.resolve(true);\n }\n if (!this.pending) {\n let settle: (live: boolean) => void = () => {};\n const promise = new Promise<boolean>((resolve) => {\n const timer = setTimeout(() => settle(false), timeoutMs);\n settle = (live) => {\n clearTimeout(timer);\n this.pending = null;\n resolve(live);\n };\n });\n this.pending = { promise, settle };\n }\n return this.pending.promise;\n }\n\n /** Ends the subscription and stops trying to subscribe again. */\n disconnect(): void {\n this.stopped = true;\n clearTimeout(this.retryTimer);\n this.retryTimer = undefined;\n this.endSubscription();\n this.live = false;\n this.pending?.settle(false);\n }\n\n /** Whether the worker's events currently reach the local bus. */\n isActive(): boolean {\n return this.live;\n }\n\n private subscribe(): void {\n const generation = ++this.generation;\n // disconnect() and resubscribeLater() move the generation on\n const current = () => generation === this.generation;\n this.subscription = this.api.events.subscribe.subscribe(undefined, {\n onStarted: () => {\n if (current()) this.setLive(true);\n },\n onData: (event) => {\n if (current()) this.eventBus.emit(event.type, event.payload as never);\n },\n onConnectionStateChange: (state) => {\n if (!current() || state.state !== \"connecting\") return;\n this.setLive(false);\n // A refused or failed connection will not turn live soon; stop waiting\n if (state.error) this.pending?.settle(false);\n },\n onError: (error) => {\n if (!current()) return;\n logger.debug(`Worker event subscription failed: ${error.message}`);\n this.resubscribeLater();\n },\n onStopped: () => {\n if (current()) this.resubscribeLater();\n },\n onComplete: () => {\n if (current()) this.resubscribeLater();\n },\n });\n }\n\n private resubscribeLater(): void {\n this.setLive(false);\n this.endSubscription();\n\n const delay = Math.min(\n RESUBSCRIBE_BASE_DELAY_MS * 2 ** this.attempts,\n RESUBSCRIBE_MAX_DELAY_MS,\n );\n this.attempts++;\n // disconnect() clears this timer\n this.retryTimer = setTimeout(() => {\n this.retryTimer = undefined;\n this.subscribe();\n }, delay);\n // A pending retry alone must not keep a finished CLI process alive.\n this.retryTimer.unref?.();\n }\n\n /** Ends the current subscription; its later callbacks are ignored. */\n private endSubscription(): void {\n this.generation++;\n this.subscription?.unsubscribe();\n this.subscription = null;\n }\n\n private setLive(live: boolean): void {\n if (live === this.live) return;\n this.live = live;\n if (!live) {\n if (this.wasLive) {\n logger.warn(\"⚠️ Lost live job updates from the worker; reconnecting\");\n }\n return;\n }\n\n this.attempts = 0;\n this.pending?.settle(true);\n if (this.wasLive) {\n logger.info(\"🔗 Live job updates from the worker are back\");\n // Events sent while the stream was down are lost; have views refetch.\n this.eventBus.emit(EventType.JOB_LIST_CHANGE, undefined);\n this.eventBus.emit(EventType.LIBRARY_CHANGE, undefined);\n } else {\n logger.debug(\"Subscribed to the worker's events\");\n }\n this.wasLive = true;\n }\n}\n","import type { ScraperOptions } from \"../../scraper/types\";\nimport type { ExistingTargetPolicy } from \"../../store/types\";\nimport type { PipelineJob, PipelineJobStatus } from \"../types\";\n\n/**\n * The tRPC codes the pipeline router gives enqueue errors a caller can act on:\n * an existing target (409), an invalid library name (400) and an unknown\n * refresh target (404). `PipelineClient` relays exactly these from a remote\n * worker; any other failure keeps its generic wrapping.\n */\nexport const RELAYED_ENQUEUE_ERROR_CODES = [\n \"CONFLICT\",\n \"BAD_REQUEST\",\n \"NOT_FOUND\",\n] as const;\n\n/** One of {@link RELAYED_ENQUEUE_ERROR_CODES}. */\nexport type RelayedEnqueueErrorCode = (typeof RELAYED_ENQUEUE_ERROR_CODES)[number];\n\n/**\n * Per-request options for enqueueing a scrape job. Deliberately separate from\n * `ScraperOptions`, which is persisted and replayed: an intent stored there would\n * leak into re-index forms and recovery.\n */\nexport interface EnqueueScrapeOptions {\n /** What to do when the target library or version already exists. Defaults to `\"reject-version\"`. */\n onExisting?: ExistingTargetPolicy;\n}\n\n/**\n * Common interface that both PipelineManager and PipelineClient implement.\n * Uses public PipelineJob interface for API consistency across implementations.\n * Starting and stopping belongs to whoever created the pipeline (see `openBackend`).\n */\nexport interface IPipeline {\n /**\n * Enqueues a scrape job.\n * @throws {LibraryAlreadyExistsError | VersionAlreadyExistsError} When the target exists and\n * the policy rejects it (a `TRPCError` with code `CONFLICT` through `PipelineClient`).\n * @throws {InvalidLibraryNameError} When a new library's name fails validation (`BAD_REQUEST`).\n */\n enqueueScrapeJob(\n library: string,\n version: string | undefined | null,\n options: ScraperOptions,\n enqueue?: EnqueueScrapeOptions,\n ): Promise<string>;\n enqueueRefreshJob(\n library: string,\n version: string | undefined | null,\n options?: Pick<ScraperOptions, \"preserveHashes\">,\n ): Promise<string>;\n getJob(jobId: string): Promise<PipelineJob | undefined>;\n getJobs(status?: PipelineJobStatus): Promise<PipelineJob[]>;\n cancelJob(jobId: string): Promise<void>;\n clearCompletedJobs(): Promise<number>;\n waitForJobCompletion(jobId: string): Promise<void>;\n /**\n * Removes a library version: cancels its unfinished jobs, waits until each\n * has ended (one already being cancelled can still be storing a page), then\n * removes the version, and the library with its last version. A job enqueued for the same version meanwhile is registered\n * only after the removal is done, so it cannot slip in between.\n */\n removeVersion(library: string, version: string | undefined | null): Promise<void>;\n}\n","/**\n * Pipeline backed by a remote worker: every operation calls the worker's\n * application API through a shared {@link ApiClient}.\n */\n\nimport { TRPCError } from \"@trpc/server\";\nimport type { EventBusService } from \"../events/EventBusService\";\nimport type { RemoteEventProxy } from \"../events/RemoteEventProxy\";\nimport { EventType } from \"../events/types\";\nimport type { ScraperOptions } from \"../scraper/types\";\nimport type { ApiClient } from \"../services/apiClient\";\nimport { normalizeVersionLabel } from \"../store/types\";\nimport { logger } from \"../utils/logger\";\nimport {\n type EnqueueScrapeOptions,\n type IPipeline,\n RELAYED_ENQUEUE_ERROR_CODES,\n type RelayedEnqueueErrorCode,\n} from \"./trpc/interfaces\";\nimport { type PipelineJob, PipelineJobStatus } from \"./types\";\n\n/**\n * How long submitting the first job waits for the worker's event stream, so the\n * job's first events reach this process.\n */\nexport const EVENTS_CONNECT_TIMEOUT_MS = 5000;\n\n/**\n * How often `waitForJobCompletion` asks the worker for the job's state while\n * the worker's events reach this process. The lookup only catches an event lost\n * around a reconnect.\n */\nconst JOB_SAFETY_LOOKUP_INTERVAL_MS = 10_000;\n\n/** How often `waitForJobCompletion` asks while the worker's events do not arrive. */\nconst JOB_POLL_INTERVAL_MS = 1000;\n\n/** How long job lookups may keep failing before `waitForJobCompletion` gives up. */\nconst JOB_LOOKUP_GIVE_UP_MS = 30_000;\n\n/**\n * Re-raises a worker's enqueue error as a `TRPCError` with the same code and\n * message, so this process's own router relays it unchanged (the web UI then\n * sees the same 409/400/404 as in front of a local pipeline). The worker's router\n * already decided which errors a caller can act on; anything it left as an\n * internal error, or a failure that never reached it, is wrapped as a plain\n * error prefixed with `failure`.\n *\n * @returns The error to rethrow.\n */\nfunction toEnqueueError(error: unknown, failure: string): Error {\n const message = error instanceof Error ? error.message : String(error);\n const code = (error as { data?: { code?: unknown } } | null)?.data?.code;\n return RELAYED_ENQUEUE_ERROR_CODES.includes(code as RelayedEnqueueErrorCode)\n ? new TRPCError({ code: code as RelayedEnqueueErrorCode, message, cause: error })\n : new Error(`${failure}: ${message}`);\n}\n\n/**\n * Implements {@link IPipeline} by delegating every operation to a remote worker.\n */\nexport class PipelineClient implements IPipeline {\n /**\n * @param client The worker's API client. Whoever created it closes it.\n * @param eventBus The local bus that the worker's relayed job events arrive on.\n * @param relay The relay that brings those events; whoever created it disconnects it.\n */\n constructor(\n private readonly client: ApiClient,\n private readonly eventBus: EventBusService,\n private readonly relay: RemoteEventProxy,\n ) {}\n\n /** The first job submission's wait for the event stream, shared by later ones. */\n private eventsReady: Promise<void> | undefined;\n\n /**\n * Waits, once, for the worker's event stream before the first job is\n * submitted, so a job that starts at once does not lose its first events.\n * When the stream is not live in time, warns once and lets jobs go ahead;\n * waits then rely on asking the worker.\n */\n private waitForEvents(): Promise<void> {\n this.eventsReady ??= this.relay.connect(EVENTS_CONNECT_TIMEOUT_MS).then((live) => {\n if (!live) {\n logger.warn(\n \"⚠️ Live job updates from the worker are unavailable; progress is not shown and waits check the job's state instead\",\n );\n }\n });\n return this.eventsReady;\n }\n\n async enqueueScrapeJob(\n library: string,\n version: string | undefined | null,\n options: ScraperOptions,\n enqueue?: EnqueueScrapeOptions,\n ): Promise<string> {\n await this.waitForEvents();\n try {\n const normalizedVersion = normalizeVersionLabel(version) || null;\n const result = await this.client.enqueueScrapeJob.mutate({\n library,\n version: normalizedVersion,\n options,\n onExisting: enqueue?.onExisting,\n });\n logger.debug(`Job ${result.jobId} enqueued successfully`);\n return result.jobId;\n } catch (error) {\n throw toEnqueueError(error, \"Failed to enqueue job\");\n }\n }\n\n async enqueueRefreshJob(\n library: string,\n version: string | undefined | null,\n options?: { preserveHashes?: boolean },\n ): Promise<string> {\n await this.waitForEvents();\n try {\n const normalizedVersion = normalizeVersionLabel(version) || null;\n const result = await this.client.enqueueRefreshJob.mutate({\n library,\n version: normalizedVersion,\n options,\n });\n logger.debug(`Refresh job ${result.jobId} enqueued successfully`);\n return result.jobId;\n } catch (error) {\n throw toEnqueueError(error, \"Failed to enqueue refresh job\");\n }\n }\n\n async getJob(jobId: string, signal?: AbortSignal): Promise<PipelineJob | undefined> {\n try {\n // superjson automatically deserializes Date objects\n return await this.client.getJob.query({ id: jobId }, { signal });\n } catch (error) {\n throw new Error(\n `Failed to get job ${jobId}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n async getJobs(status?: PipelineJobStatus): Promise<PipelineJob[]> {\n try {\n // superjson automatically deserializes Date objects\n const result = await this.client.getJobs.query({ status });\n return result.jobs || [];\n } catch (error) {\n logger.error(`❌ Failed to get jobs from external worker: ${error}`);\n throw error;\n }\n }\n\n async cancelJob(jobId: string): Promise<void> {\n try {\n await this.client.cancelJob.mutate({ id: jobId });\n logger.debug(`Job cancelled via external worker: ${jobId}`);\n } catch (error) {\n logger.error(`❌ Failed to cancel job ${jobId} via external worker: ${error}`);\n throw error;\n }\n }\n\n async clearCompletedJobs(): Promise<number> {\n try {\n const result = await this.client.clearCompletedJobs.mutate();\n logger.debug(`Cleared ${result.count} completed jobs via external worker`);\n return result.count || 0;\n } catch (error) {\n logger.error(`❌ Failed to clear completed jobs via external worker: ${error}`);\n throw error;\n }\n }\n\n /**\n * Waits until the worker reports the job as completed, failed, or cancelled.\n * Like `PipelineManager.waitForJobCompletion`, it resolves for completed and\n * cancelled jobs and rejects for failed ones.\n *\n * The relayed status events settle the wait. It also asks the worker for the\n * job right away, which covers a job that finished before the wait began,\n * and then again: every few seconds while events arrive, to catch one lost\n * around a reconnect, and every second while they do not.\n *\n * @param jobId The job to wait for.\n * @throws Error if the job failed, the worker does not know it, or the worker\n * stays unreachable beyond a bounded period.\n */\n async waitForJobCompletion(jobId: string): Promise<void> {\n return new Promise((resolve, reject) => {\n let settled = false;\n let pollTimer: ReturnType<typeof setTimeout> | undefined;\n let lastAnswerAt = Date.now();\n\n const finish = (error?: Error) => {\n if (settled) {\n return;\n }\n settled = true;\n unsubscribe();\n clearTimeout(pollTimer);\n if (error) {\n reject(error);\n } else {\n resolve();\n }\n };\n\n const settleIfDone = (\n job: Pick<PipelineJob, \"status\" | \"error\" | \"errorMessage\">,\n ) => {\n switch (job.status) {\n case PipelineJobStatus.COMPLETED:\n case PipelineJobStatus.CANCELLED:\n finish();\n break;\n case PipelineJobStatus.FAILED:\n // The worker emits the FAILED status before it sets `error`, so a\n // relayed event carries the text only in `errorMessage`\n finish(\n new Error(job.error?.message || job.errorMessage || `Job ${jobId} failed`),\n );\n break;\n }\n };\n\n const unsubscribe = this.eventBus.on(EventType.JOB_STATUS_CHANGE, (job) => {\n if (job.id === jobId) {\n settleIfDone(job);\n }\n });\n\n // A lookup the worker never answers fails when the give-up window ends,\n // so a stalled request cannot keep the wait open\n const lookUp = async () => {\n const deadline = new AbortController();\n const timer = setTimeout(\n () => deadline.abort(),\n lastAnswerAt + JOB_LOOKUP_GIVE_UP_MS - Date.now(),\n );\n try {\n return await this.getJob(jobId, deadline.signal);\n } catch (error) {\n throw deadline.signal.aborted\n ? new Error(\n `Failed to get job ${jobId}: the worker did not answer for ${JOB_LOOKUP_GIVE_UP_MS / 1000} s`,\n )\n : error;\n } finally {\n clearTimeout(timer);\n }\n };\n\n const poll = async () => {\n try {\n const job = await lookUp();\n lastAnswerAt = Date.now();\n if (!job) {\n // Clearing finished jobs or restarting the worker drops the record\n finish(\n new Error(\n `Job not found: ${jobId}. The worker no longer knows it; it may have been cleared or the worker restarted.`,\n ),\n );\n return;\n }\n settleIfDone(job);\n } catch (error) {\n // getJob only throws Error instances\n if (Date.now() - lastAnswerAt >= JOB_LOOKUP_GIVE_UP_MS) {\n finish(error as Error);\n return;\n }\n logger.debug(`Job lookup for ${jobId} failed: ${error}`);\n }\n if (!settled) {\n const interval = this.relay.isActive()\n ? JOB_SAFETY_LOOKUP_INTERVAL_MS\n : JOB_POLL_INTERVAL_MS;\n pollTimer = setTimeout(poll, interval);\n }\n };\n\n void poll();\n });\n }\n\n /** Removes the version on the worker, which cancels its own job for it first. */\n async removeVersion(\n library: string,\n version: string | undefined | null,\n ): Promise<void> {\n await this.client.removeDocs.mutate({ library, version: version ?? null });\n }\n}\n","class ScraperError extends Error {\n constructor(\n message: string,\n public readonly isRetryable: boolean = false,\n public readonly cause?: Error,\n ) {\n super(message);\n this.name = this.constructor.name;\n if (cause?.stack) {\n this.stack = `${this.stack}\\nCaused by: ${cause.stack}`;\n }\n }\n}\n\nclass InvalidUrlError extends ScraperError {\n constructor(url: string, cause?: Error) {\n super(`Invalid URL: ${url}`, false, cause);\n }\n}\n\nclass RedirectError extends ScraperError {\n constructor(\n public readonly originalUrl: string,\n public readonly redirectUrl: string,\n public readonly statusCode: number,\n ) {\n super(\n `Redirect detected from ${originalUrl} to ${redirectUrl} (status: ${statusCode})`,\n false,\n );\n }\n}\n\n/** A bot-protection challenge answered the request in place of the page. */\nclass ChallengeError extends ScraperError {\n /**\n * @param url The URL that was requested.\n * @param statusCode The status the challenge was served with.\n * @param challengeType The kind of challenge, such as \"cloudflare\".\n * @param responseUrl The URL whose response carried the challenge, which a\n * redirect may have moved to another host.\n */\n constructor(\n public readonly url: string,\n public readonly statusCode: number,\n public readonly challengeType: string,\n public readonly responseUrl: string = url,\n ) {\n super(\n `Challenge detected for ${url} (status: ${statusCode}, type: ${challengeType}): the site answered with a bot check instead of the page`,\n false,\n );\n }\n}\n\nclass TlsCertificateError extends ScraperError {\n constructor(\n public readonly url: string,\n public readonly code?: string,\n cause?: Error,\n ) {\n super(\n `TLS certificate validation failed for ${url}${\n code ? ` (${code})` : \"\"\n }. The remote site may have an incomplete or untrusted certificate chain.`,\n false,\n cause,\n );\n }\n}\n\n/** An HTTP fetch that failed with a response, carrying that response's status. */\nclass HttpStatusError extends ScraperError {\n /**\n * @param message Describes the failure.\n * @param isRetryable Whether a later attempt may succeed.\n * @param statusCode The response's status.\n * @param cause The underlying error.\n * @param responseUrl The URL that answered with the status, when known; a\n * redirect may have moved it to another host.\n */\n constructor(\n message: string,\n isRetryable: boolean,\n public readonly statusCode: number,\n cause?: Error,\n public readonly responseUrl?: string,\n ) {\n super(message, isRetryable, cause);\n }\n}\n\nclass AccessPolicyError extends ScraperError {\n constructor(message: string) {\n super(message, false);\n }\n}\n\n/**\n * Returns the first line of a thrown value's message.\n *\n * Playwright's messages run on with call logs and install hints; the first line\n * names the failure.\n *\n * @param error The thrown value.\n * @returns The first line, or the whole message when that line is empty.\n */\nfunction firstErrorLine(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n return message.split(\"\\n\")[0] || message;\n}\n\n/** A page that had to be rendered in the browser could not be. */\nclass RenderError extends ScraperError {\n constructor(\n public readonly url: string,\n cause: Error,\n ) {\n super(`Playwright could not render ${url}: ${firstErrorLine(cause)}`, false, cause);\n }\n}\n\nexport {\n AccessPolicyError,\n ChallengeError,\n firstErrorLine,\n HttpStatusError,\n InvalidUrlError,\n RedirectError,\n RenderError,\n ScraperError,\n TlsCertificateError,\n};\n","import mime from \"mime\";\n\n/**\n * Represents a parsed Content-Type header.\n */\nexport interface ParsedContentType {\n mimeType: string;\n charset?: string;\n}\n\n/**\n * Extension-to-MIME overrides for types the `mime` package gets wrong or does\n * not know. See openspec/changes/refactor-mime-type-detection/design.md.\n *\n * Module-level: `detectMimeTypeFromPath` runs once per discovered link, and\n * rebuilding this per call allocated the whole table to do one lookup.\n */\nconst CUSTOM_MIME_TYPES: Record<string, string> = {\n // JavaScript/TypeScript family\n ts: \"text/x-typescript\",\n tsx: \"text/x-tsx\",\n mts: \"text/x-typescript\", // TypeScript ES modules\n cts: \"text/x-typescript\", // TypeScript CommonJS modules\n js: \"text/javascript\",\n jsx: \"text/x-jsx\",\n cjs: \"text/javascript\", // CommonJS modules\n mjs: \"text/javascript\", // ES modules\n\n // Python family\n py: \"text/x-python\",\n pyw: \"text/x-python\",\n pyi: \"text/x-python\",\n pyx: \"text/x-cython\", // Cython\n pxd: \"text/x-cython\", // Cython\n\n // Systems languages\n go: \"text/x-go\",\n rs: \"text/x-rust\",\n c: \"text/x-csrc\",\n h: \"text/x-chdr\",\n cpp: \"text/x-c++src\",\n cxx: \"text/x-c++src\",\n cc: \"text/x-c++src\",\n hpp: \"text/x-c++hdr\",\n hxx: \"text/x-c++hdr\",\n zig: \"text/x-zig\",\n nim: \"text/x-nim\",\n v: \"text/x-v\",\n cr: \"text/x-crystal\",\n\n // JVM languages\n kt: \"text/x-kotlin\",\n kts: \"text/x-kotlin\", // Kotlin script\n scala: \"text/x-scala\",\n groovy: \"text/x-groovy\",\n gradle: \"text/x-gradle\",\n\n // Apple/Mobile\n swift: \"text/x-swift\",\n dart: \"text/x-dart\",\n\n // Scripting languages\n rb: \"text/x-ruby\",\n rake: \"text/x-ruby\", // Rakefile\n php: \"text/x-php\",\n lua: \"text/x-lua\",\n pl: \"text/x-perl\",\n pm: \"text/x-perl\",\n r: \"text/x-r\", // Also handles .R since extension is lowercased\n\n // Functional languages\n hs: \"text/x-haskell\",\n lhs: \"text/x-haskell\", // Literate Haskell\n elm: \"text/x-elm\",\n erl: \"text/x-erlang\",\n ex: \"text/x-elixir\",\n exs: \"text/x-elixir\",\n clj: \"text/x-clojure\",\n cljs: \"text/x-clojure\",\n cljc: \"text/x-clojure\",\n scm: \"text/x-scheme\", // mime package: application/vnd.lotus-screencam\n ss: \"text/x-scheme\",\n tcl: \"text/x-tcl\", // mime package: application/x-tcl\n jl: \"text/x-julia\",\n\n // .NET\n cs: \"text/x-csharp\",\n\n // Web3/Smart contracts\n sol: \"text/x-solidity\",\n move: \"text/x-move\",\n cairo: \"text/x-cairo\",\n\n // Modern web frameworks\n vue: \"text/x-vue\",\n svelte: \"text/x-svelte\",\n astro: \"text/x-astro\",\n\n // Shell scripting\n sh: \"text/x-shellscript\",\n bash: \"text/x-shellscript\",\n zsh: \"text/x-shellscript\",\n fish: \"text/x-shellscript\",\n csh: \"text/x-shellscript\", // mime package: application/x-csh\n tcsh: \"text/x-shellscript\",\n ksh: \"text/x-shellscript\",\n ps1: \"text/x-powershell\",\n bat: \"text/x-batch\", // mime package: application/x-msdownload\n cmd: \"text/x-batch\",\n\n // Documentation formats\n markdown: \"text/markdown\",\n mdx: \"text/mdx\",\n gfm: \"text/x-gfm\",\n mkd: \"text/markdown\",\n mkdn: \"text/markdown\",\n mkdown: \"text/markdown\",\n mdown: \"text/markdown\",\n mdwn: \"text/markdown\",\n ronn: \"text/markdown\",\n rst: \"text/x-rst\", // reStructuredText\n adoc: \"text/x-asciidoc\",\n asciidoc: \"text/x-asciidoc\",\n textile: \"text/x-textile\",\n org: \"text/x-org\", // Org-mode\n pod: \"text/x-pod\", // Perl documentation\n rdoc: \"text/x-rdoc\", // Ruby documentation\n wiki: \"text/x-wiki\",\n rmd: \"text/x-rmarkdown\", // R Markdown\n\n // Configuration files\n toml: \"text/x-toml\",\n ini: \"text/x-ini\",\n cfg: \"text/x-ini\",\n conf: \"text/x-conf\",\n properties: \"text/x-properties\",\n env: \"text/x-dotenv\",\n\n // Build systems\n dockerfile: \"text/x-dockerfile\",\n containerfile: \"text/x-dockerfile\",\n makefile: \"text/x-makefile\",\n cmake: \"text/x-cmake\",\n bazel: \"text/x-bazel\",\n bzl: \"text/x-bazel\",\n buck: \"text/x-buck\",\n\n // Infrastructure as Code\n tf: \"text/x-terraform\",\n tfvars: \"text/x-terraform\",\n hcl: \"text/x-hcl\",\n\n // Data/Query languages\n sql: \"text/x-sql\",\n graphql: \"text/x-graphql\",\n gql: \"text/x-graphql\",\n\n // Schema/API definitions\n proto: \"text/x-proto\",\n prisma: \"text/x-prisma\",\n thrift: \"text/x-thrift\",\n avro: \"text/x-avro\",\n\n // TeX/LaTeX\n tex: \"text/x-tex\",\n latex: \"text/x-latex\",\n\n // Document formats (ensure correct detection for DocumentPipeline)\n doc: \"application/msword\",\n xls: \"application/vnd.ms-excel\",\n ppt: \"application/vnd.ms-powerpoint\",\n odt: \"application/vnd.oasis.opendocument.text\",\n ods: \"application/vnd.oasis.opendocument.spreadsheet\",\n odp: \"application/vnd.oasis.opendocument.presentation\",\n rtf: \"application/rtf\",\n epub: \"application/epub+zip\",\n fb2: \"application/x-fictionbook+xml\",\n};\n\n/**\n * Corrections for MIME types arriving from outside — chiefly HTTP\n * `Content-Type` headers. Extensions are matched against\n * {@link CUSTOM_MIME_TYPES} first, so these mostly cover external sources.\n */\nconst MIME_TYPE_NORMALIZATION: Record<string, string> = {\n \"application/node\": \"text/javascript\", // .cjs files\n \"video/mp2t\": \"text/x-typescript\", // .ts/.mts files (MPEG-2 transport stream conflict)\n \"application/rls-services+xml\": \"text/x-rust\", // .rs files\n \"application/vnd.lotus-organizer\": \"text/x-org\", // .org files (Lotus Organizer conflict)\n \"application/vnd.dart\": \"text/x-dart\", // .dart files\n \"application/x-perl\": \"text/x-perl\", // .pl/.pm files\n \"application/x-tex\": \"text/x-tex\", // .tex files\n \"application/x-latex\": \"text/x-latex\", // .latex files\n \"application/toml\": \"text/x-toml\", // .toml files\n \"application/x-csh\": \"text/x-shellscript\", // .csh/.tcsh files\n \"application/x-tcl\": \"text/x-tcl\", // .tcl files\n \"application/vnd.lotus-screencam\": \"text/x-scheme\", // .scm files (Lotus ScreenCam conflict)\n \"application/x-msdownload\": \"text/x-batch\", // .bat/.cmd files\n};\n\n/**\n * Enhanced MIME type detection and utility functions.\n * Combines standard MIME type operations with enhanced source code detection.\n */\n// biome-ignore lint/complexity/noStaticOnlyClass: helpers are static\nexport class MimeTypeUtils {\n /**\n * Parses a Content-Type header string into its MIME type and charset.\n * @param contentTypeHeader The Content-Type header string (e.g., \"text/html; charset=utf-8\").\n * @returns A ParsedContentType object, or a default if parsing fails.\n */\n public static parseContentType(contentTypeHeader?: string | null): ParsedContentType {\n if (!contentTypeHeader) {\n return { mimeType: \"application/octet-stream\" };\n }\n const parts = contentTypeHeader.split(\";\").map((part) => part.trim());\n // Normalized for the same reason path detection is: the `mime` package's\n // misfilings also arrive from servers, and a header saying\n // `application/x-tcl` describes a text script just as a `.tcl` path does.\n const raw = parts[0].toLowerCase();\n const mimeType = MimeTypeUtils.normalizeMimeType(raw) ?? raw;\n let charset: string | undefined;\n\n for (let i = 1; i < parts.length; i++) {\n const param = parts[i];\n if (param.toLowerCase().startsWith(\"charset=\")) {\n charset = param.substring(\"charset=\".length).toLowerCase();\n break;\n }\n }\n return { mimeType, charset };\n }\n\n /**\n * Checks if a MIME type represents HTML content.\n */\n public static isHtml(mimeType: string): boolean {\n return mimeType === \"text/html\" || mimeType === \"application/xhtml+xml\";\n }\n\n /**\n * Checks if a MIME type represents Markdown content.\n */\n public static isMarkdown(mimeType: string): boolean {\n return (\n mimeType === \"text/markdown\" ||\n mimeType === \"text/x-markdown\" ||\n mimeType === \"text/mdx\" ||\n mimeType === \"text/x-gfm\"\n );\n }\n\n /**\n * Checks if a MIME type represents plain text content.\n * This includes basic text/* types but excludes structured formats like JSON, XML, etc.\n */\n public static isText(mimeType: string): boolean {\n if (!mimeType) {\n return false;\n }\n\n const normalizedMimeType = mimeType.toLowerCase();\n\n // Accept basic text/* types, but exclude structured formats that have specific pipelines\n if (normalizedMimeType.startsWith(\"text/\")) {\n // Exclude structured text formats that should go to specific pipelines\n if (\n MimeTypeUtils.isJson(normalizedMimeType) ||\n MimeTypeUtils.isMarkdown(normalizedMimeType)\n ) {\n return false;\n }\n return true;\n }\n\n return false;\n }\n\n /**\n * Checks if a MIME type represents content that is safe for text processing.\n * This includes all text/* types and specific application types that are text-based.\n * Used by TextPipeline as a fallback for content that other pipelines don't handle.\n */\n public static isSafeForTextProcessing(mimeType: string): boolean {\n if (!mimeType) {\n return false;\n }\n\n const normalizedMimeType = mimeType.toLowerCase();\n\n // Accept all text/* types\n if (normalizedMimeType.startsWith(\"text/\")) {\n return true;\n }\n\n // Accept JSON content (when not handled by JsonPipeline)\n if (MimeTypeUtils.isJson(normalizedMimeType)) {\n return true;\n }\n\n // Accept source code types (when not handled by SourceCodePipeline)\n if (MimeTypeUtils.isSourceCode(normalizedMimeType)) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Checks if a MIME type represents JSON content.\n */\n public static isJson(mimeType: string): boolean {\n return (\n mimeType === \"application/json\" ||\n mimeType === \"text/json\" ||\n mimeType === \"text/x-json\"\n );\n }\n\n /**\n * Checks if a MIME type represents PDF content.\n */\n public static isPdf(mimeType: string): boolean {\n return mimeType === \"application/pdf\";\n }\n\n /**\n * Checks if a MIME type represents a modern Office document (DOCX, XLSX, PPTX).\n */\n public static isOfficeDocument(mimeType: string): boolean {\n return (\n mimeType ===\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\" ||\n mimeType === \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\" ||\n mimeType ===\n \"application/vnd.openxmlformats-officedocument.presentationml.presentation\"\n );\n }\n\n /**\n * Checks if a MIME type represents a legacy Office document (DOC, XLS, PPT).\n */\n public static isLegacyOfficeDocument(mimeType: string): boolean {\n return (\n mimeType === \"application/msword\" ||\n mimeType === \"application/vnd.ms-excel\" ||\n mimeType === \"application/vnd.ms-powerpoint\"\n );\n }\n\n /**\n * Checks if a MIME type represents an OpenDocument format (ODT, ODS, ODP).\n */\n public static isOpenDocument(mimeType: string): boolean {\n return (\n mimeType === \"application/vnd.oasis.opendocument.text\" ||\n mimeType === \"application/vnd.oasis.opendocument.spreadsheet\" ||\n mimeType === \"application/vnd.oasis.opendocument.presentation\"\n );\n }\n\n /**\n * Checks if a MIME type represents RTF content.\n */\n public static isRtf(mimeType: string): boolean {\n return mimeType === \"application/rtf\" || mimeType === \"text/rtf\";\n }\n\n /**\n * Checks if a MIME type represents an eBook format (EPUB, FB2).\n */\n public static isEbook(mimeType: string): boolean {\n return (\n mimeType === \"application/epub+zip\" || mimeType === \"application/x-fictionbook+xml\"\n );\n }\n\n /**\n * Checks if a MIME type represents a Jupyter Notebook.\n */\n public static isJupyterNotebook(mimeType: string): boolean {\n return mimeType === \"application/x-ipynb+json\";\n }\n\n /**\n * Checks if a MIME type represents a document that can be processed\n * by the DocumentPipeline (PDF, Office docs, OpenDocument, RTF, eBooks,\n * Jupyter notebooks).\n */\n public static isSupportedDocument(mimeType: string): boolean {\n return (\n MimeTypeUtils.isPdf(mimeType) ||\n MimeTypeUtils.isOfficeDocument(mimeType) ||\n MimeTypeUtils.isLegacyOfficeDocument(mimeType) ||\n MimeTypeUtils.isOpenDocument(mimeType) ||\n MimeTypeUtils.isRtf(mimeType) ||\n MimeTypeUtils.isEbook(mimeType) ||\n MimeTypeUtils.isJupyterNotebook(mimeType)\n );\n }\n\n /**\n * Checks if a MIME type represents source code that should be wrapped in code blocks.\n */\n public static isSourceCode(mimeType: string): boolean {\n return MimeTypeUtils.extractLanguageFromMimeType(mimeType) !== \"\";\n }\n\n /**\n * Checks if a MIME type names a binary media family: image, video, audio, or font.\n *\n * These are the families whose file extensions are trustworthy enough to act on\n * before a request is made. Deliberately excludes `application/*`, because the\n * `mime` package files plain-text scripts there — `.csh`, `.tcl`, `.bat` and\n * `.scm` all resolve to `application/*` despite being source code that pipelines\n * read happily.\n *\n * @param mimeType The MIME type to classify.\n * @returns True when the type names binary media.\n */\n public static isBinaryMediaType(mimeType: string): boolean {\n if (!mimeType) return false;\n const normalized = mimeType.toLowerCase();\n return (\n normalized.startsWith(\"image/\") ||\n normalized.startsWith(\"video/\") ||\n normalized.startsWith(\"audio/\") ||\n normalized.startsWith(\"font/\")\n );\n }\n\n /**\n * Checks if content appears to be binary based on the presence of null bytes.\n * This is a reliable heuristic since text files should not contain null bytes.\n * @param content The content to check (string or Buffer)\n * @returns true if the content appears to be binary\n */\n public static isBinary(content: string | Buffer): boolean {\n if (typeof content === \"string\") {\n return content.includes(\"\\0\");\n }\n\n // For Buffer, check for null bytes directly\n return content.includes(0);\n }\n\n /**\n * Detects MIME type from file path or URL, with special handling for common source code\n * extensions that the mime package doesn't handle well or gets wrong.\n *\n * Query parameters and hash fragments are stripped before extension detection, so URLs\n * like `https://cdn.example.com/report.pdf?token=abc#page=1` are handled correctly.\n *\n * @param filePath - The file path or URL to detect MIME type for\n * @returns The detected MIME type or null if unknown\n */\n public static detectMimeTypeFromPath(filePath: string): string | null {\n // Strip query parameters and hash fragments that may be present in URLs\n // (e.g., \"report.pdf?token=abc\" or \"doc.html#section\")\n const cleanPath = filePath.split(\"?\")[0].split(\"#\")[0];\n const extension = cleanPath.toLowerCase().split(\".\").pop();\n\n if (extension && CUSTOM_MIME_TYPES[extension]) {\n return CUSTOM_MIME_TYPES[extension];\n }\n\n // Fall back to the mime package for other types\n const detectedType = mime.getType(cleanPath);\n\n // Normalize problematic MIME types that the mime package gets wrong\n return MimeTypeUtils.normalizeMimeType(detectedType);\n }\n\n /**\n * Normalizes MIME types that are incorrectly detected by the mime package.\n * This handles cases like 'application/node' for .cjs files.\n *\n * @param mimeType - The MIME type to normalize\n * @returns The normalized MIME type\n */\n public static normalizeMimeType(mimeType: string | null): string | null {\n if (!mimeType) {\n return null;\n }\n\n return MIME_TYPE_NORMALIZATION[mimeType] || mimeType;\n }\n\n /**\n * Extracts the programming language identifier from a MIME type for code block formatting.\n *\n * @param mimeType - The MIME type to extract language from\n * @returns The language identifier (e.g., \"typescript\", \"python\") or empty string if unknown\n */\n public static extractLanguageFromMimeType(mimeType: string): string {\n const mimeToLanguage: Record<string, string> = {\n // JavaScript/TypeScript\n \"text/x-typescript\": \"typescript\",\n \"text/typescript\": \"typescript\",\n \"application/typescript\": \"typescript\",\n \"text/x-tsx\": \"tsx\",\n \"text/javascript\": \"javascript\",\n \"application/javascript\": \"javascript\",\n \"application/x-javascript\": \"javascript\",\n \"text/x-jsx\": \"jsx\",\n\n // Python\n \"text/x-python\": \"python\",\n \"text/x-cython\": \"cython\",\n\n // Systems languages\n \"text/x-c\": \"c\",\n \"text/x-csrc\": \"c\",\n \"text/x-chdr\": \"c\",\n \"text/x-c++\": \"cpp\",\n \"text/x-c++src\": \"cpp\",\n \"text/x-c++hdr\": \"cpp\",\n \"text/x-go\": \"go\",\n \"text/x-rust\": \"rust\",\n \"text/x-zig\": \"zig\",\n \"text/x-nim\": \"nim\",\n \"text/x-v\": \"v\",\n \"text/x-crystal\": \"crystal\",\n\n // JVM languages\n \"text/x-java\": \"java\",\n \"text/x-kotlin\": \"kotlin\",\n \"text/x-scala\": \"scala\",\n \"text/x-groovy\": \"groovy\",\n \"text/x-gradle\": \"groovy\",\n\n // Apple/Mobile\n \"text/x-swift\": \"swift\",\n \"text/x-dart\": \"dart\",\n\n // .NET\n \"text/x-csharp\": \"csharp\",\n\n // Scripting languages\n \"text/x-ruby\": \"ruby\",\n \"text/x-php\": \"php\",\n \"text/x-lua\": \"lua\",\n \"text/x-perl\": \"perl\",\n \"text/x-r\": \"r\",\n\n // Functional languages\n \"text/x-haskell\": \"haskell\",\n \"text/x-elm\": \"elm\",\n \"text/x-erlang\": \"erlang\",\n \"text/x-elixir\": \"elixir\",\n \"text/x-clojure\": \"clojure\",\n \"text/x-scheme\": \"scheme\",\n \"text/x-tcl\": \"tcl\",\n \"text/x-batch\": \"batch\",\n \"text/x-julia\": \"julia\",\n\n // Web3/Smart contracts\n \"text/x-solidity\": \"solidity\",\n \"text/x-move\": \"move\",\n \"text/x-cairo\": \"cairo\",\n\n // Modern web frameworks\n \"text/x-vue\": \"vue\",\n \"text/x-svelte\": \"svelte\",\n \"text/x-astro\": \"astro\",\n\n // Stylesheets\n \"text/css\": \"css\",\n \"text/x-scss\": \"scss\",\n \"text/x-sass\": \"sass\",\n \"text/less\": \"less\",\n\n // Shell\n \"text/x-sh\": \"bash\",\n \"text/x-shellscript\": \"bash\",\n \"application/x-sh\": \"bash\",\n \"text/x-powershell\": \"powershell\",\n\n // Documentation formats\n \"text/x-rst\": \"rst\",\n \"text/x-asciidoc\": \"asciidoc\",\n \"text/x-textile\": \"textile\",\n \"text/x-org\": \"org\",\n \"text/x-pod\": \"pod\",\n \"text/x-rdoc\": \"rdoc\",\n \"text/x-wiki\": \"wiki\",\n \"text/x-rmarkdown\": \"rmarkdown\",\n\n // Configuration files\n \"text/x-toml\": \"toml\",\n \"text/x-ini\": \"ini\",\n \"text/x-conf\": \"conf\",\n \"text/x-properties\": \"properties\",\n \"text/x-dotenv\": \"dotenv\",\n\n // Build systems\n \"text/x-dockerfile\": \"dockerfile\",\n \"text/x-makefile\": \"makefile\",\n \"text/x-cmake\": \"cmake\",\n \"text/x-bazel\": \"bazel\",\n \"text/x-buck\": \"buck\",\n\n // Infrastructure as Code\n \"text/x-terraform\": \"hcl\",\n \"text/x-hcl\": \"hcl\",\n\n // Data formats\n \"text/x-yaml\": \"yaml\",\n \"text/yaml\": \"yaml\",\n \"application/x-yaml\": \"yaml\",\n \"application/yaml\": \"yaml\",\n \"text/x-json\": \"json\",\n \"application/json\": \"json\",\n \"text/x-xml\": \"xml\",\n \"text/xml\": \"xml\",\n \"application/xml\": \"xml\",\n \"application/xslt+xml\": \"xml\",\n \"application/xml-dtd\": \"xml\",\n \"application/wsdl+xml\": \"xml\",\n \"text/x-sql\": \"sql\",\n \"text/x-graphql\": \"graphql\",\n\n // Schema/API definitions\n \"text/x-proto\": \"protobuf\",\n \"text/x-prisma\": \"prisma\",\n \"text/x-thrift\": \"thrift\",\n \"text/x-avro\": \"avro\",\n\n // TeX/LaTeX\n \"text/x-tex\": \"tex\",\n \"text/x-latex\": \"latex\",\n };\n\n return mimeToLanguage[mimeType] || \"\";\n }\n}\n","import psl from \"psl\";\nimport { InvalidUrlError } from \"./errors\";\nimport { MimeTypeUtils } from \"./mimeTypeUtils\";\n\ninterface UrlNormalizerOptions {\n removeHash?: boolean;\n removeTrailingSlash?: boolean;\n removeQuery?: boolean;\n removeIndex?: boolean;\n}\n\nconst defaultNormalizerOptions: UrlNormalizerOptions = {\n removeHash: true,\n removeTrailingSlash: true,\n removeQuery: false,\n removeIndex: true,\n};\n\nexport function normalizeUrl(\n url: string,\n options: UrlNormalizerOptions = defaultNormalizerOptions,\n): string {\n try {\n const finalOptions = { ...defaultNormalizerOptions, ...options };\n const normalized = new URL(url);\n\n // Captured before the reset below, so the URL is parsed once rather than twice.\n const originalHash = normalized.hash;\n const originalSearch = normalized.search;\n\n // Reset search and hash for the normalized base\n normalized.search = \"\";\n normalized.hash = \"\";\n\n // A preserved fragment names a route, so the path in front of it is part of\n // that route's spelling: on a hash-routed site `/docs/#/guide` and\n // `/docs#/guide` are different pages, and trimming the slash invents a URL\n // the site does not serve. Only URLs that actually carry a fragment are\n // exempt — an ordinary `/docs/` on the same site still folds onto `/docs`,\n // which is why this is decided per URL rather than per crawl.\n const pathIsPartOfRoute = !finalOptions.removeHash && originalHash !== \"\";\n\n // Remove index files first, before handling trailing slashes\n if (finalOptions.removeIndex && !pathIsPartOfRoute) {\n normalized.pathname = normalized.pathname.replace(\n /\\/index\\.(html|htm|asp|php|jsp)$/i,\n \"/\",\n );\n }\n\n // Handle trailing slash\n if (\n finalOptions.removeTrailingSlash &&\n !pathIsPartOfRoute &&\n normalized.pathname.length > 1\n ) {\n normalized.pathname = normalized.pathname.replace(/\\/+$/, \"\");\n }\n\n // Keep original parts we want to preserve\n const preservedHash = !finalOptions.removeHash ? originalHash : \"\";\n const preservedSearch = !finalOptions.removeQuery ? originalSearch : \"\";\n\n // Construct final URL string\n // Use href to get the full string, but we need to re-assemble if we want query/hash specific control\n // Easier: use the modified normalized object\n if (!finalOptions.removeQuery) {\n normalized.search = preservedSearch;\n }\n if (!finalOptions.removeHash) {\n normalized.hash = preservedHash;\n }\n\n // Case is deliberately left alone. A URL path, query and fragment are\n // case-sensitive, so folding them can merge two different documents into\n // one — and since this value is the crawl's dedup key, the second one is\n // then never fetched. Servers that do serve paths case-insensitively will\n // index a page twice instead, which is the failure that leaves evidence.\n return normalized.href;\n } catch {\n return url; // Return original URL if parsing fails\n }\n}\n\n/**\n * Validates if a string is a valid URL\n * @throws {InvalidUrlError} If the URL is invalid\n */\nexport function validateUrl(url: string): void {\n try {\n new URL(url);\n } catch (error) {\n throw new InvalidUrlError(url, error instanceof Error ? error : undefined);\n }\n}\n\n/**\n * Extracts the primary/registrable domain from a hostname using the public suffix list.\n * This properly handles complex TLDs like .co.uk, .com.au, etc.\n *\n * Examples:\n * - docs.python.org -> python.org\n * - api.github.com -> github.com\n * - example.co.uk -> example.co.uk\n * - user.github.io -> user.github.io (special case for GitHub Pages)\n * - localhost -> localhost\n * - 192.168.1.1 -> 192.168.1.1 (IP addresses returned as-is)\n */\nexport function extractPrimaryDomain(hostname: string): string {\n // Handle IP addresses - return as-is\n if (/^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(hostname) || /^[0-9a-fA-F:]+$/.test(hostname)) {\n return hostname;\n }\n\n // Handle localhost and other single-part hostnames\n if (!hostname.includes(\".\")) {\n return hostname;\n }\n\n // Use public suffix list for accurate domain extraction\n const domain = psl.get(hostname.toLowerCase());\n return domain || hostname; // Fallback to original hostname if psl fails\n}\n\nexport type { UrlNormalizerOptions };\n\n/**\n * Rewrites a published Markdown file's URL to the page it represents.\n *\n * `https://example.com/guide.md` and `https://example.com/guide` name the same\n * document, so they must share one identity — otherwise a site whose `llms.txt`\n * lists `.md` URLs is indexed twice, once per spelling.\n *\n * The extension is only half the test. Callers SHALL also establish that the\n * response really was Markdown, because a server that ignores the extension and\n * answers with HTML or a soft error would otherwise fold a page onto an identity\n * that does not serve it.\n *\n * @param url The absolute URL the content was fetched from.\n * @returns The page URL, or `url` unchanged when the path names no Markdown file.\n */\nexport function stripMarkdownExtension(url: string): string {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return url;\n }\n\n // Gated on the shared detector rather than on \"has a dot\", so the name stays\n // true and the set of Markdown extensions has one home. The pathname is passed\n // deliberately: given a whole URL the detector would read a host like\n // `example.md` as a Markdown file.\n const detected = MimeTypeUtils.detectMimeTypeFromPath(parsed.pathname);\n if (!detected || !MimeTypeUtils.isMarkdown(detected)) return url;\n\n // A leading dot is not an extension separator, so `/.md` is left alone — it\n // names no page to fold onto.\n const stripped = parsed.pathname.replace(/([^/])\\.[^/.]*$/, \"$1\");\n if (stripped === parsed.pathname) return url;\n\n parsed.pathname = stripped;\n return parsed.toString();\n}\n","/**\n * Default exclusion patterns for documentation scraping.\n * These patterns are always applied unless user explicitly provides their own exclude patterns.\n * Patterns use glob/regex syntax supported by the pattern matcher.\n */\n\n/**\n * Default file exclusion patterns - files commonly found in documentation that should be excluded.\n * These patterns match files anywhere in the path structure.\n */\nexport const DEFAULT_FILE_EXCLUSIONS = [\n // CHANGELOG files (case variations)\n \"**/CHANGELOG.md\",\n \"**/changelog.md\",\n \"**/CHANGELOG.mdx\",\n \"**/changelog.mdx\",\n\n // LICENSE files (case variations)\n \"**/LICENSE\",\n \"**/LICENSE.md\",\n \"**/license.md\",\n\n // CODE_OF_CONDUCT files (case variations)\n \"**/CODE_OF_CONDUCT.md\",\n \"**/code_of_conduct.md\",\n\n // Test files\n \"**/*.test.*\",\n \"**/*.spec.*\",\n \"**/*_test.py\",\n \"**/*_test.go\",\n\n // Package manager lock files\n \"**/*.lock\",\n \"**/package-lock.json\",\n \"**/yarn.lock\",\n \"**/pnpm-lock.yaml\",\n \"**/go.sum\",\n\n // Build artifacts\n \"**/*.min.js\",\n \"**/*.min.css\",\n \"**/*.map\",\n \"**/*.d.ts\",\n\n // IDE/System files\n \"**/.DS_Store\",\n \"**/Thumbs.db\",\n \"**/*.swp\",\n \"**/*.swo\",\n\n // Internal config files (using regex pattern)\n \"/.*\\\\.(ini|cfg|conf|log|pid)$/\",\n];\n\n/**\n * Default folder/path exclusion patterns - directories commonly found in documentation that should be excluded.\n */\nexport const DEFAULT_FOLDER_EXCLUSIONS = [\n // Archive and deprecated content (matches anywhere in path)\n \"**/archive/**\",\n \"**/archived/**\",\n \"**/deprecated/**\",\n \"**/legacy/**\",\n \"**/old/**\",\n \"**/outdated/**\",\n \"**/previous/**\",\n \"**/superseded/**\",\n\n // Specific paths that don't follow the general pattern\n \"docs/old/**\",\n\n // Test directories\n \"**/test/**\",\n \"**/tests/**\",\n \"**/__tests__/**\",\n \"**/spec/**\",\n\n // Build output directories\n \"**/dist/**\",\n \"**/build/**\",\n \"**/out/**\",\n \"**/target/**\",\n \"**/.next/**\",\n \"**/.nuxt/**\",\n\n // IDE directories\n \"**/.vscode/**\",\n \"**/.idea/**\",\n\n // Internationalization folders - non-English locales\n \"**/i18n/ar*/**\",\n \"**/i18n/de*/**\",\n \"**/i18n/es*/**\",\n \"**/i18n/fr*/**\",\n \"**/i18n/hi*/**\",\n \"**/i18n/it*/**\",\n \"**/i18n/ja*/**\",\n \"**/i18n/ko*/**\",\n \"**/i18n/nl*/**\",\n \"**/i18n/pl*/**\",\n \"**/i18n/pt*/**\",\n \"**/i18n/ru*/**\",\n \"**/i18n/sv*/**\",\n \"**/i18n/th*/**\",\n \"**/i18n/tr*/**\",\n \"**/i18n/vi*/**\",\n \"**/i18n/zh*/**\",\n\n // Common locale folder patterns\n \"**/zh-cn/**\",\n \"**/zh-hk/**\",\n \"**/zh-mo/**\",\n \"**/zh-sg/**\",\n \"**/zh-tw/**\",\n];\n\n/**\n * Combined default exclusion patterns (files + folders).\n * These are applied when no user-provided exclude patterns are specified.\n */\nexport const DEFAULT_EXCLUSION_PATTERNS = [\n ...DEFAULT_FILE_EXCLUSIONS,\n ...DEFAULT_FOLDER_EXCLUSIONS,\n];\n\n/**\n * Get effective exclusion patterns by merging defaults with user patterns.\n * If user provides patterns, use only theirs (allowing override).\n * If user provides no patterns, use defaults.\n */\nexport function getEffectiveExclusionPatterns(userPatterns?: string[]): string[] {\n // If user explicitly provides patterns (even empty array), respect their choice\n if (userPatterns !== undefined) {\n return userPatterns;\n }\n\n // Otherwise, use default patterns\n return DEFAULT_EXCLUSION_PATTERNS;\n}\n","import { Minimatch, minimatch } from \"minimatch\";\nimport { getEffectiveExclusionPatterns } from \"./defaultPatterns\";\n\n/**\n * Utility functions for pattern matching (glob and regex) for URL filtering.\n * Supports auto-detection and conversion of glob patterns to RegExp.\n *\n * Default exclusion patterns are applied when no user-provided exclude patterns are specified.\n * This includes common documentation files (CHANGELOG.md, LICENSE, etc.) and folders\n * (archive directories, non-English locales, etc.).\n *\n * Patterns starting and ending with '/' are treated as regex, otherwise as glob (minimatch syntax).\n * Glob wildcards supported: '*' (any chars except '/'), '**' (any chars, including '/').\n *\n * @module patternMatcher\n */\n\n/**\n * Compiled-pattern caches.\n *\n * Every discovered URL is matched against the full exclusion set — around 70\n * default patterns, tested against both the full URL and the pathname — so\n * recompiling each pattern per URL dominates the cost of link filtering.\n * Compilation depends only on the pattern string (options are fixed), and the\n * key space is the set of distinct patterns in use rather than anything\n * URL-derived, so these stay naturally bounded.\n */\nconst regExpCache = new Map<string, RegExp>();\nconst globCache = new Map<string, Minimatch>();\n\n/**\n * Returns a compiled matcher for a glob pattern, reusing a previous one when the\n * same pattern has been seen before.\n *\n * @param pattern The glob pattern to compile.\n * @returns A reusable Minimatch instance.\n */\nfunction getGlobMatcher(pattern: string): Minimatch {\n let matcher = globCache.get(pattern);\n if (!matcher) {\n matcher = new Minimatch(pattern, { dot: true });\n globCache.set(pattern, matcher);\n }\n return matcher;\n}\n\n/**\n * Detects if a pattern is a regex (starts and ends with '/')\n */\nexport function isRegexPattern(pattern: string): boolean {\n return pattern.length > 2 && pattern.startsWith(\"/\") && pattern.endsWith(\"/\");\n}\n\n/**\n * Converts a pattern string to a RegExp instance (auto-detects glob/regex).\n * For globs, uses minimatch's internal conversion.\n */\nexport function patternToRegExp(pattern: string): RegExp {\n const cached = regExpCache.get(pattern);\n if (cached) return cached;\n\n let re: RegExp | false;\n if (isRegexPattern(pattern)) {\n re = new RegExp(pattern.slice(1, -1));\n } else {\n // For globs, minimatch.makeRe returns a RegExp\n re = minimatch.makeRe(pattern, { dot: true });\n }\n if (!re) throw new Error(`Invalid glob pattern: ${pattern}`);\n\n regExpCache.set(pattern, re);\n return re;\n}\n\n/**\n * Matches an absolute URL with a scheme (e.g. `https://`, `file://`).\n * Used to avoid prepending a `/` to inputs that are already full URLs.\n */\nconst URL_WITH_PROTOCOL_RE = /^[a-z][a-z0-9+.-]*:\\/\\//i;\n\n/**\n * Checks if a given path matches any pattern in the list.\n * For globs, uses minimatch. For regex, uses RegExp.\n */\nexport function matchesAnyPattern(path: string, patterns?: string[]): boolean {\n if (!patterns || patterns.length === 0) return false;\n // Always match from a leading slash for path-based globs, but leave full\n // URLs (with scheme) untouched so anchored regex patterns like `^https://`\n // still match.\n const isFullUrl = URL_WITH_PROTOCOL_RE.test(path);\n const normalizedPath = isFullUrl || path.startsWith(\"/\") ? path : `/${path}`;\n return patterns.some((pattern) => {\n if (isRegexPattern(pattern)) {\n return patternToRegExp(pattern).test(normalizedPath);\n }\n // For glob patterns:\n // - If pattern starts with '/', strip leading slash from BOTH pattern and path for minimatch\n // - Otherwise, strip leading slash only from path\n const pathForMatch = normalizedPath.replace(/^\\//, \"\");\n const patternForMatch = pattern.startsWith(\"/\") ? pattern.slice(1) : pattern;\n return getGlobMatcher(patternForMatch).match(pathForMatch);\n });\n}\n\n/**\n * Matches a flat string (hostname, label, etc.) against patterns without any\n * path normalization. Patterns use the same syntax as URL patterns: a glob\n * processed by minimatch, or a regex wrapped in `/.../`. Matching is\n * case-insensitive, which matches DNS semantics for the hostname use case.\n */\nexport function matchesAnyHostPattern(value: string, patterns?: string[]): boolean {\n if (!patterns || patterns.length === 0) return false;\n const normalized = value.toLowerCase();\n return patterns.some((pattern) => {\n if (isRegexPattern(pattern)) {\n return patternToRegExp(pattern).test(value);\n }\n return getGlobMatcher(pattern.toLowerCase()).match(normalized);\n });\n}\n\n/**\n * Extracts the path and query from a URL string (no domain).\n */\nexport function extractPathAndQuery(url: string): string {\n try {\n const u = new URL(url);\n return u.pathname + (u.search || \"\");\n } catch {\n return url; // fallback: return as-is\n }\n}\n\n/**\n * Determines if a URL should be included based on include/exclude patterns.\n * Exclude patterns take precedence. If no include patterns, all are included by default.\n *\n * If no user exclude patterns are provided, default exclusion patterns are automatically applied.\n * These defaults exclude common documentation files (CHANGELOG.md, LICENSE, etc.) and folders\n * (archives, non-English locales, etc.).\n *\n * Patterns are matched against both the full URL and the pathname for maximum flexibility:\n * - Full URL: `https://example.com/docs/v3/**` matches `https://example.com/docs/v3/guide`\n * - Pathname: `/docs/v3/**` matches `https://example.com/docs/v3/guide`\n */\nexport function shouldIncludeUrl(\n url: string,\n includePatterns?: string[],\n excludePatterns?: string[],\n): boolean {\n // Extract pathname for path-based pattern matching\n const path = extractPathAndQuery(url);\n const normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n\n // For file:// URLs, also match against the basename (strip leading slash from pattern for basename matching)\n let basename: string | undefined;\n if (url.startsWith(\"file://\")) {\n try {\n const u = new URL(url);\n basename = u.pathname ? u.pathname.split(\"/\").pop() : undefined;\n } catch {}\n }\n // Helper to strip leading slash from patterns for basename matching\n const stripSlash = (patterns?: string[]) =>\n patterns?.map((p) => (p.startsWith(\"/\") ? p.slice(1) : p));\n\n // Get effective exclusion patterns (merges defaults with user patterns)\n const effectiveExcludePatterns = getEffectiveExclusionPatterns(excludePatterns);\n\n // Exclude patterns take precedence\n // Match against BOTH full URL and pathname for flexibility\n if (\n matchesAnyPattern(url, effectiveExcludePatterns) ||\n matchesAnyPattern(normalizedPath, effectiveExcludePatterns) ||\n (basename && matchesAnyPattern(basename, stripSlash(effectiveExcludePatterns)))\n )\n return false;\n if (!includePatterns || includePatterns.length === 0) return true;\n // Match against BOTH full URL and pathname for flexibility\n return (\n matchesAnyPattern(url, includePatterns) ||\n matchesAnyPattern(normalizedPath, includePatterns) ||\n (basename ? matchesAnyPattern(basename, stripSlash(includePatterns)) : false)\n );\n}\n","import { lookup } from \"node:dns/promises\";\nimport fs from \"node:fs/promises\";\nimport net from \"node:net\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { matchesAnyHostPattern } from \"../scraper/utils/patternMatcher\";\nimport type { AppConfig } from \"./config\";\nimport { AccessPolicyError } from \"./errors\";\nimport { logger } from \"./logger\";\n\nconst SPECIAL_USE_IPV4_CIDRS = [\n \"0.0.0.0/8\",\n \"10.0.0.0/8\",\n \"100.64.0.0/10\",\n \"127.0.0.0/8\",\n \"169.254.0.0/16\",\n \"172.16.0.0/12\",\n \"192.0.0.0/24\",\n \"192.0.2.0/24\",\n \"192.168.0.0/16\",\n \"198.18.0.0/15\",\n \"198.51.100.0/24\",\n \"203.0.113.0/24\",\n \"224.0.0.0/4\",\n \"240.0.0.0/4\",\n];\n\nconst SPECIAL_USE_IPV6_CIDRS = [\"::/128\", \"::1/128\", \"fc00::/7\", \"fe80::/10\", \"ff00::/8\"];\n\nconst ARCHIVE_EXTENSIONS = new Set([\".zip\", \".tar\", \".gz\", \".tgz\"]);\n\n/**\n * Where users go to change file access decisions.\n *\n * Rejections state which rule blocked the path and point here, rather than\n * naming individual settings and environment variables. Every setting named in\n * an error is one more thing a rename can silently invalidate, and the docs\n * carry the full picture — config file, env vars, and tokens — in one place\n * that is already maintained. Deep-linked without an anchor on purpose: a stale\n * anchor fails quietly.\n */\nconst FILE_ACCESS_DOCS =\n \"https://github.com/arabold/docs-mcp-server/blob/main/docs/setup/configuration.md\";\n\ntype ScraperSecurityConfig = AppConfig[\"scraper\"][\"security\"];\n\nexport interface ResolvedFileAccess {\n filePath: string;\n accessPath: string;\n virtualArchivePath: string | null;\n}\n\n/**\n * Shared access policy for outbound network and local file access.\n */\nexport class ScraperAccessPolicy {\n private readonly allowedCidrs = new net.BlockList();\n private readonly specialUseCidrs = new net.BlockList();\n private readonly allowedHosts: string[];\n /** Roots already reported as unresolvable, so each is warned about once. */\n private readonly warnedUnresolvedRoots = new Set<string>();\n private hasWarnedUnavailableAllowlist = false;\n private hasLoggedConfiguredRoots = false;\n\n constructor(private readonly security: ScraperSecurityConfig) {\n this.allowedHosts = security.network.allowedHosts;\n\n for (const cidr of security.network.allowedCidrs) {\n this.addCidr(this.allowedCidrs, cidr);\n }\n\n for (const cidr of SPECIAL_USE_IPV4_CIDRS) {\n this.addCidr(this.specialUseCidrs, cidr);\n }\n for (const cidr of SPECIAL_USE_IPV6_CIDRS) {\n this.addCidr(this.specialUseCidrs, cidr);\n }\n }\n\n /**\n * Checks whether a network URL is allowed before connecting.\n */\n async assertNetworkUrlAllowed(url: string): Promise<void> {\n const parsed = new URL(url);\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n return;\n }\n\n const hostname = normalizeHostname(parsed.hostname);\n const ipFamily = net.isIP(hostname);\n\n if (this.security.network.mode === \"allowlist\") {\n // Allowlist mode: a request is permitted iff its hostname matches a\n // configured host pattern OR every resolved IP for the hostname is\n // inside `allowedCidrs`. `allowPrivateNetworks` is intentionally ignored\n // here because the explicit allowlist is the complete authorization\n // surface.\n //\n // A hostname listed in `allowedHosts` is authoritative for that name:\n // we trust its DNS answers, even when they resolve to private or\n // special-use addresses. This mirrors `open` mode and matches the\n // documented mental model — adding a host to `allowedHosts` is the\n // explicit trust decision. Operators who want a strictly address-bound\n // policy can leave `allowedHosts` empty and use `allowedCidrs` only.\n if (ipFamily !== 0) {\n const family = ipFamily === 6 ? \"ipv6\" : \"ipv4\";\n if (this.allowedCidrs.check(hostname, family)) return;\n throw new AccessPolicyError(`Security policy blocked network access to ${url}`);\n }\n\n if (matchesAnyHostPattern(hostname, this.allowedHosts)) {\n return;\n }\n\n const addresses = await resolveAddresses(hostname);\n const allAllowedByCidr =\n addresses.length > 0 &&\n addresses.every((address) => {\n const family = net.isIP(address.address);\n if (family === 0) return false;\n return this.allowedCidrs.check(address.address, family === 6 ? \"ipv6\" : \"ipv4\");\n });\n if (allAllowedByCidr) return;\n\n throw new AccessPolicyError(`Security policy blocked network access to ${url}`);\n }\n\n // Open mode: public targets are allowed; private/special-use targets are\n // blocked unless explicitly opened up.\n if (this.security.network.allowPrivateNetworks) {\n return;\n }\n\n if (ipFamily !== 0) {\n this.assertSpecialUseAddressAllowed(hostname, url);\n return;\n }\n\n if (looksLikeIpLiteral(hostname)) {\n throw new AccessPolicyError(`Security policy blocked network access to ${url}`);\n }\n\n if (matchesAnyHostPattern(hostname, this.allowedHosts)) {\n return;\n }\n\n const addresses = await resolveAddresses(hostname);\n for (const address of addresses) {\n this.assertSpecialUseAddressAllowed(address.address, url);\n }\n }\n\n /**\n * Checks whether TLS certificate validation may be bypassed for a URL.\n */\n shouldAllowInvalidTls(url: string): boolean {\n try {\n const parsed = new URL(url);\n return parsed.protocol === \"https:\" && this.security.network.allowInvalidTls;\n } catch {\n return false;\n }\n }\n\n /**\n * Resolves and validates a file URL against the configured file access policy.\n *\n * Rejections name the specific policy rule that blocked the path and link to\n * the configuration documentation rather than naming individual settings.\n * Filesystem paths — configured or resolved — stay out of the thrown message\n * because it reaches MCP clients and the web UI; they are logged instead,\n * where only the operator sees them. Root tokens such as `$DOCUMENTS` are\n * named in the message: they are runtime state rather than host detail, and\n * warn-level logs are suppressed on the non-interactive runs where an\n * unresolvable token is most likely.\n */\n async resolveFileAccess(\n url: string,\n additionalAllowedRoots: string[] = [],\n ): Promise<ResolvedFileAccess> {\n const filePath = fileUrlToPathLoose(url);\n const resolved = await resolveArchiveAwarePath(filePath);\n const accessPath = resolved.archivePath ?? filePath;\n const bypassRoots = await this.expandRoots(additionalAllowedRoots);\n const matchedBypassRoot = await this.findContainingRoot(\n accessPath,\n bypassRoots,\n false,\n );\n\n let matchedRoot: string | null = matchedBypassRoot;\n\n if (this.security.fileAccess.mode === \"disabled\" && !matchedBypassRoot) {\n throw new AccessPolicyError(\n `Local file access is disabled by the scraper security policy, so ${url} cannot be indexed. ` +\n `See ${FILE_ACCESS_DOCS} to configure local file access.`,\n );\n }\n\n if (this.security.fileAccess.mode === \"allowedRoots\" && !matchedBypassRoot) {\n const configuredRoots = await this.expandRoots(\n this.security.fileAccess.allowedRoots,\n true,\n );\n if (configuredRoots.length === 0) {\n this.warnUnavailableAllowlist();\n throw new AccessPolicyError(\n `Local file access is limited to configured roots, but ${describeUnavailableRoots(\n this.security.fileAccess.allowedRoots,\n )}, so ${url} cannot be indexed. ` +\n `See ${FILE_ACCESS_DOCS} to configure the allowed roots.`,\n );\n }\n\n matchedRoot = await this.findContainingRoot(\n accessPath,\n configuredRoots,\n this.security.fileAccess.followSymlinks,\n );\n if (!matchedRoot) {\n this.logConfiguredRoots(configuredRoots);\n throw new AccessPolicyError(\n `${url} is outside the configured allowed roots, so it cannot be indexed. ` +\n `See ${FILE_ACCESS_DOCS} to allow this folder.`,\n );\n }\n }\n\n if (!this.security.fileAccess.followSymlinks && !matchedBypassRoot) {\n const symlinkPath = await findSymlinkInPath(accessPath);\n if (symlinkPath) {\n throw new AccessPolicyError(\n `${url} resolves through a symlink, which the security policy blocks by default, so it cannot be indexed. ` +\n `See ${FILE_ACCESS_DOCS} to allow symlinked paths.`,\n );\n }\n }\n\n if (!this.security.fileAccess.includeHidden) {\n // Hidden-segment checks apply to segments strictly below the matched\n // allowed root. Segments at-or-above the root are part of the user's\n // explicit opt-in: a configured root like `/Users/x/.config/docs` is\n // expected to live under a hidden ancestor and must not be self-rejected.\n // In `unrestricted` mode with no specific match, fall back to checking\n // the full absolute path.\n if (hasHiddenSegmentBelowRoot(filePath, matchedRoot)) {\n throw new AccessPolicyError(\n `${url} contains a hidden path segment (a name starting with \".\"), which the security policy blocks by default, ` +\n `so it cannot be indexed. See ${FILE_ACCESS_DOCS} to allow hidden files and folders.`,\n );\n }\n if (\n resolved.virtualArchivePath &&\n hasHiddenArchiveSegment(resolved.virtualArchivePath)\n ) {\n throw new AccessPolicyError(\n `The archive entry requested by ${url} is hidden (a name starting with \".\"), which the security policy blocks by default. ` +\n `See ${FILE_ACCESS_DOCS} to allow hidden archive entries.`,\n );\n }\n }\n\n return {\n filePath,\n accessPath,\n virtualArchivePath: resolved.virtualArchivePath,\n };\n }\n\n /**\n * Throws if `address` falls inside a blocked special-use range and is not\n * explicitly permitted by `allowedCidrs`. Used both for direct-IP targets\n * and for revalidating DNS-resolved addresses (open mode) and allowlisted\n * hostnames (allowlist mode, to close DNS-rebinding gaps).\n */\n private assertSpecialUseAddressAllowed(address: string, url: string): void {\n const family = net.isIP(address);\n if (family === 0) {\n return;\n }\n\n const type = family === 6 ? \"ipv6\" : \"ipv4\";\n if (!this.specialUseCidrs.check(address, type)) {\n return;\n }\n\n if (this.allowedCidrs.check(address, type)) {\n return;\n }\n\n throw new AccessPolicyError(`Security policy blocked network access to ${url}`);\n }\n\n private addCidr(blockList: net.BlockList, cidr: string): void {\n const [network, prefix] = cidr.split(\"/\");\n const family = net.isIP(network);\n if (family === 0 || prefix === undefined) {\n return;\n }\n blockList.addSubnet(\n network,\n Number.parseInt(prefix, 10),\n family === 6 ? \"ipv6\" : \"ipv4\",\n );\n }\n\n /**\n * Expands configured root entries into concrete paths, dropping those that do\n * not resolve on this system. With `warnOnUnresolved`, every dropped entry is\n * reported once — silently discarding them makes `allowedRoots` look active\n * when it grants nothing.\n */\n private async expandRoots(\n roots: string[],\n warnOnUnresolved = false,\n ): Promise<string[]> {\n const expanded: string[] = [];\n for (const root of roots) {\n const value = await expandConfiguredRoot(root);\n if (value) {\n expanded.push(value);\n continue;\n }\n if (warnOnUnresolved && !this.warnedUnresolvedRoots.has(root)) {\n this.warnedUnresolvedRoots.add(root);\n logger.warn(\n `⚠️ Ignoring allowed file root \"${root}\": it does not resolve to an existing directory on this system.`,\n );\n }\n }\n return expanded;\n }\n\n /**\n * Warns that `allowedRoots` mode is active but grants nothing, which blocks\n * all local file access. Emitted once per policy instance.\n */\n private warnUnavailableAllowlist(): void {\n if (this.hasWarnedUnavailableAllowlist) return;\n this.hasWarnedUnavailableAllowlist = true;\n\n // Operator-facing log: naming the configured entries is safe here and is\n // the fastest way to see why the allowlist came up empty.\n const configured = this.security.fileAccess.allowedRoots;\n const cause =\n configured.length === 0\n ? \"no roots are configured\"\n : `none of the configured roots (${configured.join(\", \")}) exist on this system`;\n logger.warn(\n `⚠️ Local file access is limited to configured roots, but ${cause}, so all file:// indexing is blocked. ` +\n `See ${FILE_ACCESS_DOCS} to configure the allowed roots.`,\n );\n }\n\n /**\n * Logs the roots that local file access is limited to. Emitted once per policy\n * instance, alongside the first out-of-root rejection.\n */\n private logConfiguredRoots(roots: string[]): void {\n if (this.hasLoggedConfiguredRoots) return;\n this.hasLoggedConfiguredRoots = true;\n\n logger.warn(`⚠️ Local file access is limited to: ${roots.join(\", \")}`);\n }\n\n private async findContainingRoot(\n accessPath: string,\n roots: string[],\n followSymlinks: boolean,\n ): Promise<string | null> {\n const resolvedAccessPath = await resolveContainmentPath(accessPath, followSymlinks);\n for (const root of roots) {\n const resolvedRoot = await resolveContainmentPath(root, followSymlinks);\n if (pathContains(resolvedRoot, resolvedAccessPath)) {\n return resolvedRoot;\n }\n }\n return null;\n }\n}\n\nasync function resolveAddresses(\n hostname: string,\n): Promise<Array<{ address: string; family: number }>> {\n try {\n const result = await lookup(hostname, { all: true, verbatim: true });\n return Array.isArray(result) ? result : [];\n } catch {\n return [];\n }\n}\n\nfunction normalizeHostname(hostname: string): string {\n return hostname.toLowerCase().replace(/^\\[(.*)]$/, \"$1\");\n}\n\nfunction looksLikeIpLiteral(hostname: string): boolean {\n return hostname.includes(\":\") || /^\\d+(?:\\.\\d+){0,3}$/.test(hostname);\n}\n\nasync function findSymlinkInPath(targetPath: string): Promise<string | null> {\n const resolved = path.resolve(targetPath);\n const root = path.parse(resolved).root;\n const relative = path.relative(root, resolved);\n const segments = relative.split(path.sep).filter(Boolean);\n let current = root;\n\n for (const segment of segments) {\n current = path.join(current, segment);\n const stats = await fs.lstat(current).catch(() => null);\n if (stats?.isSymbolicLink()) {\n return current;\n }\n }\n\n return null;\n}\n\n/**\n * Converts a file URL into a local filesystem path while preserving legacy leniency.\n */\nexport function fileUrlToPathLoose(url: string): string {\n let filePath = url.replace(/^file:\\/\\/\\/?/, \"\");\n filePath = decodeURIComponent(filePath);\n\n if (!filePath.startsWith(\"/\") && process.platform !== \"win32\") {\n filePath = `/${filePath}`;\n }\n\n return filePath;\n}\n\nconst USER_DIR_TOKENS: Record<string, string> = {\n $DOCUMENTS: \"Documents\",\n $DOWNLOADS: \"Downloads\",\n $DESKTOP: \"Desktop\",\n};\n\nconst ROOT_TOKENS = new Set([\"$HOME\", \"$CWD\", ...Object.keys(USER_DIR_TOKENS)]);\n\n/**\n * Describes why an `allowedRoots` allowlist grants no access, for an error that\n * also reaches MCP clients and the web UI.\n *\n * Configured tokens are named because they are fixed vocabulary that says\n * nothing about the host. Literal paths are only counted: even a path that does\n * not exist reveals the layout an operator intended, so `/mnt/acme-secrets/docs`\n * must not travel back to a caller.\n *\n * Today `expandConfiguredRoot` resolves literal paths unconditionally, so only\n * tokens reach this function and the count stays at zero. The branch guards the\n * day that changes — validating literal roots must not start leaking them.\n */\nfunction describeUnavailableRoots(configured: string[]): string {\n if (configured.length === 0) {\n return \"no roots are configured\";\n }\n\n const tokens = configured.filter((root) => ROOT_TOKENS.has(root));\n const literalCount = configured.length - tokens.length;\n const parts: string[] = [];\n if (tokens.length > 0) {\n parts.push(`${tokens.join(\", \")} did not resolve`);\n }\n if (literalCount > 0) {\n parts.push(`${literalCount} configured path(s) do not exist`);\n }\n return `none of its entries are available on this system (${parts.join(\"; \")})`;\n}\n\n/**\n * Expands user-facing configured root tokens into concrete filesystem paths.\n *\n * Supported tokens:\n * - `$HOME` — the user's home directory (broad; grants access to dotfiles).\n * - `$DOCUMENTS`, `$DOWNLOADS`, `$DESKTOP` — standard user folders. Resolve to\n * `<home>/<Folder>` if that directory exists, otherwise null so the token\n * denies rather than silently granting an unexpected path.\n * - `$CWD` — the process's current working directory. Useful for CLI use.\n *\n * Any other value is treated as a literal filesystem path and absolute-resolved.\n * Returning `null` means the token could not be resolved on this platform or\n * account and therefore grants no access by itself.\n */\nexport async function expandConfiguredRoot(root: string): Promise<string | null> {\n if (root === \"$HOME\") {\n const homeDir = os.homedir();\n return homeDir ? path.resolve(homeDir) : null;\n }\n\n if (root === \"$CWD\") {\n return path.resolve(process.cwd());\n }\n\n const subdir = USER_DIR_TOKENS[root];\n if (subdir !== undefined) {\n const homeDir = os.homedir();\n if (!homeDir) {\n return null;\n }\n const candidate = path.join(homeDir, subdir);\n const stats = await fs.stat(candidate).catch(() => null);\n if (!stats?.isDirectory()) {\n return null;\n }\n return path.resolve(candidate);\n }\n\n return path.resolve(root);\n}\n\nasync function resolveArchiveAwarePath(filePath: string): Promise<{\n archivePath: string | null;\n virtualArchivePath: string | null;\n}> {\n let currentPath = filePath;\n while (\n currentPath !== \"/\" &&\n currentPath !== \".\" &&\n path.dirname(currentPath) !== currentPath\n ) {\n const stats = await fs.lstat(currentPath).catch(() => null);\n if (stats?.isFile() && looksLikeArchivePath(currentPath)) {\n const virtualArchivePath = filePath\n .substring(currentPath.length)\n .replace(/^\\/+/, \"\")\n .replace(/^\\\\+/, \"\");\n return {\n archivePath: currentPath,\n virtualArchivePath: virtualArchivePath || null,\n };\n }\n if (stats) {\n return { archivePath: null, virtualArchivePath: null };\n }\n currentPath = path.dirname(currentPath);\n }\n\n return { archivePath: null, virtualArchivePath: null };\n}\n\nasync function resolveContainmentPath(\n targetPath: string,\n followSymlinks: boolean,\n): Promise<string> {\n if (!followSymlinks) {\n return path.resolve(targetPath);\n }\n\n return fs.realpath(targetPath).catch(() => path.resolve(targetPath));\n}\n\nfunction looksLikeArchivePath(filePath: string): boolean {\n return ARCHIVE_EXTENSIONS.has(path.extname(filePath).toLowerCase());\n}\n\nfunction pathContains(root: string, candidate: string): boolean {\n if (root === candidate) {\n return true;\n }\n\n const relative = path.relative(root, candidate);\n return relative !== \"\" && !relative.startsWith(\"..\") && !path.isAbsolute(relative);\n}\n\n/**\n * Returns true if any path segment strictly below `matchedRoot` starts with a\n * dot. When `matchedRoot` is null (e.g. `unrestricted` mode with no explicit\n * containing root), the entire absolute path is checked. The matched root\n * itself is treated as opt-in and never contributes to the hidden check, so\n * configuring an allowed root like `/Users/x/.config/docs` does not\n * self-reject because its absolute path contains `.config`.\n */\nfunction hasHiddenSegmentBelowRoot(\n targetPath: string,\n matchedRoot: string | null,\n): boolean {\n const resolved = path.resolve(targetPath);\n let segments: string[];\n if (matchedRoot) {\n const resolvedRoot = path.resolve(matchedRoot);\n if (resolved === resolvedRoot) return false;\n const relative = path.relative(resolvedRoot, resolved);\n if (!relative || relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n // Target is outside the matched root — fall back to the strict check\n // to remain defensive.\n segments = resolved.split(path.sep).filter(Boolean);\n } else {\n segments = relative.split(path.sep).filter(Boolean);\n }\n } else {\n segments = resolved.split(path.sep).filter(Boolean);\n }\n return segments.some((segment) => segment.startsWith(\".\"));\n}\n\nfunction hasHiddenArchiveSegment(archivePath: string): boolean {\n return archivePath\n .split(/[\\\\/]+/)\n .filter(Boolean)\n .some((segment) => segment.startsWith(\".\"));\n}\n","/**\n * Recognition of bot-protection challenge pages that a site serves in place of\n * the requested document, with a success status.\n */\n\n/**\n * How much of a document is inspected. Challenge pages are a few kilobytes and\n * carry their markers in the head, so a documentation page that merely\n * mentions them further down is not mistaken for one.\n */\nconst SCAN_LIMIT = 64 * 1024;\n\n/** The title of Fastly's client challenge page. */\nconst FASTLY_CHALLENGE_TITLE = /<title>\\s*Client Challenge\\s*<\\/title>/i;\n\n/** The path prefix Fastly serves the challenge's scripts and assets from. */\nconst FASTLY_CHALLENGE_ASSET_PATH = \"/_fs-ch-\";\n\n/**\n * Detects a challenge page that answered a request in place of the document.\n *\n * Recognizes Fastly's client challenge (served by pypi.org, among others): a\n * page titled \"Client Challenge\" whose scripts load from `/_fs-ch-<id>/`. It is\n * served with status 200 and stays in place in a headless browser.\n *\n * @param html The HTML as served, or as rendered by a browser.\n * @returns The challenge type to report in a `ChallengeError`, or null when the\n * document is not a known challenge page.\n */\nexport function detectChallengePage(html: string | Buffer): string | null {\n const head =\n typeof html === \"string\"\n ? html.slice(0, SCAN_LIMIT)\n : html.subarray(0, SCAN_LIMIT).toString(\"utf-8\");\n\n if (FASTLY_CHALLENGE_TITLE.test(head) && head.includes(FASTLY_CHALLENGE_ASSET_PATH)) {\n return \"fastly\";\n }\n return null;\n}\n","import { HeaderGenerator, type HeaderGeneratorOptions } from \"header-generator\";\n\n/**\n * Generates realistic browser-like HTTP headers to help avoid bot detection.\n * Uses the `header-generator` library for header generation.\n */\nexport class FingerprintGenerator {\n private headerGenerator: HeaderGenerator;\n\n /**\n * Creates an instance of FingerprintGenerator.\n * @param options Optional configuration for the header generator.\n */\n constructor(options?: Partial<HeaderGeneratorOptions>) {\n // Default options for a broad range of realistic headers\n const defaultOptions: Partial<HeaderGeneratorOptions> = {\n browsers: [{ name: \"chrome\", minVersion: 100 }, \"firefox\", \"safari\"],\n devices: [\"desktop\", \"mobile\"],\n operatingSystems: [\"windows\", \"linux\", \"macos\", \"android\", \"ios\"],\n locales: [\"en-US\", \"en\"],\n httpVersion: \"2\",\n };\n\n this.headerGenerator = new HeaderGenerator({\n ...defaultOptions,\n ...options,\n });\n }\n\n /**\n * Generates a set of realistic HTTP headers.\n * @returns A set of realistic HTTP headers.\n */\n generateHeaders(): Record<string, string> {\n return this.headerGenerator.getHeaders();\n }\n}\n","/**\n * User agent browser contexts fall back to when no caller or fingerprint value\n * is available. Bump the Chrome version when it starts looking implausibly old\n * to the anti-bot heuristics this exists to satisfy.\n */\nexport const DEFAULT_BROWSER_USER_AGENT =\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36\";\n\n/**\n * Reads a header by name, ignoring case.\n *\n * HTTP header names are case-insensitive, but caller-supplied headers arrive as\n * a plain object, so `headers[\"User-Agent\"]` misses a caller who wrote\n * `user-agent`.\n *\n * @param headers Caller-supplied request headers.\n * @param name The header name to look up.\n * @returns The matching value, or undefined when absent.\n */\nexport function getHeader(\n headers: Record<string, string> | undefined,\n name: string,\n): string | undefined {\n if (!headers) {\n return undefined;\n }\n const target = name.toLowerCase();\n for (const [header, value] of Object.entries(headers)) {\n if (header.toLowerCase() === target) {\n return value;\n }\n }\n return undefined;\n}\n\n/**\n * Connection-level headers, which the client that opens a connection sets for\n * itself. Chromium refuses to take them from a page: a navigation that carries\n * one fails with `net::ERR_INVALID_ARGUMENT`. Generated Firefox fingerprints\n * include `TE: trailers`, and a few include `Connection: keep-alive`.\n */\nconst CONNECTION_HEADERS = new Set([\n \"connection\",\n \"content-length\",\n \"cookie2\",\n \"host\",\n \"keep-alive\",\n \"proxy-connection\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n]);\n\n/**\n * Returns headers without the connection-level ones.\n *\n * A generated fingerprint copies a browser's headers, connection-level ones\n * included. The HTTP client that sends the request manages its own connection\n * and sets these itself: a copied `Connection: keep-alive` asks the server to\n * hold open a connection the client may never reuse.\n *\n * @param headers Request headers, such as a generated fingerprint.\n * @returns The headers minus any connection-level entry, in any letter case.\n */\nexport function withoutConnectionHeaders(\n headers: Record<string, string>,\n): Record<string, string> {\n return Object.fromEntries(\n Object.entries(headers).filter(\n ([header]) => !CONNECTION_HEADERS.has(header.toLowerCase()),\n ),\n );\n}\n\n/**\n * Returns headers without the ones Chromium sets for itself.\n *\n * A browser sets the `Sec-Fetch-*` family with values that fit each request: a\n * script gets `Sec-Fetch-Dest: script`, not the `document` of the page that\n * loads it. While Playwright intercepts requests, Chromium fails every\n * sub-resource request that carries an overridden one with\n * `net::ERR_INVALID_ARGUMENT`. Connection-level headers, such as `TE` or\n * `Transfer-Encoding`, belong to the browser's own connections, and Chromium\n * fails the navigation itself when a page asks for one.\n *\n * @param headers Request headers, such as a generated fingerprint.\n * @returns The headers minus any `Sec-Fetch-*` or connection-level entry, in\n * any letter case.\n */\nexport function withoutBrowserManagedHeaders(\n headers: Record<string, string>,\n): Record<string, string> {\n return Object.fromEntries(\n Object.entries(withoutConnectionHeaders(headers)).filter(\n ([header]) => !header.toLowerCase().startsWith(\"sec-fetch-\"),\n ),\n );\n}\n","/**\n * Waits for an operation, rejecting if it takes longer than the given time.\n * The operation itself keeps running; only the wait is bounded.\n *\n * @param operation - The promise to wait for.\n * @param timeoutMs - How long to wait, in milliseconds.\n * @param description - Names the operation in the timeout error.\n * @returns The operation's result.\n */\nexport async function withTimeout<T>(\n operation: Promise<T>,\n timeoutMs: number,\n description: string,\n): Promise<T> {\n let timeout: NodeJS.Timeout | undefined;\n try {\n return await Promise.race([\n operation,\n new Promise<T>((_resolve, reject) => {\n timeout = setTimeout(() => {\n reject(new Error(`${description} timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n }),\n ]);\n } finally {\n if (timeout) {\n clearTimeout(timeout);\n }\n }\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { type Browser, chromium, type LaunchOptions } from \"playwright\";\nimport { ScraperAccessPolicy } from \"../../utils/accessPolicy\";\nimport type { AppConfig } from \"../../utils/config\";\nimport { logger } from \"../../utils/logger\";\nimport { withTimeout } from \"../../utils/timeout\";\n\n/**\n * Process IDs of the browsers `ManagedBrowser.launch()` started. Playwright's\n * `Browser` does not expose its process, so the ID is read over CDP at launch,\n * while the browser still answers.\n */\nconst browserPids = new WeakMap<Browser, number>();\n\n/**\n * One headless Chromium that the browser fetcher and the HTML renderer can\n * share, so a scrape runs a single browser process.\n *\n * The browser is launched on first use and launched again after it exits;\n * callers that ask at the same time share one launch. Closing is safe to\n * repeat and does not stop later use: the next `get()` launches a new one.\n *\n * Every browser it hands out checks the redirects Chromium follows against the\n * scraper's access policy (see `blockDisallowedRedirects`).\n */\nexport class ManagedBrowser {\n private browser: Browser | null = null;\n private launching: Promise<Browser> | null = null;\n private readonly closeTimeoutMs: number;\n private readonly accessPolicy: ScraperAccessPolicy;\n\n /**\n * @param scraperConfig - Scraper settings (close timeout, network policy).\n */\n constructor(scraperConfig: AppConfig[\"scraper\"]) {\n this.closeTimeoutMs = scraperConfig.pageTimeoutMs;\n this.accessPolicy = new ScraperAccessPolicy(scraperConfig.security);\n }\n\n /**\n * Tells whether `browser` is still the one `get()` hands out: connected, and\n * not retired, closed or replaced. A retired browser stops being current at\n * once, before Chromium reports it disconnected.\n *\n * @param browser - A browser this instance handed out earlier.\n */\n isCurrent(browser: Browser): boolean {\n return this.browser === browser && browser.isConnected();\n }\n\n /**\n * Returns a connected browser, launching one on first use and again after\n * Chromium has exited. Concurrent callers share a single launch.\n */\n async get(): Promise<Browser> {\n if (this.browser?.isConnected()) {\n return this.browser;\n }\n\n this.launching ??= this.replaceBrowser().finally(() => {\n this.launching = null;\n });\n return this.launching;\n }\n\n /**\n * Closes the given browser, killing its process if it does not close in\n * time. Use it for a browser that may be stuck; when it is the current one,\n * the next `get()` launches a new browser.\n *\n * @param browser - The browser to close.\n * @param reason - Why it is closed, for the logs.\n */\n async retire(browser: Browser, reason: string): Promise<void> {\n if (this.browser === browser) {\n this.browser = null;\n }\n\n logger.debug(`Closing Playwright browser (${reason})`);\n try {\n // A disconnected browser is closed too, which reaps its process.\n await withTimeout(browser.close(), this.closeTimeoutMs, \"Playwright browser close\");\n } catch (error) {\n logger.warn(`⚠️ Error closing Playwright browser (${reason}): ${error}`);\n ManagedBrowser.killProcess(browser, reason);\n }\n }\n\n /**\n * Closes the browser, including one whose launch is still in flight.\n */\n async close(): Promise<void> {\n await this.launching?.catch(() => undefined);\n if (this.browser) {\n await this.retire(this.browser, \"shutdown\");\n }\n }\n\n private async replaceBrowser(): Promise<Browser> {\n if (this.browser) {\n logger.warn(\"⚠️ Browser disconnected, launching a new one\");\n // Reap the dead process without holding up the launch.\n void this.retire(this.browser, \"disconnected\");\n } else {\n logger.debug(\"Launching browser...\");\n }\n\n const browser = await ManagedBrowser.launch();\n try {\n await this.blockDisallowedRedirects(browser);\n } catch (error) {\n // Without the guard, a redirect could reach a blocked address.\n await this.retire(browser, \"redirect guard failed\");\n throw error;\n }\n this.browser = browser;\n return browser;\n }\n\n /**\n * Blocks the redirects the access policy denies, in every page, frame and\n * worker of the browser.\n *\n * Playwright's request routing only sees the first request of a redirect\n * chain: Chromium follows redirects itself, so an allowed URL could\n * otherwise send a page, a script or a form post on to a private address.\n * A Fetch session on the browser target pauses every hop, including those of\n * cross-site iframes that run in their own process, so the hops are checked\n * there. First requests are left to the routes of the browser's users.\n *\n * @param browser - The browser to guard, before any page opens in it.\n */\n private async blockDisallowedRedirects(browser: Browser): Promise<void> {\n const session = await browser.newBrowserCDPSession();\n session.on(\"Fetch.requestPaused\", (event) => {\n const resolve = async () => {\n const blocked =\n event.redirectedRequestId !== undefined &&\n !(await this.isRequestAllowed(event.request.url));\n if (!blocked) {\n await session.send(\"Fetch.continueRequest\", { requestId: event.requestId });\n return;\n }\n logger.debug(`Blocked redirect to ${event.request.url}`);\n await session.send(\"Fetch.failRequest\", {\n requestId: event.requestId,\n errorReason: \"BlockedByClient\",\n });\n };\n // The request's page may close while it is paused.\n resolve().catch(() => undefined);\n });\n await session.send(\"Fetch.enable\", { patterns: [{ urlPattern: \"*\" }] });\n }\n\n private async isRequestAllowed(url: string): Promise<boolean> {\n try {\n await this.accessPolicy.assertNetworkUrlAllowed(url);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Launches a headless Chromium for scraping.\n *\n * Without an explicit executable, Playwright launches its headless shell.\n * Installs made with `playwright install --no-shell` leave the shell out and\n * have only the full build, so a missing shell falls back to that.\n *\n * @returns The launched browser; the caller closes it.\n */\n static async launch(): Promise<Browser> {\n const options: LaunchOptions = {\n headless: true,\n executablePath: ManagedBrowser.resolveChromiumExecutablePath(),\n args: [\n \"--no-sandbox\",\n \"--disable-setuid-sandbox\",\n \"--disable-dev-shm-usage\",\n \"--disable-blink-features=AutomationControlled\",\n ],\n };\n\n let browser: Browser;\n try {\n browser = await chromium.launch(options);\n } catch (error) {\n const missingExecutable =\n error instanceof Error && error.message.includes(\"Executable doesn't exist\");\n if (options.executablePath || !missingExecutable) {\n throw error;\n }\n logger.debug(\"Playwright's headless shell is not installed; using the full build\");\n browser = await chromium.launch({ ...options, channel: \"chromium\" });\n }\n\n await ManagedBrowser.recordProcessId(browser);\n return browser;\n }\n\n /**\n * Remembers the browser's process ID, so a browser that will not close can\n * still be killed. Best effort: without an ID, the kill is skipped.\n */\n private static async recordProcessId(browser: Browser): Promise<void> {\n try {\n const session = await browser.newBrowserCDPSession();\n const { processInfo } = await session.send(\"SystemInfo.getProcessInfo\");\n await session.detach();\n const pid = processInfo.find((info) => info.type === \"browser\")?.id;\n if (pid) {\n browserPids.set(browser, pid);\n }\n } catch (error) {\n logger.debug(`Could not read the browser process ID: ${error}`);\n }\n }\n\n /**\n * Tells whether Playwright's own Chromium is installed: the headless shell a\n * launch uses by default, or the full build it falls back to.\n *\n * Playwright only reports the full build's path. The shell of the same\n * revision sits next to it, in `chromium_headless_shell-<revision>`, and\n * Playwright marks a finished download with an `INSTALLATION_COMPLETE` file.\n *\n * @returns True when a launch without an explicit executable can succeed.\n */\n static isPlaywrightChromiumInstalled(): boolean {\n let fullBuildPath: string;\n try {\n fullBuildPath = chromium.executablePath();\n } catch {\n // executablePath() throws when no managed build is registered at all.\n return false;\n }\n if (fs.existsSync(fullBuildPath)) {\n return true;\n }\n\n // Walk up from the executable to its `chromium-<revision>` folder.\n for (let dir = fullBuildPath; path.dirname(dir) !== dir; dir = path.dirname(dir)) {\n const revision = /^chromium-(\\d+)$/.exec(path.basename(dir))?.[1];\n if (revision) {\n const shellDir = path.join(\n path.dirname(dir),\n `chromium_headless_shell-${revision}`,\n );\n return fs.existsSync(path.join(shellDir, \"INSTALLATION_COMPLETE\"));\n }\n }\n return false;\n }\n\n /**\n * Resolves the Chromium binary to launch.\n *\n * Playwright's own managed build is pinned to the installed Playwright\n * version and is always preferred. A distro Chromium is only a fallback for\n * environments that skipped the browser download, since an arbitrary system\n * build can drift from the protocol Playwright expects.\n *\n * @returns An explicit executable path, or undefined to let Playwright choose.\n */\n private static resolveChromiumExecutablePath(): string | undefined {\n const configuredPath = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH;\n if (configuredPath) {\n return configuredPath;\n }\n\n if (ManagedBrowser.isPlaywrightChromiumInstalled()) {\n return undefined;\n }\n\n const systemPath = [\n \"/usr/lib/chromium/chromium\",\n \"/usr/bin/chromium\",\n \"/usr/bin/chromium-browser\",\n ].find((candidate) => fs.existsSync(candidate));\n\n if (systemPath) {\n logger.debug(\n `Playwright's managed Chromium is unavailable; using system Chromium at ${systemPath}`,\n );\n }\n return systemPath;\n }\n\n private static killProcess(browser: Browser, reason: string): void {\n const pid = browserPids.get(browser);\n if (!pid) {\n logger.warn(`⚠️ Cannot kill the Playwright browser, its process ID is unknown`);\n return;\n }\n\n logger.warn(`⚠️ Force killing Playwright browser process pid=${pid}: ${reason}`);\n try {\n process.kill(pid, \"SIGKILL\");\n } catch (error) {\n // ESRCH: the process has already exited.\n logger.warn(\n `⚠️ Failed to force kill Playwright browser process pid=${pid}: ${error}`,\n );\n }\n }\n}\n","/**\n * Semantic status of a fetch operation, abstracting HTTP status codes\n * into meaningful states for content processing.\n */\nexport enum FetchStatus {\n /**\n * Content was successfully fetched (HTTP 200 or new file).\n * The content field will contain the fetched data.\n */\n SUCCESS = \"success\",\n\n /**\n * Content has not been modified since the last fetch (HTTP 304).\n * The content field will be empty. Occurs when etag is provided\n * in FetchOptions and matches the server's current ETag.\n */\n NOT_MODIFIED = \"not_modified\",\n\n /**\n * The resource was not found (HTTP 404 or file doesn't exist).\n * The content field will be empty. In refresh operations,\n * this indicates the page should be removed from the index.\n */\n NOT_FOUND = \"not_found\",\n\n /**\n * The resource was fetched but its content type cannot be processed by any\n * configured pipeline, so the body was abandoned without being read.\n * The content field will be empty. This is neither a success nor a failure:\n * it produces no page and does not count toward the child-page failure rate.\n */\n SKIPPED = \"skipped\",\n}\n\n/**\n * Raw content fetched from a source before processing.\n * Includes metadata about the content for proper processing.\n */\nexport interface RawContent {\n /** Raw content as string or buffer */\n content: string | Buffer;\n /**\n * MIME type of the content (e.g., \"text/html\", \"application/json\").\n * Does not include parameters like charset.\n */\n mimeType: string;\n /**\n * Character set of the content (e.g., \"utf-8\"), extracted from Content-Type header.\n */\n charset?: string;\n /**\n * Content encoding (e.g., \"gzip\", \"deflate\"), from Content-Encoding header.\n */\n encoding?: string;\n /** Original source location */\n source: string;\n /**\n * ETag value for caching purposes.\n * For HTTP sources, this comes from the ETag header.\n * For local files, this is a hash of the last modified date.\n */\n etag?: string;\n /**\n * Last modified timestamp in ISO8601 format.\n * For HTTP sources, this comes from the Last-Modified header.\n * For local files, this is the file modification time.\n */\n lastModified?: string;\n /**\n * Semantic status of the fetch operation.\n * Abstracts HTTP status codes into meaningful states:\n * - SUCCESS: Content was fetched successfully\n * - NOT_MODIFIED: Content unchanged since last fetch (conditional request)\n * - NOT_FOUND: Resource doesn't exist (should be removed from index)\n */\n status: FetchStatus;\n}\n\n/**\n * Options for configuring content fetching behavior\n */\nexport interface FetchOptions {\n /** Maximum retry attempts for failed fetches */\n maxRetries?: number;\n /** Base delay between retries in milliseconds */\n retryDelay?: number;\n /** Additional headers for HTTP requests */\n headers?: Record<string, string>;\n /** Timeout in milliseconds */\n timeout?: number;\n /** AbortSignal for cancellation */\n signal?: AbortSignal;\n /** Whether to follow HTTP redirects (3xx responses) */\n followRedirects?: boolean;\n /**\n * ETag value for conditional requests.\n * When provided, the fetcher will include an If-None-Match header\n * and may return a 304 Not Modified response if content hasn't changed.\n */\n etag?: string | null;\n /** Internal-only allowlist roots for application-managed temporary files. */\n internalAllowedFileRoots?: string[];\n /**\n * Decides whether a response's content type is worth downloading.\n *\n * Supplied by the caller so the fetcher never needs to know about pipelines.\n * When provided, a response whose type is rejected is abandoned before its body\n * is read and reported as {@link FetchStatus.SKIPPED}. When omitted, no\n * content-type gating occurs and every successful response is read in full.\n */\n acceptsMimeType?: (mimeType: string) => boolean;\n}\n\n/**\n * Interface for fetching content from different sources\n */\nexport interface ContentFetcher {\n /**\n * Check if this fetcher can handle the given source\n */\n canFetch(source: string): boolean;\n\n /**\n * Fetch content from the source\n */\n fetch(source: string, options?: FetchOptions): Promise<RawContent>;\n}\n","import type { Browser, BrowserContext, Page } from \"playwright\";\nimport { ScraperAccessPolicy } from \"../../utils/accessPolicy\";\nimport type { AppConfig } from \"../../utils/config\";\nimport {\n AccessPolicyError,\n ChallengeError,\n HttpStatusError,\n RedirectError,\n ScraperError,\n} from \"../../utils/errors\";\nimport { logger } from \"../../utils/logger\";\nimport { MimeTypeUtils } from \"../../utils/mimeTypeUtils\";\nimport { detectChallengePage } from \"./challenge\";\nimport { FingerprintGenerator } from \"./FingerprintGenerator\";\nimport {\n DEFAULT_BROWSER_USER_AGENT,\n getHeader,\n withoutBrowserManagedHeaders,\n} from \"./headers\";\nimport { ManagedBrowser } from \"./ManagedBrowser\";\nimport {\n type ContentFetcher,\n type FetchOptions,\n FetchStatus,\n type RawContent,\n} from \"./types\";\n\n/**\n * Maximum redirects to follow via the request API. Matches Playwright's own\n * default (20) — redirects are followed manually only so every hop can be\n * revalidated against the access policy, not to change the allowed depth.\n */\nconst MAX_REQUEST_REDIRECTS = 20;\n\n/**\n * Fetches content using a headless browser (Playwright).\n * This fetcher can handle JavaScript-heavy pages and bypass anti-scraping measures.\n */\nexport class BrowserFetcher implements ContentFetcher {\n private readonly managedBrowser: ManagedBrowser;\n private fingerprintGenerator: FingerprintGenerator;\n private readonly defaultTimeoutMs: number;\n private readonly accessPolicy: ScraperAccessPolicy;\n\n /**\n * @param scraperConfig - Scraper settings (timeouts, network policy).\n * @param managedBrowser - The browser to fetch with; pass one to share it\n * with other users, such as the HTML renderer.\n */\n constructor(\n scraperConfig: AppConfig[\"scraper\"],\n managedBrowser = new ManagedBrowser(scraperConfig),\n ) {\n this.managedBrowser = managedBrowser;\n this.defaultTimeoutMs = scraperConfig.browserTimeoutMs;\n this.fingerprintGenerator = new FingerprintGenerator();\n this.accessPolicy = new ScraperAccessPolicy(scraperConfig.security);\n }\n\n canFetch(source: string): boolean {\n return source.startsWith(\"http://\") || source.startsWith(\"https://\");\n }\n\n private async isRequestAllowed(url: string): Promise<boolean> {\n try {\n await this.accessPolicy.assertNetworkUrlAllowed(url);\n return true;\n } catch {\n return false;\n }\n }\n\n async fetch(source: string, options?: FetchOptions): Promise<RawContent> {\n try {\n options?.signal?.throwIfAborted();\n await this.accessPolicy.assertNetworkUrlAllowed(source);\n\n const browser = await this.managedBrowser.get();\n try {\n return await this.fetchWithBrowser(browser, source, options);\n } catch (error) {\n if (this.managedBrowser.isCurrent(browser) || options?.signal?.aborted) {\n throw error;\n }\n // The browser went away under this page: Chromium exited (e.g. under\n // memory pressure), or another user retired it. The page never got a\n // fair attempt, so give it one more on the current browser.\n logger.warn(`⚠️ Browser closed while fetching ${source}, retrying once`);\n return await this.fetchWithBrowser(\n await this.managedBrowser.get(),\n source,\n options,\n );\n }\n } catch (error) {\n if (options?.signal?.aborted) {\n throw new ScraperError(\"Browser fetch cancelled\", false);\n }\n\n // Preserve already-typed ScraperErrors (and their isRetryable flag) thrown\n // by fetchWithBrowser or fetchViaRequest, rather than re-wrapping them\n // into a new, always-non-retryable error.\n if (error instanceof ScraperError) {\n throw error;\n }\n\n logger.error(`❌ Browser fetch failed for ${source}: ${error}`);\n throw new ScraperError(\n `Browser fetch failed for ${source}: ${error instanceof Error ? error.message : String(error)}`,\n false,\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n /**\n * Loads `source` in a fresh context of the given browser.\n *\n * @param browser - The browser to open the page in.\n * @param source - The URL to fetch.\n * @param options - Headers, timeout and redirect policy for the fetch.\n * @returns The fetched raw content.\n */\n private async fetchWithBrowser(\n browser: Browser,\n source: string,\n options?: FetchOptions,\n ): Promise<RawContent> {\n let page: Page | null = null;\n let browserContext: BrowserContext | null = null;\n // Aborting closes the context, which ends a navigation in progress instead\n // of letting it run until it times out.\n const closeOnAbort = (): void => {\n void browserContext?.close().catch(() => undefined);\n };\n options?.signal?.addEventListener(\"abort\", closeOnAbort, { once: true });\n\n try {\n const fingerprintHeaders = this.fingerprintGenerator.generateHeaders();\n browserContext = await browser.newContext({\n userAgent:\n getHeader(options?.headers, \"user-agent\") ||\n fingerprintHeaders[\"user-agent\"] ||\n DEFAULT_BROWSER_USER_AGENT,\n ignoreHTTPSErrors: this.accessPolicy.shouldAllowInvalidTls(\n \"https://browser-context.local\",\n ),\n });\n // An abort before the context existed had nothing to close.\n options?.signal?.throwIfAborted();\n page = await browserContext.newPage();\n await page.setViewportSize({ width: 1920, height: 1080 });\n\n await page.route(\"**/*\", async (route) => {\n const requestUrl = route.request().url();\n if (!(await this.isRequestAllowed(requestUrl))) {\n return await route.abort(\"blockedbyclient\");\n }\n\n return await route.continue();\n });\n // The browser fails redirects to blocked addresses (see ManagedBrowser);\n // remember which hop stopped the navigation, to name it in the error.\n let blockedNavigation: string | undefined;\n page.on(\"requestfailed\", (request) => {\n if (\n request.frame() === page?.mainFrame() &&\n request.isNavigationRequest() &&\n request.failure()?.errorText.includes(\"ERR_BLOCKED_BY_CLIENT\")\n ) {\n blockedNavigation = request.url();\n }\n });\n\n // Compose the browser-like fingerprint headers used both for the page's\n // own navigation and (if needed) the non-navigable request-API fallback,\n // so the two look like the same client to anti-bot checks. Like\n // HttpFetcher, it keeps the fingerprint's HTML-first Accept.\n const requestHeaders: Record<string, string> = {\n ...fingerprintHeaders,\n ...options?.headers,\n };\n // Chromium sets the Sec-Fetch-* and connection-level headers itself;\n // overriding them would make it fail the page's scripts, styles and other\n // sub-resources, or the navigation itself. The request API is\n // Playwright's own client, so it keeps them.\n await page.setExtraHTTPHeaders(withoutBrowserManagedHeaders(requestHeaders));\n\n // Set timeout\n const timeout = options?.timeout || this.defaultTimeoutMs;\n\n // Navigate to the page. Gate on \"load\" rather than \"networkidle\": many\n // sites keep background connections open indefinitely (analytics,\n // Cloudflare telemetry, websockets), so \"networkidle\" never settles and\n // page.goto times out even though the document is already available.\n logger.debug(`Navigating to ${source} with browser...`);\n // page.goto() returns the *first* main-document response. A challenge\n // page typically navigates again once it clears, so the status that\n // matters is the last one the main frame received.\n let lastMainFrameResponse: Awaited<ReturnType<typeof page.goto>> = null;\n page.on(\"response\", (candidate) => {\n const request = candidate.request();\n if (request.isNavigationRequest() && request.frame() === page?.mainFrame()) {\n lastMainFrameResponse = candidate;\n }\n });\n let response: Awaited<ReturnType<typeof page.goto>>;\n try {\n response = await page.goto(source, { waitUntil: \"load\", timeout });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (/ERR_BLOCKED_BY_CLIENT/.test(message)) {\n throw new AccessPolicyError(\n `Security policy blocked network access to ${blockedNavigation ?? source}`,\n );\n }\n // Non-navigable resources (Markdown, JSON, binary files, ...) make the\n // browser begin a download, so page.goto rejects with\n // ERR_INVALID_ARGUMENT / ERR_ABORTED, or with \"Download is starting\"\n // while requests are routed. Fetch those through the context's request\n // API instead (see fetchViaRequest): it shares cookies — so any\n // anti-bot clearance carries over — but does not try to render them.\n // A navigation cut off because its page or browser is going away (for\n // example, the browser was replaced) is reported as ERR_ABORTED too;\n // that is no download, so it is not fetched again here. Only a page\n // that went first says \"frame was detached\": a closed browser leaves\n // a bare ERR_ABORTED, so ask the browser itself.\n const goingAway =\n /frame was detached/i.test(message) || !this.managedBrowser.isCurrent(browser);\n if (\n !goingAway &&\n /ERR_INVALID_ARGUMENT|ERR_ABORTED|Download is starting/i.test(message)\n ) {\n return await this.fetchViaRequest(\n page,\n source,\n options,\n timeout,\n requestHeaders,\n );\n }\n throw error;\n }\n\n // Best-effort: give the network a moment to settle (e.g. so a JS\n // challenge can finish) but never fail the fetch if it never goes idle.\n await page\n .waitForLoadState(\"networkidle\", { timeout: Math.min(timeout, 5_000) })\n .catch(() => undefined);\n\n if (!response) {\n throw new ScraperError(`Failed to navigate to ${source}`, false);\n }\n\n // Check if we should follow redirects\n if (\n options?.followRedirects === false &&\n response.status() >= 300 &&\n response.status() < 400\n ) {\n const location = response.headers().location;\n if (location) {\n throw new RedirectError(source, location, response.status());\n }\n }\n\n // Get the final URL after any redirects\n const finalUrl = page.url();\n await this.accessPolicy.assertNetworkUrlAllowed(finalUrl);\n\n // If the browser did not get past the block, the error page it rendered\n // is not documentation — returning it SUCCESS would index the block page.\n // Mirrors the status check fetchViaRequest already performs.\n // A challenge navigates again once it clears, so everything downstream —\n // content type, body, etag — must come from the document that actually\n // ended up loaded, not from the one page.goto() first returned.\n response = lastMainFrameResponse ?? response;\n const finalStatus = response.status();\n if (finalStatus === 404) {\n logger.debug(`Browser navigation to ${source} returned 404`);\n return {\n content: Buffer.from(\"\"),\n mimeType: \"text/plain\",\n source: finalUrl,\n status: FetchStatus.NOT_FOUND,\n } satisfies RawContent;\n }\n if (finalStatus >= 400) {\n throw new HttpStatusError(\n `Browser navigation to ${source} returned status ${finalStatus}`,\n true,\n finalStatus,\n );\n }\n\n // Determine content type\n const contentType = response.headers()[\"content-type\"] || \"text/html\";\n const { mimeType, charset } = MimeTypeUtils.parseContentType(contentType);\n\n const content = MimeTypeUtils.isHtml(mimeType)\n ? await page.content()\n : await response.body();\n\n // A challenge the browser could not get past either is still on the page\n // after the load settled; its status alone does not give it away.\n const challengeType =\n typeof content === \"string\" ? detectChallengePage(content) : null;\n if (challengeType) {\n throw new ChallengeError(source, finalStatus, challengeType);\n }\n\n const contentBuffer = Buffer.isBuffer(content)\n ? content\n : Buffer.from(content, \"utf-8\");\n\n // Extract ETag header for caching\n const etag = response.headers().etag;\n\n return {\n content: contentBuffer,\n mimeType,\n charset,\n encoding: undefined, // Browser handles encoding automatically\n source: finalUrl,\n etag,\n status: FetchStatus.SUCCESS,\n } satisfies RawContent;\n } finally {\n options?.signal?.removeEventListener(\"abort\", closeOnAbort);\n await page?.unroute(\"**/*\").catch(() => undefined);\n await page?.close().catch(() => undefined);\n await browserContext?.close().catch(() => undefined);\n }\n }\n\n /**\n * Fetches a resource the browser cannot navigate to (Markdown, JSON, plain\n * text, ...). Loads the origin first so any JS/anti-bot challenge is solved\n * and clearance cookies are set on the shared context, then retrieves the\n * resource bytes via the context's request API (which reuses those cookies\n * but does not attempt to render the response as a document).\n *\n * @param page - The page whose context (and cookies) the request reuses.\n * @param source - The non-navigable resource URL to fetch.\n * @param options - The original fetch options (headers, redirect policy).\n * @param timeout - Navigation/request timeout in milliseconds.\n * @param headers - The composed fingerprint and caller headers, including\n * any Sec-Fetch-* or connection-level values among them. The page itself\n * leaves those to Chromium; the request-API call sends them as composed, so\n * it presents the same client identity as the browser that (potentially)\n * just solved a challenge.\n * @returns The fetched raw content.\n */\n private async fetchViaRequest(\n page: Page,\n source: string,\n options: FetchOptions | undefined,\n timeout: number,\n headers: Record<string, string>,\n ): Promise<RawContent> {\n const origin = new URL(source).origin;\n logger.debug(\n `Resource ${source} is not browser-navigable; clearing ${origin} then fetching via request API`,\n );\n // Visit a navigable page on the same origin so the browser can solve any JS\n // challenge and set clearance cookies; ignore failures since the request\n // below still returns a definitive status.\n await page\n .goto(origin, { waitUntil: \"load\", timeout })\n .then(() =>\n page\n .waitForLoadState(\"networkidle\", { timeout: Math.min(timeout, 5_000) })\n .catch(() => undefined),\n )\n .catch(() => undefined);\n\n const { response, finalUrl } = await this.requestWithValidatedRedirects(\n page,\n source,\n options,\n timeout,\n headers,\n );\n\n // Same semantics as the navigation path: a 404 is a definitive answer that\n // refresh uses to delete a stale page and that llms.txt seeds treat as\n // non-fatal, so it must not surface as a generic failure.\n if (response.status() === 404) {\n logger.debug(`Browser request for ${source} returned 404`);\n return {\n content: Buffer.from(\"\"),\n mimeType: \"text/plain\",\n source: finalUrl,\n status: FetchStatus.NOT_FOUND,\n } satisfies RawContent;\n }\n if (!response.ok()) {\n throw new HttpStatusError(\n `Browser request for ${source} returned status ${response.status()}`,\n true,\n response.status(),\n );\n }\n\n const contentType = response.headers()[\"content-type\"] || \"application/octet-stream\";\n const { mimeType, charset } = MimeTypeUtils.parseContentType(contentType);\n const content = Buffer.from(await response.body());\n\n // The origin visit above does not clear every challenge, and the request\n // then gets the challenge page in place of the resource.\n const challengeType = MimeTypeUtils.isHtml(mimeType)\n ? detectChallengePage(content)\n : null;\n if (challengeType) {\n throw new ChallengeError(source, response.status(), challengeType);\n }\n\n return {\n content,\n mimeType,\n charset,\n encoding: undefined,\n source: finalUrl,\n etag: response.headers().etag,\n status: FetchStatus.SUCCESS,\n } satisfies RawContent;\n }\n\n /**\n * Fetches `source` via the context's request API, following redirects\n * manually so every hop can be revalidated against the access policy before\n * it's followed — `page.request` bypasses the `page.route` handler that\n * guards browser-driven navigation, so this is the only SSRF check a\n * redirect target gets.\n *\n * @param page - The page whose context the request reuses.\n * @param source - The resource URL to fetch.\n * @param options - The original fetch options (redirect policy).\n * @param timeout - Request timeout in milliseconds, applied per hop.\n * @param headers - Headers to send with every hop (see `fetchViaRequest`).\n * @returns The final response and the URL it was fetched from.\n */\n private async requestWithValidatedRedirects(\n page: Page,\n source: string,\n options: FetchOptions | undefined,\n timeout: number,\n headers: Record<string, string>,\n ): Promise<{\n response: Awaited<ReturnType<Page[\"request\"][\"get\"]>>;\n finalUrl: string;\n }> {\n let currentUrl = source;\n\n for (let redirectCount = 0; ; redirectCount++) {\n const response = await page.request.get(currentUrl, {\n headers,\n maxRedirects: 0,\n timeout,\n });\n\n const status = response.status();\n const location = response.headers().location;\n if (status < 300 || status >= 400 || !location) {\n return { response, finalUrl: currentUrl };\n }\n\n if (options?.followRedirects === false) {\n throw new RedirectError(currentUrl, location, status);\n }\n\n if (redirectCount >= MAX_REQUEST_REDIRECTS) {\n throw new ScraperError(`Too many redirects while fetching ${source}`, false);\n }\n\n const redirectUrl = new URL(location, currentUrl).href;\n await this.accessPolicy.assertNetworkUrlAllowed(redirectUrl);\n currentUrl = redirectUrl;\n }\n }\n\n /**\n * Closes the browser this fetcher uses.\n */\n async close(): Promise<void> {\n await this.managedBrowser.close();\n }\n}\n","import crypto from \"node:crypto\";\nimport fs from \"node:fs/promises\";\nimport { fileUrlToPathLoose, ScraperAccessPolicy } from \"../../utils/accessPolicy\";\nimport type { AppConfig } from \"../../utils/config\";\nimport { ScraperError } from \"../../utils/errors\";\nimport { MimeTypeUtils } from \"../../utils/mimeTypeUtils\";\nimport {\n type ContentFetcher,\n type FetchOptions,\n FetchStatus,\n type RawContent,\n} from \"./types\";\n\n/**\n * Fetches content from local file system.\n */\nexport class FileFetcher implements ContentFetcher {\n private readonly accessPolicy: ScraperAccessPolicy | null;\n\n constructor(scraperConfig?: AppConfig[\"scraper\"]) {\n this.accessPolicy = scraperConfig\n ? new ScraperAccessPolicy(scraperConfig.security)\n : null;\n }\n\n canFetch(source: string): boolean {\n return source.startsWith(\"file://\");\n }\n\n /**\n * Fetches the content of a file given a file:// URL, decoding percent-encoded paths as needed.\n * Uses enhanced MIME type detection for better source code file recognition.\n * Supports conditional fetching via ETag comparison for efficient refresh operations.\n */\n async fetch(source: string, options?: FetchOptions): Promise<RawContent> {\n const filePath = this.accessPolicy\n ? (\n await this.accessPolicy.resolveFileAccess(\n source,\n options?.internalAllowedFileRoots,\n )\n ).filePath\n : fileUrlToPathLoose(source);\n\n try {\n const stats = await fs.stat(filePath);\n\n // Generate current ETag from last modified time\n const currentEtag = crypto\n .createHash(\"md5\")\n .update(stats.mtime.toISOString())\n .digest(\"hex\");\n\n // Check if file has been modified (ETag comparison)\n if (options?.etag && options.etag === currentEtag) {\n // File hasn't changed - return NOT_MODIFIED status\n return {\n content: Buffer.from(\"\"),\n mimeType: \"text/plain\",\n source,\n etag: currentEtag,\n lastModified: stats.mtime.toISOString(),\n status: FetchStatus.NOT_MODIFIED,\n };\n }\n\n // File is new or has been modified - read the content\n const content = await fs.readFile(filePath);\n\n // Use enhanced MIME type detection that properly handles source code files\n const detectedMimeType = MimeTypeUtils.detectMimeTypeFromPath(filePath);\n const mimeType = detectedMimeType || \"application/octet-stream\";\n\n return {\n content,\n mimeType,\n source,\n etag: currentEtag,\n lastModified: stats.mtime.toISOString(),\n status: FetchStatus.SUCCESS,\n // Don't assume charset for text files - let the pipeline detect it\n };\n } catch (error: unknown) {\n // Check for file not found error\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return {\n content: Buffer.from(\"\"),\n mimeType: \"text/plain\",\n source,\n status: FetchStatus.NOT_FOUND,\n };\n }\n // For all other errors, throw a ScraperError\n throw new ScraperError(\n `Failed to read file ${filePath}: ${\n (error as { message?: string }).message ?? \"Unknown error\"\n }`,\n false,\n error instanceof Error ? error : undefined,\n );\n }\n }\n}\n","export class PipelineError extends Error {\n constructor(\n message: string,\n public readonly cause?: Error,\n ) {\n super(message);\n this.name = this.constructor.name;\n if (cause?.stack) {\n this.stack = `${this.stack}\\nCaused by: ${cause.stack}`;\n }\n }\n}\n\nexport class PipelineStateError extends PipelineError {}\n\n/**\n * Error indicating that an operation was cancelled.\n */\nexport class CancellationError extends PipelineError {\n constructor(message = \"Operation cancelled\") {\n super(message);\n }\n}\n","/**\n * Per-host pause for servers that ask the scraper to slow down.\n *\n * A crawl runs several requests at once. When one of them is throttled, the\n * others would go on requesting the same host at full speed, so a throttle\n * pauses the host rather than the one request that met it.\n */\n\nimport { CancellationError } from \"../../pipeline/errors\";\n\n/**\n * The longest a host is paused for, whatever the server asks. A server asking\n * for an hour would otherwise park the crawl; capped, the request is retried\n * and fails if the server still refuses it.\n */\nexport const MAX_THROTTLE_DELAY_MS = 60_000;\n\n/**\n * Caps the doubling. Beyond this the pause is at its maximum anyway, and the\n * cap keeps a base delay of zero from multiplying into NaN.\n */\nconst MAX_BACKOFF_EXPONENT = 16;\n\n/** The pause state of one host. */\ninterface HostState {\n /** Epoch milliseconds before which no request is sent to the host. */\n resumeAt: number;\n /** Throttled responses since the host last answered a request normally. */\n strikes: number;\n /** Epoch milliseconds of the most recent throttled response. */\n throttledAt: number;\n}\n\n/**\n * Parses a `Retry-After` header into a delay.\n *\n * Accepts both forms RFC 9110 allows: delta-seconds (`120`) and an HTTP-date\n * (`Wed, 21 Oct 2015 07:28:00 GMT`). A date in the past means no delay.\n *\n * @param value The header value as the response carried it.\n * @param now The current time in epoch milliseconds.\n * @returns The delay in milliseconds, or undefined when the header is missing\n * or unreadable.\n */\nexport function parseRetryAfter(value: unknown, now = Date.now()): number | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n const trimmed = value.trim();\n if (/^\\d+$/.test(trimmed)) {\n return Number(trimmed) * 1000;\n }\n // Every HTTP-date form names the month. Without that check `Date.parse`\n // would read values such as \"-5\" or \"1.5\" as dates.\n const date = /[a-z]/i.test(trimmed) ? Date.parse(trimmed) : Number.NaN;\n return Number.isNaN(date) ? undefined : Math.max(0, date - now);\n}\n\n/**\n * Pauses every request to a host after the host throttles one of them.\n *\n * Shared by the fetchers of one crawl, so all of its workers wait out the same\n * pause. The pause doubles with each throttled response in a row and resets\n * once the host answers a request sent after the last throttle.\n */\nexport class HostBackoff {\n private readonly hosts = new Map<string, HostState>();\n\n /**\n * Waits until requests to the host of `url` may resume.\n *\n * @param url The URL about to be requested.\n * @param signal Aborts the wait.\n * @throws {CancellationError} When the signal aborts.\n */\n async wait(url: string, signal?: AbortSignal): Promise<void> {\n const host = hostOf(url);\n // Re-read after each sleep: another request may have extended the pause.\n for (\n let state = this.hosts.get(host);\n state && state.resumeAt > Date.now();\n state = this.hosts.get(host)\n ) {\n await sleep(state.resumeAt - Date.now(), signal);\n }\n }\n\n /**\n * Records a throttled response and pauses its host.\n *\n * Without a `Retry-After`, the pause starts at `baseDelayMs` and doubles with\n * each throttle in a row, and is jittered down by up to half so the requests\n * of separate crawls do not retry in step.\n *\n * @param url The URL that was throttled.\n * @param baseDelayMs The pause after the first throttle, before jitter.\n * @param retryAfterMs The pause the server asked for, if it named one.\n * @returns How long the host is paused from now, in milliseconds.\n */\n throttle(url: string, baseDelayMs: number, retryAfterMs?: number): number {\n const host = hostOf(url);\n const now = Date.now();\n const state = this.hosts.get(host) ?? { resumeAt: 0, strikes: 0, throttledAt: 0 };\n state.strikes++;\n state.throttledAt = now;\n\n let delay: number;\n if (retryAfterMs !== undefined) {\n delay = Math.min(retryAfterMs, MAX_THROTTLE_DELAY_MS);\n } else {\n const exponent = Math.min(state.strikes - 1, MAX_BACKOFF_EXPONENT);\n const nominal = Math.min(baseDelayMs * 2 ** exponent, MAX_THROTTLE_DELAY_MS);\n delay = nominal / 2 + (Math.random() * nominal) / 2;\n }\n\n state.resumeAt = Math.max(state.resumeAt, now + Math.round(delay));\n this.hosts.set(host, state);\n return state.resumeAt - now;\n }\n\n /**\n * Records a normal answer from the host, which ends its backoff.\n *\n * Only a request sent after the last throttle counts: one that was already\n * in flight says nothing about whether the host has recovered.\n *\n * @param url The URL that was answered.\n * @param sentAt When the request was sent, in epoch milliseconds.\n */\n recover(url: string, sentAt: number): void {\n const host = hostOf(url);\n const state = this.hosts.get(host);\n if (state && sentAt > state.throttledAt) {\n this.hosts.delete(host);\n }\n }\n}\n\n/**\n * Returns the key a URL's pause is stored under.\n *\n * @param url An absolute URL.\n * @returns The URL's host, including any port.\n */\nfunction hostOf(url: string): string {\n return new URL(url).host;\n}\n\n/**\n * Resolves after `ms` milliseconds, or rejects as soon as the signal aborts.\n *\n * @param ms The delay in milliseconds.\n * @param signal Aborts the delay.\n */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer);\n reject(new CancellationError(\"Wait for a throttled host cancelled\"));\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n if (signal?.aborted) {\n onAbort();\n return;\n }\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n","import https from \"node:https\";\nimport axios, { type AxiosError, type AxiosRequestConfig } from \"axios\";\nimport { CancellationError } from \"../../pipeline/errors\";\nimport { ScraperAccessPolicy } from \"../../utils/accessPolicy\";\nimport type { AppConfig } from \"../../utils/config\";\nimport {\n ChallengeError,\n HttpStatusError,\n RedirectError,\n ScraperError,\n TlsCertificateError,\n} from \"../../utils/errors\";\nimport { logger } from \"../../utils/logger\";\nimport { MimeTypeUtils } from \"../../utils/mimeTypeUtils\";\nimport { detectChallengePage } from \"./challenge\";\nimport { FingerprintGenerator } from \"./FingerprintGenerator\";\nimport { HostBackoff, parseRetryAfter } from \"./HostBackoff\";\nimport { withoutConnectionHeaders } from \"./headers\";\nimport {\n type ContentFetcher,\n type FetchOptions,\n FetchStatus,\n type RawContent,\n} from \"./types\";\n\n/**\n * Maximum number of redirects to follow in a single fetch. Matches the legacy\n * axios default; kept here as a named constant because redirects are now\n * followed manually so every hop can be revalidated against the access policy.\n */\nconst MAX_REDIRECTS = 5;\n\n/**\n * How much longer than other retries a throttled request waits when the server\n * names no delay. A retry after the usual second would most likely be\n * throttled again.\n */\nconst THROTTLE_DELAY_FACTOR = 5;\n\n/**\n * Fetches content from remote sources using HTTP/HTTPS.\n *\n * A 429, or a 503 with `Retry-After`, pauses every request this fetcher sends\n * to that host (see {@link HostBackoff}).\n */\nexport class HttpFetcher implements ContentFetcher {\n private readonly maxRetriesDefault: number;\n /** Applied when the caller names no timeout; axios itself has no default. */\n private readonly timeoutDefaultMs: number;\n private readonly baseDelayDefaultMs: number;\n private readonly retryableStatusCodes = [\n 408, // Request Timeout\n 429, // Too Many Requests\n 500, // Internal Server Error\n 502, // Bad Gateway\n 503, // Service Unavailable\n 504, // Gateway Timeout\n 525, // SSL Handshake Failed (Cloudflare specific)\n ];\n\n private readonly nonRetryableErrorCodes = [\n \"ENOTFOUND\", // DNS resolution failed - domain doesn't exist\n \"ECONNREFUSED\", // Connection refused - service not running\n \"ENOENT\", // No such file or directory\n \"EACCES\", // Permission denied\n \"EINVAL\", // Invalid argument\n \"EMFILE\", // Too many open files\n \"ENFILE\", // File table overflow\n \"EPERM\", // Operation not permitted\n ];\n\n private readonly tlsCertificateErrorCodes = [\n \"CERT_HAS_EXPIRED\",\n \"DEPTH_ZERO_SELF_SIGNED_CERT\",\n \"ERR_TLS_CERT_ALTNAME_INVALID\",\n \"SELF_SIGNED_CERT_IN_CHAIN\",\n \"UNABLE_TO_GET_ISSUER_CERT\",\n \"UNABLE_TO_GET_ISSUER_CERT_LOCALLY\",\n \"UNABLE_TO_VERIFY_LEAF_SIGNATURE\",\n ];\n\n private fingerprintGenerator: FingerprintGenerator;\n private readonly accessPolicy: ScraperAccessPolicy;\n private readonly hostBackoff: HostBackoff;\n\n /**\n * @param scraperConfig - Scraper settings, including the retry defaults.\n * @param hostBackoff - The per-host pause; pass one to share it with other\n * fetchers of the same crawl.\n */\n constructor(scraperConfig: AppConfig[\"scraper\"], hostBackoff = new HostBackoff()) {\n this.maxRetriesDefault = scraperConfig.fetcher.maxRetries;\n this.baseDelayDefaultMs = scraperConfig.fetcher.baseDelayMs;\n this.timeoutDefaultMs = scraperConfig.fetcher.timeoutMs;\n this.fingerprintGenerator = new FingerprintGenerator();\n this.accessPolicy = new ScraperAccessPolicy(scraperConfig.security);\n this.hostBackoff = hostBackoff;\n }\n\n canFetch(source: string): boolean {\n return source.startsWith(\"http://\") || source.startsWith(\"https://\");\n }\n\n private async delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n private isTlsCertificateError(code?: string): boolean {\n return code ? this.tlsCertificateErrorCodes.includes(code) : false;\n }\n\n async fetch(source: string, options?: FetchOptions): Promise<RawContent> {\n const maxRetries = options?.maxRetries ?? this.maxRetriesDefault;\n const baseDelay = options?.retryDelay ?? this.baseDelayDefaultMs;\n // Default to following redirects if not specified\n const followRedirects = options?.followRedirects ?? true;\n\n const result = await this.performFetch(\n source,\n options,\n maxRetries,\n baseDelay,\n followRedirects,\n );\n\n return result;\n }\n\n private async performFetch(\n source: string,\n options: FetchOptions | undefined,\n maxRetries: number = this.maxRetriesDefault,\n baseDelay: number = this.baseDelayDefaultMs,\n followRedirects: boolean = true,\n ): Promise<RawContent> {\n await this.accessPolicy.assertNetworkUrlAllowed(source);\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n // Outside the try so a throttle is recorded against the host of the hop\n // that answered, which a redirect may have changed.\n let currentUrl = source;\n try {\n let redirectCount = 0;\n\n while (true) {\n // Node's HTTP client manages the connection, so the fingerprint's\n // connection-level headers are left out.\n const fingerprint = withoutConnectionHeaders(\n this.fingerprintGenerator.generateHeaders(),\n );\n // The fingerprint's Accept asks for HTML first. Markdown that a server\n // converts on request leaves out the site's navigation, and with it\n // the links a crawl follows; Markdown the site publishes is fetched\n // by its own URL instead (llms.txt entries, `.md` links).\n const headers: Record<string, string> = {\n ...fingerprint,\n ...options?.headers, // User-provided headers override generated ones\n };\n\n // Add If-None-Match header for conditional requests if ETag is provided\n if (options?.etag) {\n headers[\"If-None-Match\"] = options.etag;\n logger.debug(\n `Conditional request for ${source} with If-None-Match: ${options.etag}`,\n );\n }\n\n const config: AxiosRequestConfig = {\n // Streamed so the Content-Type can be inspected before any body bytes\n // are consumed, letting unprocessable responses be abandoned early.\n responseType: \"stream\",\n headers: {\n ...headers,\n // Override Accept-Encoding to exclude zstd which Axios doesn't handle automatically\n // This prevents servers from sending zstd-compressed content that would appear as binary garbage\n \"Accept-Encoding\": \"gzip, deflate, br\",\n },\n // Defaulted rather than passed through as undefined: axios treats\n // that as \"wait forever\", so a server that accepts the connection\n // and then stalls held the worker until the process died.\n timeout: options?.timeout ?? this.timeoutDefaultMs,\n signal: options?.signal, // Pass signal to axios\n // Redirects are handled manually so every target can be revalidated before connect.\n maxRedirects: 0,\n decompress: true,\n // Allow 304 responses to be handled as successful responses\n validateStatus: (status) => {\n return (status >= 200 && status < 400) || status === 304;\n },\n };\n\n if (this.accessPolicy.shouldAllowInvalidTls(currentUrl)) {\n config.httpsAgent = new https.Agent({ rejectUnauthorized: false });\n }\n\n // A throttled retry waits here too, together with every other\n // request to the host.\n await this.hostBackoff.wait(currentUrl, options?.signal);\n const sentAt = Date.now();\n const response = await axios.get(currentUrl, config);\n this.hostBackoff.recover(currentUrl, sentAt);\n\n // Under `responseType: \"stream\"` a body that is never read pins its\n // socket: Node will not return a partially-consumed response to the\n // keep-alive pool. Only the success path consumes the stream, so every\n // other exit — 304, redirect, access-policy rejection, the content-type\n // gate — tears it down here rather than at each call site.\n let bodyConsumed = false;\n try {\n // 304 Not Modified is a conditional response, not a redirect. Handle\n // it before the 30x redirect branch so the missing Location header\n // does not trip the redirect check.\n if (response.status === 304) {\n logger.debug(`HTTP 304 Not Modified for ${currentUrl}`);\n return {\n content: Buffer.from(\"\"),\n mimeType: \"text/plain\",\n source: currentUrl,\n status: FetchStatus.NOT_MODIFIED,\n } satisfies RawContent;\n }\n\n if (response.status >= 300 && response.status < 400) {\n const location = response.headers.location;\n if (!location) {\n throw new ScraperError(\n `Redirect response for ${currentUrl} did not include a location header`,\n false,\n );\n }\n\n if (!followRedirects) {\n throw new RedirectError(currentUrl, location, response.status);\n }\n\n if (redirectCount >= MAX_REDIRECTS) {\n throw new ScraperError(\n `Too many redirects while fetching ${source}`,\n false,\n );\n }\n\n const redirectUrl = new URL(location, currentUrl).href;\n await this.accessPolicy.assertNetworkUrlAllowed(redirectUrl);\n\n currentUrl = redirectUrl;\n redirectCount += 1;\n continue;\n }\n\n const contentTypeHeader = response.headers[\"content-type\"];\n const { mimeType, charset } = MimeTypeUtils.parseContentType(\n typeof contentTypeHeader === \"string\" ? contentTypeHeader : undefined,\n );\n const rawContentEncoding = response.headers[\"content-encoding\"];\n const contentEncoding =\n typeof rawContentEncoding === \"string\" ? rawContentEncoding : undefined;\n\n // Determine the final effective URL after redirects (if any)\n const finalUrl =\n // Node follow-redirects style\n response.request?.res?.responseUrl ||\n // Some adapters may expose directly\n response.request?.responseUrl ||\n // Fallback to axios recorded config URL\n response.config?.url ||\n currentUrl;\n\n await this.accessPolicy.assertNetworkUrlAllowed(finalUrl);\n\n // Content-type gate. Runs after redirect resolution and the access-policy\n // check for the final URL, and before the body is read, so a response no\n // pipeline can process costs headers rather than megabytes.\n if (options?.acceptsMimeType && !options.acceptsMimeType(mimeType)) {\n logger.debug(`Skipping ${finalUrl}: ${mimeType} is not processable`);\n return {\n content: Buffer.from(\"\"),\n mimeType,\n charset,\n source: finalUrl,\n status: FetchStatus.SKIPPED,\n } satisfies RawContent;\n }\n\n // Extract ETag header for caching\n const etag = response.headers.etag || response.headers.ETag;\n if (etag) {\n logger.debug(`Received ETag for ${finalUrl}: ${etag}`);\n }\n\n // Extract Last-Modified header for caching\n const lastModified = response.headers[\"last-modified\"];\n const lastModifiedISO = lastModified\n ? new Date(lastModified).toISOString()\n : undefined;\n\n const content = await readStreamToBuffer(response.data, options?.signal);\n bodyConsumed = true;\n\n // Some challenges answer with 200 rather than 403, so the status\n // check in the catch block below never sees them. Their page is\n // not the document and must not be returned as one.\n const challengeType = MimeTypeUtils.isHtml(mimeType)\n ? detectChallengePage(content)\n : null;\n if (challengeType) {\n throw new ChallengeError(\n source,\n response.status,\n challengeType,\n currentUrl,\n );\n }\n\n return {\n content,\n mimeType,\n charset,\n encoding: contentEncoding,\n source: finalUrl,\n etag,\n lastModified: lastModifiedISO,\n status: FetchStatus.SUCCESS,\n } satisfies RawContent;\n } finally {\n if (!bodyConsumed) {\n destroyStream(response.data);\n }\n }\n }\n } catch (error: unknown) {\n if (error instanceof RedirectError || error instanceof ChallengeError) {\n throw error;\n }\n\n if (error instanceof ScraperError && !error.isRetryable) {\n throw error;\n }\n\n const axiosError = error as AxiosError;\n const status = axiosError.response?.status;\n const code = axiosError.code;\n const errorCause = error instanceof Error ? error : undefined;\n\n // Handle abort/cancel: do not retry, throw CancellationError\n if (options?.signal?.aborted || code === \"ERR_CANCELED\") {\n // Throw with isError = false to indicate cancellation is not an error\n throw new CancellationError(\"HTTP fetch cancelled\");\n }\n\n // Handle 404 Not Found - return special status for refresh operations\n if (status === 404) {\n logger.debug(`Resource not found (404): ${source}`);\n return {\n content: Buffer.from(\"\"),\n mimeType: \"text/plain\",\n source: source,\n status: FetchStatus.NOT_FOUND,\n } satisfies RawContent;\n }\n\n // Handle redirect errors (status codes 301, 302, 303, 307, 308)\n if (!followRedirects && status && status >= 300 && status < 400) {\n const location = axiosError.response?.headers?.location;\n if (location) {\n throw new RedirectError(source, location, status);\n }\n }\n\n // The server asked the scraper to slow down. The pause covers the whole\n // host, and is recorded before the challenge check below so the browser\n // fallback waits it out as well.\n const retryAfterMs = parseRetryAfter(\n axiosError.response?.headers?.[\"retry-after\"],\n );\n const throttleDelayMs =\n status === 429 || (status === 503 && retryAfterMs !== undefined)\n ? this.hostBackoff.throttle(\n currentUrl,\n baseDelay * THROTTLE_DELAY_FACTOR,\n retryAfterMs,\n )\n : undefined;\n\n // Detect Cloudflare challenges. Cloudflare also serves its challenge\n // with 429 once a client is rate limited; retrying that only extends\n // the block, so it goes to the browser at once like a 403 challenge.\n if (status === 403 || status === 429) {\n const cfMitigated = axiosError.response?.headers?.[\"cf-mitigated\"];\n const server = axiosError.response?.headers?.server;\n let responseBody = \"\";\n\n // Read the error body so the content-based challenge markers below can\n // still be matched. Under `responseType: \"stream\"` this is a Readable,\n // so it has to be drained rather than cast.\n if (axiosError.response?.data) {\n try {\n responseBody = (\n await readStreamToBuffer(axiosError.response.data)\n ).toString(\"utf-8\");\n } catch {\n // Ignore conversion errors\n }\n }\n\n // Check for various Cloudflare challenge indicators. A 429 from\n // Cloudflare is not a challenge on the server header alone: that is\n // also how a plain rate limit on a Cloudflare-fronted site looks.\n const isCloudflareChallenge =\n cfMitigated === \"challenge\" ||\n (status === 403 && server === \"cloudflare\") ||\n responseBody.includes(\"Enable JavaScript and cookies to continue\") ||\n responseBody.includes(\"Just a moment...\") ||\n responseBody.includes(\"cf_chl_opt\");\n\n if (isCloudflareChallenge) {\n throw new ChallengeError(source, status, \"cloudflare\", currentUrl);\n }\n }\n\n // Axios rejects 4xx/5xx before the success path's try/finally is entered,\n // so the error body is a Readable nothing has consumed. Left open it pins\n // the socket, which matters most on the retry path: a new connection is\n // opened while the failed one is still held.\n destroyStream(axiosError.response?.data);\n\n if (this.isTlsCertificateError(code)) {\n throw new TlsCertificateError(source, code, errorCause);\n }\n\n if (\n attempt < maxRetries &&\n (status === undefined || this.retryableStatusCodes.includes(status)) &&\n !this.nonRetryableErrorCodes.includes(code ?? \"\")\n ) {\n const delay = throttleDelayMs ?? baseDelay * 2 ** attempt;\n logger.warn(\n `⚠️ Attempt ${attempt + 1}/${\n maxRetries + 1\n } failed for ${source} (Status: ${status}, Code: ${code}). Retrying in ${delay}ms...`,\n );\n // A throttled request waits out the host's pause at the top of the\n // next attempt instead.\n if (throttleDelayMs === undefined) {\n await this.delay(delay);\n }\n continue;\n }\n\n // Not a 5xx error or max retries reached\n const failureMessage = `Failed to fetch ${source} after ${\n attempt + 1\n } attempts: ${axiosError.message ?? \"Unknown error\"}`;\n throw status === undefined\n ? new ScraperError(failureMessage, true, errorCause)\n : new HttpStatusError(failureMessage, true, status, errorCause, currentUrl);\n }\n }\n throw new ScraperError(\n `Failed to fetch ${source} after ${maxRetries + 1} attempts`,\n true,\n );\n }\n}\n\n/**\n * Abandons a streamed response body without reading it.\n *\n * Used when the content-type gate rejects a response: the socket is torn down so\n * the remaining bytes are never transferred.\n *\n * @param stream The response body, which may be any shape axios returned.\n */\nfunction destroyStream(stream: unknown): void {\n const candidate = stream as { destroy?: () => void } | null | undefined;\n if (candidate && typeof candidate.destroy === \"function\") {\n candidate.destroy();\n }\n}\n\n/**\n * Collects a streamed response body into a single Buffer.\n *\n * Axios yields a Node Readable under `responseType: \"stream\"`, already decompressed\n * when `decompress` is enabled. A body that is absent or not async-iterable — which\n * some error responses carry — reads as empty rather than throwing.\n *\n * @param stream The response body to read.\n * @param signal Optional abort signal; aborting destroys the stream.\n * @returns The complete body as a Buffer.\n */\nasync function readStreamToBuffer(\n stream: unknown,\n signal?: AbortSignal,\n): Promise<Buffer> {\n if (\n !stream ||\n typeof (stream as AsyncIterable<unknown>)[Symbol.asyncIterator] !== \"function\"\n ) {\n return Buffer.from(\"\");\n }\n\n const chunks: Buffer[] = [];\n const onAbort = () => destroyStream(stream);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n try {\n for await (const chunk of stream as AsyncIterable<Buffer | string>) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n } finally {\n signal?.removeEventListener(\"abort\", onAbort);\n }\n return Buffer.concat(chunks);\n}\n","/**\n * Fetcher that routes URLs to HTTP, browser, or file implementations and\n * retries with a browser when an HTTP challenge is detected. Requires the\n * resolved scraper configuration to align with entrypoint-provided settings.\n */\n\nimport type { AppConfig } from \"../../utils/config\";\nimport { ChallengeError, HttpStatusError, TlsCertificateError } from \"../../utils/errors\";\nimport { logger } from \"../../utils/logger\";\nimport { BrowserFetcher } from \"./BrowserFetcher\";\nimport { FileFetcher } from \"./FileFetcher\";\nimport { HostBackoff } from \"./HostBackoff\";\nimport { HttpFetcher } from \"./HttpFetcher\";\nimport type { ManagedBrowser } from \"./ManagedBrowser\";\nimport type { ContentFetcher, FetchOptions, RawContent } from \"./types\";\n\n/** Statuses anti-bot layers return that a real browser can often get past. */\nconst ANTI_BOT_STATUS_CODES = new Set([403, 429]);\n\n/**\n * AutoDetectFetcher automatically selects the appropriate fetcher based on URL type\n * and handles fallbacks for challenge detection.\n *\n * This eliminates the need for consumers to manage multiple fetcher instances\n * and implement fallback logic themselves.\n */\nexport class AutoDetectFetcher implements ContentFetcher {\n private readonly httpFetcher: HttpFetcher;\n private readonly browserFetcher: BrowserFetcher;\n private readonly fileFetcher: FileFetcher;\n /** Pauses a host that throttled a request, for the browser fallback too. */\n private readonly hostBackoff = new HostBackoff();\n\n /**\n * @param scraperConfig - Scraper settings shared by all fetchers.\n * @param managedBrowser - The browser for the browser fallback; pass one to\n * share it with the HTML renderer.\n */\n constructor(scraperConfig: AppConfig[\"scraper\"], managedBrowser?: ManagedBrowser) {\n this.httpFetcher = new HttpFetcher(scraperConfig, this.hostBackoff);\n this.browserFetcher = new BrowserFetcher(scraperConfig, managedBrowser);\n this.fileFetcher = new FileFetcher(scraperConfig);\n }\n\n /**\n * Classifies a fetch failure as one a real browser could plausibly get past.\n *\n * @param error The error the HTTP fetcher threw.\n * @returns A reason to log, or null when the browser would not help.\n */\n private static browserFallbackReason(error: unknown): string | null {\n if (error instanceof ChallengeError) {\n return \"Challenge detected\";\n }\n if (error instanceof TlsCertificateError) {\n return \"TLS certificate validation failed\";\n }\n // A 403/429 that wasn't recognized as a challenge is still usually an\n // anti-bot block. Keyed off the response status, never the message text,\n // which embeds the url and would match any url containing \"403\".\n if (error instanceof HttpStatusError && ANTI_BOT_STATUS_CODES.has(error.statusCode)) {\n return `Anti-bot block (HTTP ${error.statusCode})`;\n }\n return null;\n }\n\n /**\n * Returns the URL whose response caused a fetch failure.\n *\n * @param error The error the HTTP fetcher threw.\n * @returns The answering URL, or undefined when the error does not name one.\n */\n private static responseUrl(error: unknown): string | undefined {\n if (error instanceof ChallengeError || error instanceof HttpStatusError) {\n return error.responseUrl;\n }\n return undefined;\n }\n\n /**\n * Check if this fetcher can handle the given source.\n * Returns true for any URL that any of the underlying fetchers can handle.\n */\n canFetch(source: string): boolean {\n return (\n this.httpFetcher.canFetch(source) ||\n this.browserFetcher.canFetch(source) ||\n this.fileFetcher.canFetch(source)\n );\n }\n\n /**\n * Fetch content from the source, automatically selecting the appropriate fetcher\n * and handling fallbacks when challenges are detected.\n */\n async fetch(source: string, options?: FetchOptions): Promise<RawContent> {\n // For file:// URLs, use FileFetcher directly\n if (this.fileFetcher.canFetch(source)) {\n logger.debug(`Using FileFetcher for: ${source}`);\n return this.fileFetcher.fetch(source, options);\n }\n\n // For HTTP(S) URLs, try HttpFetcher first, fallback to BrowserFetcher on\n // a challenge or an anti-bot block\n if (this.httpFetcher.canFetch(source)) {\n try {\n logger.debug(`Using HttpFetcher for: ${source}`);\n return await this.httpFetcher.fetch(source, options);\n } catch (error: unknown) {\n const reason = AutoDetectFetcher.browserFallbackReason(error);\n if (reason) {\n logger.info(`🔄 ${reason} for ${source}, falling back to browser fetcher...`);\n // A 429 paused the host; navigating at once would be throttled again.\n // The browser follows the same redirects, so it also waits for the\n // host that answered when a redirect led away from `source`.\n for (const url of new Set([source, AutoDetectFetcher.responseUrl(error)])) {\n if (url) await this.hostBackoff.wait(url, options?.signal);\n }\n return this.browserFetcher.fetch(source, options);\n }\n throw error;\n }\n }\n\n // If we get here, no fetcher can handle this URL\n throw new Error(`No suitable fetcher found for URL: ${source}`);\n }\n\n /**\n * Close all underlying fetchers to prevent resource leaks.\n */\n async close(): Promise<void> {\n await Promise.allSettled([\n this.browserFetcher.close(),\n // HttpFetcher and FileFetcher don't need explicit cleanup\n ]);\n }\n}\n","import type { Chunk } from \"../splitter/types\";\nimport type { ProgressCallback } from \"../types\";\n\n/**\n * Represents an item in the scraping queue\n */\nexport type QueueItem = {\n url: string;\n depth: number;\n pageId?: number; // Database page ID for efficient deletion during refresh\n etag?: string | null; // Last known ETag for conditional requests during refresh\n /** True when the queue item was seeded from a discovered llms.txt file. */\n fromLlmsTxt?: boolean;\n /**\n * The page's own URL, when `url` is the location a representation of it was\n * retrieved from rather than the page itself.\n *\n * A refresh asks for the representation, because that is what produced the\n * stored content and what issued the stored validator. But a 404 there is a\n * statement about the representation, not about the page: a site that\n * withdraws its published Markdown files still serves the pages they\n * described. This is the address to fall back to before concluding the page\n * is gone.\n */\n identityUrl?: string;\n /** Internal-only allowlist roots for application-managed temporary files. */\n internalAllowedFileRoots?: string[];\n};\n\n/**\n * Enum defining the available HTML processing strategies.\n */\nexport enum ScrapeMode {\n Fetch = \"fetch\",\n Playwright = \"playwright\",\n Auto = \"auto\",\n}\n\n/**\n * Strategy interface for implementing different scraping behaviors\n */\nexport interface ScraperStrategy {\n scrape(\n options: ScraperOptions,\n progressCallback: ProgressCallback<ScraperProgressEvent>,\n signal?: AbortSignal, // Add optional signal\n ): Promise<void>;\n\n /**\n * Cleanup resources used by this strategy (e.g., pipeline browser instances).\n * Should be called when the strategy is no longer needed.\n */\n cleanup?(): Promise<void>;\n}\n\n/**\n * Internal runtime options for configuring the scraping process.\n *\n * This is the comprehensive configuration object used by ScraperService, PipelineWorker,\n * and scraper strategies. It includes both:\n * - User-facing options (provided via tools like scrape_docs)\n * - System-managed options (set internally by PipelineManager)\n *\n * Note: User-facing tools should NOT expose all these options directly. Instead,\n * PipelineManager is responsible for translating user input into this complete\n * runtime configuration.\n */\nexport interface ScraperOptions {\n url: string;\n library: string;\n version: string;\n maxPages?: number;\n maxDepth?: number;\n /**\n * Defines the allowed crawling boundary relative to the starting URL\n * - 'subpages': Only crawl URLs on the same hostname and within the same starting path (default)\n * - 'hostname': Crawl any URL on the same exact hostname, regardless of path\n * - 'domain': Crawl any URL on the same top-level domain, including subdomains\n */\n scope?: \"subpages\" | \"hostname\" | \"domain\";\n /**\n * Controls whether HTTP redirects (3xx responses) should be followed\n * - When true: Redirects are followed automatically (default)\n * - When false: A RedirectError is thrown when a 3xx response is received\n */\n followRedirects?: boolean;\n maxConcurrency?: number;\n ignoreErrors?: boolean;\n /** Preserve URL hash fragments for hash-routed SPAs instead of treating them as anchors. */\n preserveHashes?: boolean;\n /** CSS selectors for elements to exclude during HTML processing */\n excludeSelectors?: string[];\n /**\n * Determines the HTML processing strategy.\n * - 'fetch': Use a simple DOM parser (faster, less JS support).\n * - 'playwright': Use a headless browser (slower, full JS support).\n * - 'auto': Automatically select the best strategy (currently defaults to 'playwright').\n * @default ScrapeMode.Auto\n */\n scrapeMode?: ScrapeMode;\n /** Optional AbortSignal for cancellation */\n signal?: AbortSignal;\n /**\n * Patterns for including URLs during scraping. If not set, all are included by default.\n */\n includePatterns?: string[];\n /**\n * Patterns for excluding URLs during scraping. Exclude takes precedence over include.\n */\n excludePatterns?: string[];\n /**\n * Custom HTTP headers to send with each HTTP request (e.g., for authentication).\n * Keys are header names, values are header values.\n */\n headers?: Record<string, string>;\n /**\n * Pre-populated queue of pages to visit.\n * When provided:\n * - Disables link discovery and crawling\n * - Processes only the provided URLs\n * - Uses provided metadata (pageId, etag) for optimization\n */\n initialQueue?: QueueItem[];\n /**\n * Indicates whether this is a refresh operation (re-indexing existing version).\n * When true:\n * - Skips initial removeAllDocuments call to preserve existing data\n * - Uses ETags for conditional requests\n * - Only updates changed/deleted pages\n * @default false\n */\n isRefresh?: boolean;\n /**\n * If true, clears existing documents for the library version before scraping.\n * If false, appends to the existing documents.\n * @default true\n */\n clean?: boolean;\n /**\n * Internal-only allowlist roots for application-managed temporary files.\n */\n internalAllowedFileRoots?: string[];\n}\n\n/** Options that only steer a single run, never stored or resubmitted. */\ntype RunOnlyScraperOption = \"signal\" | \"initialQueue\" | \"isRefresh\";\n\n/**\n * Drops the options that only steer a single run (its cancellation signal and\n * a refresh's queue and flag), leaving what reproduces the scrape: what the\n * store keeps, and what a retry resubmits.\n */\nexport function withoutRunOnlyOptions<T extends Partial<ScraperOptions>>(\n options: T,\n): Omit<T, RunOnlyScraperOption> {\n const {\n signal: _signal,\n initialQueue: _initialQueue,\n isRefresh: _isRefresh,\n ...reproducible\n } = options;\n return reproducible;\n}\n\n/**\n * Result of scraping a single page.\n */\nexport interface ScrapeResult {\n /** The URL of the page that was scraped */\n url: string;\n /**\n * Where the content was actually retrieved from, when that differs from `url`.\n *\n * `url` is the page's identity; this is the location that served its bytes. They\n * diverge when a representation lives elsewhere — a published Markdown file\n * recorded under the page it represents. Undefined means the two coincide.\n */\n contentUrl?: string;\n /** Page title */\n title: string;\n /** Original MIME type of the fetched resource before pipeline processing */\n sourceContentType: string;\n /** MIME type of the stored content after pipeline processing */\n contentType: string;\n /** The final processed content, typically as a string (e.g., Markdown). Used primarily for debugging */\n textContent: string;\n /** Extracted links from the content. */\n links: string[];\n /** Any non-critical errors encountered during processing. */\n errors: Error[];\n /** Pre-split chunks from pipeline processing */\n chunks: Chunk[];\n /** ETag from HTTP response for caching */\n etag?: string | null;\n /** Last-Modified from HTTP response for caching */\n lastModified?: string | null;\n /**\n * True when this crawl already stored another representation of `url`.\n *\n * A page reachable as both `/guide.md` and `/guide` produces two results with\n * one identity, and the store keeps whichever representation is stronger. A\n * first write is not a competition and always lands, so a later crawl's\n * answer supersedes an earlier crawl's instead of being blocked by it.\n */\n isAdditionalRepresentation?: boolean;\n}\n\n/**\n * What happened to a single queued item once it was processed.\n *\n * Named explicitly rather than inferred from `result` being null, because a null\n * result cannot distinguish a page that is unchanged from one that is now empty:\n * a 304 says \"keep what you have\", an empty 200 says \"here it is, and it is\n * empty\". Those call for opposite handling.\n */\nexport enum PageOutcome {\n /** Content was produced and should be stored. The only outcome that indexes. */\n Stored = \"stored\",\n /** The resource was unchanged since the last fetch (304). Keep what is stored. */\n Unchanged = \"unchanged\",\n /** The resource is gone (404). During a refresh the stored page is deleted. */\n Absent = \"absent\",\n /** Fetched successfully but yielded no content. The page exists and is empty. */\n Empty = \"empty\",\n /** No pipeline can read this content type, so the body was never downloaded. */\n Skipped = \"skipped\",\n /** Processing failed and the error was ignored under `ignoreErrors`. */\n Failed = \"failed\",\n}\n\n/**\n * Progress information during scraping.\n *\n * Counter semantics are defined by the `scrape-progress-reporting` capability.\n * In short: `pagesScraped` counts work done, `pagesIndexed` counts what came of\n * it, and `totalPages` is what `pagesScraped` converges on.\n */\nexport interface ScraperProgressEvent {\n /**\n * Queued items that have been dequeued and reached an outcome, whatever that\n * outcome was. The numerator of the progress fraction. Every queued item\n * eventually advances this exactly once, so it converges on `totalPages`.\n */\n pagesScraped: number;\n /**\n * Items the job expects to process: URLs admitted to the queue, clamped at the\n * point the crawl will stop, which is `maxPages` plus the number of processed\n * items that produced no content.\n *\n * This is NOT the configured `maxPages` value.\n */\n totalPages: number;\n /**\n * Total number of URLs admitted to the crawl queue, unbounded by `maxPages`.\n * Exceeds `totalPages` only when the page limit clamps the crawl.\n */\n totalDiscovered: number;\n /**\n * Processed items that produced stored content — the number a user means by\n * \"pages added\". Bounded by `maxPages`. Not part of the progress fraction.\n */\n pagesIndexed: number;\n /** Current URL being processed */\n currentUrl: string;\n /** Current depth in the crawl tree */\n depth: number;\n /** Maximum depth allowed (from maxDepth option) */\n maxDepth: number;\n /** What happened to this item. Consumers branch on this, not on `result`. */\n outcome: PageOutcome;\n /** The processed content. Non-null only when `outcome` is `Stored`. */\n result: ScrapeResult | null;\n /**\n * Page identity for an `Empty` outcome, so the store can record that the page\n * exists and holds nothing. `etag` and `lastModified` are null when the\n * pipeline failed, which keeps the next refresh unconditional.\n */\n emptyPage?: {\n url: string;\n /** Where the content was retrieved from, when that differs from `url`. */\n contentUrl?: string;\n title: string;\n sourceContentType: string | null;\n contentType: string | null;\n etag: string | null;\n lastModified: string | null;\n pipelineFailed: boolean;\n /** See {@link ScrapeResult.isAdditionalRepresentation}. */\n isAdditionalRepresentation?: boolean;\n };\n /** Database page ID (for refresh operations or tracking) */\n pageId?: number;\n /**\n * Indicates the stored page is to be deleted: a 404 during refresh or a\n * broken link, or a container that an older version stored as a page.\n */\n deleted?: boolean;\n}\n","import * as cheerio from \"cheerio\";\n\nexport interface LlmsTxtLink {\n title: string;\n url: string;\n description?: string;\n optional: boolean;\n section?: string;\n}\n\nexport interface LlmsTxtSection {\n title: string;\n optional: boolean;\n links: LlmsTxtLink[];\n}\n\nexport interface LlmsTxtResult {\n projectName?: string;\n summary?: string;\n sections: LlmsTxtSection[];\n links: LlmsTxtLink[];\n}\n\nconst emptyLlmsTxtResult = (): LlmsTxtResult => ({\n sections: [],\n links: [],\n});\n\nconst markdownLinkPattern =\n /^\\s*[-*+•]\\s+\\[([^\\]\\n]+)]\\(([^)\\s]+)\\)\\s*(?::\\s*(.+?)\\s*)?$/;\n\nconst htmlDocumentPattern = /^\\s*<(?:!doctype\\s+html|html|body|head)(?:\\s|>)/i;\n\n/**\n * Unwraps llms.txt content that a browser rendered as HTML.\n *\n * Browsers wrap a `text/plain` response in a single `<pre>` element, so that\n * shape still carries a valid llms.txt. Only that shape is unwrapped: a real\n * HTML page whose body merely contains a `<pre>` code block must keep failing\n * the HTML check, otherwise a soft-404 documentation page would be accepted as\n * an llms.txt index.\n *\n * @param content The raw fetched content.\n * @returns The unwrapped text, or null when the content is not a bare `<pre>` wrapper.\n */\nfunction unwrapPlainTextPre(content: string): string | null {\n const $ = cheerio.load(content);\n const body = $(\"body\");\n if (body.length !== 1) {\n return null;\n }\n\n // Structure, not leftover text: a page whose visible text all sits inside a\n // <pre> still fails this when anything wraps or accompanies it. An empty SPA\n // shell (<div id=\"root\"></div>) renders no text but is not a plain-text\n // response, and must not be read as an llms.txt index.\n const children = body\n .children()\n .filter((_, el) => el.tagName?.toLowerCase() !== \"script\");\n if (children.length !== 1) {\n return null;\n }\n\n const pre = children.first();\n if (pre.prop(\"tagName\")?.toLowerCase() !== \"pre\") {\n return null;\n }\n\n // Only whitespace may surround it, and a head carries nothing renderable.\n const bodyClone = body.clone();\n bodyClone.children().remove();\n if (bodyClone.text().trim().length > 0) {\n return null;\n }\n\n // .text() resolves entities and drops the nested <code> a browser may add.\n return pre.text();\n}\n\n/**\n * Returns true when a URL points to an llms.txt meta-file.\n * @param url The URL to inspect.\n * @returns Whether the URL path basename is exactly llms.txt.\n */\nexport function isLlmsTxtUrl(url: string): boolean {\n try {\n const basename = new URL(url).pathname.split(\"/\").filter(Boolean).at(-1);\n return basename?.toLowerCase() === \"llms.txt\";\n } catch {\n return false;\n }\n}\n\n/**\n * Parses llms.txt Markdown into project metadata and curated links.\n * @param content The llms.txt Markdown content.\n * @returns Parsed llms.txt metadata and links, or an empty result for invalid content.\n */\nexport function parseLlmsTxt(content: string): LlmsTxtResult {\n if (!content.trim() || content.includes(\"\\0\")) {\n return emptyLlmsTxtResult();\n }\n\n // A server may render plain text as HTML; unwrap that, but keep rejecting\n // genuine HTML documents.\n const unwrapped = unwrapPlainTextPre(content);\n if (unwrapped === null && htmlDocumentPattern.test(content)) {\n return emptyLlmsTxtResult();\n }\n const rawText = unwrapped ?? content;\n\n const lines = rawText.split(/\\r?\\n/);\n const firstH1Index = lines.findIndex((line) => /^#\\s+\\S/.test(line));\n // A tag line is never a title: the HTML check above only catches documents\n // that *start* with one, so a bare fragment still reaches here.\n const isPlausibleTitle = (line: string) =>\n line.trim().length > 0 && !line.trim().startsWith(\"<\");\n\n const startIndex =\n firstH1Index !== -1 ? firstH1Index : lines.findIndex(isPlausibleTitle);\n if (startIndex === -1) {\n return emptyLlmsTxtResult();\n }\n\n const projectName = lines[startIndex].replace(/^#\\s+/, \"\").trim();\n if (!projectName) {\n return emptyLlmsTxtResult();\n }\n\n const result: LlmsTxtResult = {\n projectName,\n sections: [],\n links: [],\n };\n\n let currentSection: LlmsTxtSection | undefined;\n const summaryLines: string[] = [];\n let collectingSummary = true;\n\n for (const line of lines.slice(startIndex + 1)) {\n if (/^#\\s+\\S/.test(line)) {\n collectingSummary = false;\n continue;\n }\n\n const h2Match = /^##\\s+(.+?)\\s*$/.exec(line);\n if (h2Match) {\n collectingSummary = false;\n const title = h2Match[1].trim();\n currentSection = {\n title,\n optional: title.toLowerCase() === \"optional\",\n links: [],\n };\n result.sections.push(currentSection);\n continue;\n }\n\n if (collectingSummary) {\n if (/^>\\s?/.test(line)) {\n summaryLines.push(line.replace(/^>\\s?/, \"\").trim());\n continue;\n }\n if (summaryLines.length > 0 && line.trim() === \"\") {\n continue;\n }\n if (line.trim() !== \"\") {\n collectingSummary = false;\n }\n }\n\n const linkMatch = markdownLinkPattern.exec(line);\n if (!linkMatch) {\n continue;\n }\n\n const link: LlmsTxtLink = {\n title: linkMatch[1].trim(),\n url: linkMatch[2].trim(),\n optional: currentSection?.optional ?? false,\n ...(currentSection ? { section: currentSection.title } : {}),\n ...(linkMatch[3]?.trim() ? { description: linkMatch[3].trim() } : {}),\n };\n\n currentSection?.links.push(link);\n result.links.push(link);\n }\n\n if (summaryLines.length > 0) {\n result.summary = summaryLines.join(\"\\n\");\n }\n\n if (result.links.length === 0) {\n return emptyLlmsTxtResult();\n }\n\n return result;\n}\n","// Utility for scope filtering, extracted from WebScraperStrategy\nimport type { URL } from \"node:url\";\nimport { extractPrimaryDomain } from \"../../utils/url\";\n\nconst INDEX_FILE_PATTERN = /^index(\\.[a-z0-9]+)?$/i;\n\n/**\n * Extensions that mark a URL's last segment as a page rather than a directory.\n * Kept in step with the document formats {@link MimeTypeUtils} recognizes.\n */\nconst PAGE_FILE_EXTENSION_PATTERN =\n /\\.(?:html?|xhtml|php|aspx?|jsp|mdx?|markdown|txt|rst|adoc|json|ya?ml|xml|pdf)$/i;\n\n/**\n * Returns true when a URL path names a page rather than a directory.\n *\n * An extension alone is too loose — a version directory like `/docs/v1.0` ends\n * in `.0` — so only known page extensions count, plus the bare `index` form\n * that {@link computeBaseDirectory} already treats as a file.\n *\n * @param pathname The URL pathname to classify.\n * @returns Whether the last segment names a file.\n */\nexport function isFileLikePath(pathname: string): boolean {\n const lastSegment = pathname.split(\"/\").filter(Boolean).at(-1);\n if (!lastSegment) {\n return false;\n }\n return (\n PAGE_FILE_EXTENSION_PATTERN.test(lastSegment) || INDEX_FILE_PATTERN.test(lastSegment)\n );\n}\n\n/**\n * Compute the effective base directory for scope=subpages.\n * Rules:\n * - Empty path or \"/\" → \"/\"\n * - Path ending with \"/\" → returned unchanged\n * - Last segment matches /^index(\\.[a-z0-9]+)?$/i (case-insensitive, extension optional)\n * → parent directory with trailing slash. Covers /api/index, /api/index.html, /api/Index.HTML, etc.\n * - Otherwise → path with trailing slash appended (path is treated as a directory)\n */\nexport function computeBaseDirectory(pathname: string): string {\n if (pathname === \"\" || pathname === \"/\") return \"/\";\n if (pathname.endsWith(\"/\")) return pathname;\n const lastSegment = pathname.split(\"/\").at(-1) || \"\";\n if (INDEX_FILE_PATTERN.test(lastSegment)) {\n return pathname.replace(/\\/[^/]*$/, \"/\");\n }\n return `${pathname}/`;\n}\n\n/**\n * Returns true when `childPath` is the same as `parentPath` or is a path-descendant of it.\n * `parentPath` is normalized to end with \"/\" before comparison so directory semantics apply.\n *\n * Examples:\n * - isPathDescendant(\"/api\", \"/api\") → true (equal after normalization)\n * - isPathDescendant(\"/api\", \"/api/\") → true\n * - isPathDescendant(\"/api\", \"/api/foo\") → true\n * - isPathDescendant(\"/api\", \"/api~hash\") → false (siblingwise, not under /api/)\n * - isPathDescendant(\"/api\", \"/blog\") → false\n */\nexport function isPathDescendant(parentPath: string, childPath: string): boolean {\n const normalizedParent = parentPath.endsWith(\"/\") ? parentPath : `${parentPath}/`;\n if (childPath === normalizedParent) return true;\n if (`${childPath}/` === normalizedParent) return true; // child is parent without trailing slash\n return childPath.startsWith(normalizedParent);\n}\n\n/**\n * Strip a single trailing \".\" from a hostname. DNS names like \"example.com.\" and \"example.com\"\n * resolve identically; comparison code should treat them as equivalent.\n */\nexport function stripTrailingDot(hostname: string): string {\n return hostname.endsWith(\".\") ? hostname.slice(0, -1) : hostname;\n}\n\n/**\n * Returns true if the targetUrl is in scope of the baseUrl for the given scope.\n * - \"subpages\": same host (incl. port) AND target path starts with the base directory of base path\n * - \"hostname\": same host (incl. port)\n * - \"domain\": same primary domain (registrable domain, port-agnostic)\n *\n * Protocol equality is required for all scopes. Hostname trailing-dot is normalized for all scopes.\n */\nexport function isInScope(\n baseUrl: URL,\n targetUrl: URL,\n scope: \"subpages\" | \"hostname\" | \"domain\",\n): boolean {\n if (baseUrl.protocol !== targetUrl.protocol) return false;\n\n const baseHostNoDot = normalizeHost(baseUrl.host, baseUrl.hostname);\n const targetHostNoDot = normalizeHost(targetUrl.host, targetUrl.hostname);\n\n switch (scope) {\n case \"subpages\": {\n if (baseHostNoDot !== targetHostNoDot) return false;\n const baseDir = computeBaseDirectory(baseUrl.pathname);\n return targetUrl.pathname.startsWith(baseDir);\n }\n case \"hostname\":\n return baseHostNoDot === targetHostNoDot;\n case \"domain\": {\n return (\n extractPrimaryDomain(stripTrailingDot(baseUrl.hostname)) ===\n extractPrimaryDomain(stripTrailingDot(targetUrl.hostname))\n );\n }\n default:\n return false;\n }\n}\n\n/**\n * Strip the trailing dot only from the hostname portion of a `host` string (which may include\n * a port). Returns the host with the trailing dot removed from the hostname, port preserved.\n */\nfunction normalizeHost(host: string, hostname: string): string {\n const stripped = stripTrailingDot(hostname);\n if (stripped === hostname) return host;\n // Replace the leading hostname portion with the stripped version, preserving any \":port\" suffix.\n return host.replace(hostname, stripped);\n}\n","import path from \"node:path\";\nimport { URL } from \"node:url\";\nimport { CancellationError } from \"../../pipeline/errors\";\nimport type { ProgressCallback } from \"../../types\";\nimport { fileUrlToPathLoose } from \"../../utils/accessPolicy\";\nimport type { AppConfig } from \"../../utils/config\";\nimport { ScraperError } from \"../../utils/errors\";\nimport { logger } from \"../../utils/logger\";\nimport { normalizeUrl, type UrlNormalizerOptions } from \"../../utils/url\";\nimport { FetchStatus } from \"../fetcher/types\";\nimport type { PipelineResult } from \"../pipelines/types\";\nimport {\n PageOutcome,\n type QueueItem,\n type ScrapeResult,\n type ScraperOptions,\n type ScraperProgressEvent,\n type ScraperStrategy,\n} from \"../types\";\nimport { isLlmsTxtUrl } from \"../utils/llmsTxtParser\";\nimport { shouldIncludeUrl } from \"../utils/patternMatcher\";\nimport { isInScope } from \"../utils/scope\";\n\nexport interface BaseScraperStrategyOptions {\n urlNormalizerOptions?: UrlNormalizerOptions;\n}\n\n/**\n * Result of processing a single queue item.\n * - processed: The processed content (when available)\n * - links: Discovered links for crawling (may exist without content, e.g., directories)\n * - status: The fetch status (SUCCESS, NOT_MODIFIED, NOT_FOUND)\n */\nexport interface ProcessItemResult {\n /** The URL of the content */\n url: string;\n /** Where the content was retrieved from, when that differs from `url`. */\n contentUrl?: string;\n /** The title of the page or document, extracted during processing */\n title?: string | null;\n /** Original MIME type of the fetched resource, if known */\n sourceContentType?: string | null;\n /** MIME type of the stored content after pipeline processing, if known */\n contentType?: string | null;\n /** The ETag header value from the HTTP response, if available, used for caching and change detection. */\n etag?: string | null;\n /** The Last-Modified header value, if available, used for caching and change detection. */\n lastModified?: string | null;\n /** The pipeline-processed content, including title, text content, links, errors, and chunks. This may be null if the content was not successfully processed (e.g., 404 or 304). */\n content?: PipelineResult;\n /** Extracted links from the content. This may be an empty array if no links were found or if the content was not processed. */\n links?: string[];\n /** Fully formed queue items discovered outside normal link extraction. */\n queueItems?: QueueItem[];\n /** Internal-only allowlist roots to carry to discovered queue items. */\n internalAllowedFileRoots?: string[];\n /**\n * True when this item is a container rather than a page — a directory listing\n * or archive that yields links but is not itself indexable.\n *\n * Declared rather than inferred: a container must never be written to the\n * index as an empty page, and deducing that from a missing content type made\n * the rule depend on a field set for unrelated reasons.\n */\n isContainer?: boolean;\n /**\n * True when the pipeline raised errors while producing no content.\n *\n * Distinguishes \"this page is empty\" from \"we failed to read this page\", which\n * decides whether the response validator may be stored.\n */\n pipelineFailed?: boolean;\n /** Any non-critical errors encountered during processing. This may be an empty array if no errors were encountered or if the content was not processed. */\n status: FetchStatus;\n}\n\nclass FailureThresholdExceededError extends ScraperError {}\n\n/** Abort state shared by the items of one crawl. */\ninterface CrawlAbortState {\n /**\n * Set once the child-page failure rate trips or the progress callback\n * throws; running items stop on it.\n */\n abortError: Error | null;\n}\n\nexport abstract class BaseScraperStrategy implements ScraperStrategy {\n private static readonly FAILURE_RATE_MIN_SAMPLE = 10;\n\n /**\n * Set of normalized URLs that have been marked for processing.\n *\n * IMPORTANT: URLs are added to this set BEFORE they are actually processed, not after.\n * This prevents the same URL from being queued multiple times when discovered from different sources.\n *\n * Usage flow:\n * 1. Initial queue setup: Root URL and initialQueue items are added to visited\n * 2. During processing: When a page returns links, each link is checked against visited\n * 3. In admitToQueue deduplication: Only links NOT in visited are added to the queue AND to visited\n *\n * This approach ensures:\n * - No URL is processed more than once\n * - No URL appears in the queue multiple times\n * - Efficient deduplication across concurrent processing\n */\n protected visited = new Set<string>();\n /**\n * Page identities this crawl has already stored, as the strategy reports\n * them — `canonicalizeStoredUrl`'s output, which is a normalized URL for web\n * crawls and the URL unchanged for `file://` and GitHub sources.\n *\n * `visited` cannot serve here: it holds URLs as they were queued, and a page's\n * identity is only known once the response arrives — `/guide.md` resolves to\n * `/guide`, which by then may already be sitting in the queue under its own\n * spelling. Both are dequeued and both are stored, so without this set one\n * page would be counted twice against the page limit and the crawl would stop\n * short of the pages the user asked for.\n */\n protected storedIdentities = new Set<string>();\n /** Items dequeued and given an outcome. Converges on {@link effectiveTotal}. */\n protected pageCount = 0;\n /** Processed items that produced stored content. Bounded by `maxPages`. */\n protected pagesIndexed = 0;\n protected totalDiscovered = 0; // URLs admitted to the queue (unlimited)\n /** URLs admitted to the queue, clamped at where the crawl will stop. */\n protected effectiveTotal = 0;\n protected canonicalBaseUrl?: URL; // Final URL after initial redirect (depth 0)\n protected completedChildPageAttempts = 0;\n protected failedChildPages = 0;\n\n /**\n * The point at which the crawl stops, expressed in processed items.\n *\n * `maxPages` bounds indexed pages, so reaching it takes `maxPages` successes\n * plus however many items produced nothing along the way. Clamping the\n * denominator flat at `maxPages` would put it below the numerator; this keeps\n * the two able to meet.\n *\n * @param options Scraper options supplying the effective page limit.\n * @returns The processed-item budget.\n */\n private processingBudget(options: ScraperOptions): number {\n const maxPages = options.maxPages ?? this.config.scraper.maxPages;\n // Items that produced nothing push the stopping point further out. Derived\n // rather than stored: every processed item is either indexed or it is not.\n return maxPages + (this.pageCount - this.pagesIndexed);\n }\n\n /**\n * Raises the denominator to match a budget that just grew.\n *\n * Called when an item produces no content, which pushes the stopping point one\n * item further out. Never lowers it: the queue may already hold more.\n *\n * @param options Scraper options supplying the effective page limit.\n */\n protected retuneEffectiveTotal(options: ScraperOptions): void {\n const capped = Math.min(this.totalDiscovered, this.processingBudget(options));\n if (capped > this.effectiveTotal) {\n this.effectiveTotal = capped;\n }\n }\n\n protected options: BaseScraperStrategyOptions;\n protected config: AppConfig;\n\n constructor(config: AppConfig, options: BaseScraperStrategyOptions = {}) {\n this.config = config;\n this.options = options;\n }\n\n /**\n * Resolves the URL a page is recorded under.\n *\n * The base implementation records the URL exactly as it resolved. Trimming a\n * trailing slash or an index file is an HTTP convention — it rests on a server\n * returning the same bytes either way — and that is false for the URL spaces\n * other strategies work in: `file:///docs/index.html` and a GitHub blob path\n * both name a file, and the trimmed form addresses nothing. Strategies whose\n * URLs follow web conventions override this.\n *\n * @param url The URL the content resolved to.\n * @param _scrapeOptions Options, used by overrides.\n * @returns The URL to record the page under.\n */\n protected canonicalizeStoredUrl(url: string, _scrapeOptions: ScraperOptions): string {\n return url;\n }\n\n protected getUrlNormalizerOptions(scrapeOptions: ScraperOptions): UrlNormalizerOptions {\n // On a hash-routed site the fragment names the route, so it is kept. The\n // path in front of a fragment is then part of that route's spelling and is\n // left alone too, but `normalizeUrl` decides that per URL: disabling the\n // path rewrites for the whole crawl would leave `/docs` and `/docs/` as two\n // pages on the very sites this option is for.\n return {\n ...this.options.urlNormalizerOptions,\n removeHash: scrapeOptions.preserveHashes\n ? false\n : (this.options.urlNormalizerOptions?.removeHash ?? true),\n };\n }\n\n /**\n * Returns the URL that `scope` is measured from: the root after any redirect\n * on its first fetch, or else the URL the scrape started from.\n *\n * @param options Scraper options naming the URL the scrape started from.\n * @returns The scope base URL.\n */\n protected getScopeBaseUrl(options: ScraperOptions): URL {\n return this.canonicalBaseUrl ?? new URL(options.url);\n }\n\n /**\n * Determines if a URL should be processed based on scope and include/exclude patterns in ScraperOptions.\n * Scope is checked first, then patterns.\n *\n * `internalAllowedFileRoots` opts a queue item out of the protocol-strict\n * scope check: when a web URL has been accepted as an archive root and the\n * archive expands into `file://` members, those members are continuations of\n * the same accepted scrape and should not be rejected because they crossed\n * from `https:` to `file:`. The bypass is intentionally narrow — the\n * `file://` target must resolve inside one of the internal roots — so\n * arbitrary links injected into archive content cannot escape the archive\n * sandbox via this path. Downstream `resolveFileAccess` enforces the same\n * rule, but rejecting early here keeps unrelated `file://` URLs out of the\n * crawl queue entirely.\n */\n protected shouldProcessUrl(\n url: string,\n options: ScraperOptions,\n context: { internalAllowedFileRoots?: string[] } = {},\n ): boolean {\n if (isLlmsTxtUrl(url)) {\n return false;\n }\n\n const isInternalArchiveMember =\n url.startsWith(\"file://\") &&\n isFileUrlInsideRoots(url, context.internalAllowedFileRoots);\n\n if (!isInternalArchiveMember) {\n const scope = options.scope ?? \"subpages\";\n try {\n const base = this.getScopeBaseUrl(options);\n const target = new URL(url);\n if (!isInScope(base, target, scope)) return false;\n } catch {\n return false;\n }\n }\n return shouldIncludeUrl(url, options.includePatterns, options.excludePatterns);\n }\n\n /**\n * Process a single item from the queue.\n *\n * @returns Processed content, links, and metadata\n */\n protected abstract processItem(\n item: QueueItem,\n options: ScraperOptions,\n signal?: AbortSignal,\n ): Promise<ProcessItemResult>;\n\n private shouldCountTowardFailureThreshold(\n item: QueueItem,\n options: ScraperOptions,\n result?: ProcessItemResult,\n ): boolean {\n // An llms.txt index is a discovery hint, not a list of pages the user asked\n // for. Its dead entries must not push the scrape past the failure threshold\n // — that would abort the scrape by the back door, which is exactly what\n // treating those 404s as non-fatal is meant to prevent.\n if (item.fromLlmsTxt) {\n return false;\n }\n return !this.isRequestedRoot(item, options) && !this.isRefreshDeletion(item, result);\n }\n\n /**\n * True only for the URL the user actually requested.\n *\n * Identified by URL rather than `depth === 0`: llms.txt seeds are queued at\n * depth 0 so their own links get a fresh depth budget, and a refresh rebuilds\n * its queue from stored pages that carry neither the seed marker nor a\n * meaningful root depth.\n */\n protected isRequestedRoot(item: QueueItem, options: ScraperOptions): boolean {\n const normalizerOptions = this.getUrlNormalizerOptions(options);\n return (\n normalizeUrl(item.url, normalizerOptions) ===\n normalizeUrl(options.url, normalizerOptions)\n );\n }\n\n private isRefreshDeletion(item: QueueItem, result?: ProcessItemResult): boolean {\n return item.pageId !== undefined && result?.status === FetchStatus.NOT_FOUND;\n }\n\n private recordChildPageCompletion(\n item: QueueItem,\n options: ScraperOptions,\n result?: ProcessItemResult,\n ): void {\n if (!this.shouldCountTowardFailureThreshold(item, options, result)) {\n return;\n }\n\n this.completedChildPageAttempts++;\n }\n\n private recordChildPageFailure(item: QueueItem, options: ScraperOptions): void {\n if (!this.shouldCountTowardFailureThreshold(item, options)) {\n return;\n }\n\n this.completedChildPageAttempts++;\n this.failedChildPages++;\n }\n\n private ensureFailureRateWithinThreshold(): void {\n if (\n this.completedChildPageAttempts < BaseScraperStrategy.FAILURE_RATE_MIN_SAMPLE ||\n this.completedChildPageAttempts === 0\n ) {\n return;\n }\n\n const failureRate = this.failedChildPages / this.completedChildPageAttempts;\n const threshold = this.config.scraper.abortOnFailureRate;\n\n if (failureRate > threshold) {\n throw new FailureThresholdExceededError(\n `Scrape aborted after ${this.failedChildPages}/${this.completedChildPageAttempts} child pages failed (${failureRate.toFixed(2)} > ${threshold.toFixed(2)})`,\n false,\n );\n }\n }\n\n /**\n * Processes one dequeued item to its outcome and returns the queue items it\n * offers.\n *\n * The offered items have passed every discovered-link filter but are not yet\n * deduplicated: admission belongs to {@link admitToQueue}, which the crawl loop\n * calls in dequeue order so the queue stays breadth-first however the\n * concurrent items finish.\n *\n * @param item The dequeued item.\n * @param baseUrl Base for resolving links when the item has no final URL.\n * @param options Scraper options for this crawl.\n * @param progressCallback Receives the item's outcome.\n * @param crawl Abort state shared by every item of this crawl.\n * @param signal Cancels the crawl.\n * @returns The queue items discovered by this item.\n */\n protected async processQueueItem(\n item: QueueItem,\n baseUrl: URL,\n options: ScraperOptions,\n progressCallback: ProgressCallback<ScraperProgressEvent>,\n crawl: CrawlAbortState,\n signal?: AbortSignal,\n ): Promise<QueueItem[]> {\n const ensureFailureRateWithinThreshold = (): void => {\n try {\n this.ensureFailureRateWithinThreshold();\n } catch (error) {\n if (error instanceof FailureThresholdExceededError) {\n crawl.abortError ??= error;\n }\n throw error;\n }\n };\n\n // Items still running when the failure threshold trips stop at their next\n // checkpoint instead of reporting outcomes for a crawl that has ended.\n const throwIfCrawlAborted = (): void => {\n if (crawl.abortError) {\n throw crawl.abortError;\n }\n if (signal?.aborted) {\n throw new CancellationError(\"Scraping cancelled while processing\");\n }\n };\n\n // Check signal before processing the item\n throwIfCrawlAborted();\n // Resolved for the progress log and the enqueue-time depth filter below.\n // Items are no longer dropped here: every queued item reaches an outcome,\n // which is what lets the processed count converge on the queued total.\n const maxDepth = options.maxDepth ?? this.config.scraper.maxDepth;\n\n // Every dequeued item reaches exactly one outcome and advances the\n // processed count once, which is what makes it converge on the queued\n // total. Only `Stored` additionally advances the indexed count.\n //\n // Declared outside the try so the failure path reports through it too:\n // the counter protocol has one implementation, not two.\n const report = async (\n outcome: PageOutcome,\n extra: Partial<\n Pick<ScraperProgressEvent, \"currentUrl\" | \"result\" | \"emptyPage\" | \"deleted\">\n > = {},\n ): Promise<void> => {\n const pagesScraped = ++this.pageCount;\n\n // Two routes can reach one document — an llms.txt `.md` entry and the\n // crawled HTML page — and both are sent to the store, which decides\n // which representation to keep. Only the first of them is a new page:\n // counting the second would let one document consume two units of the\n // page budget and leave the crawl short of what the user asked for.\n const identity = extra.result?.url ?? extra.emptyPage?.url;\n const alreadyStored = identity !== undefined && this.storedIdentities.has(identity);\n const isNewPage = outcome === PageOutcome.Stored && !alreadyStored;\n if (isNewPage) {\n if (identity !== undefined) this.storedIdentities.add(identity);\n this.pagesIndexed++;\n } else {\n this.retuneEffectiveTotal(options);\n }\n\n logger.info(\n `🌐 Scraping page ${pagesScraped}/${this.effectiveTotal} (depth ${item.depth}/${maxDepth}): ${item.url}`,\n );\n\n try {\n await progressCallback({\n pagesScraped,\n totalPages: this.effectiveTotal,\n totalDiscovered: this.totalDiscovered,\n pagesIndexed: this.pagesIndexed,\n currentUrl: item.url,\n depth: item.depth,\n maxDepth,\n outcome,\n result: null,\n pageId: item.pageId,\n ...extra,\n // Told to the store rather than derived there: only the crawl knows\n // whether it has already stored this identity during this run, and\n // that is what separates \"a competing representation\" from \"the new\n // state of the page\", which are resolved in opposite directions.\n ...(extra.result\n ? { result: { ...extra.result, isAdditionalRepresentation: alreadyStored } }\n : {}),\n ...(extra.emptyPage\n ? {\n emptyPage: {\n ...extra.emptyPage,\n isAdditionalRepresentation: alreadyStored,\n },\n }\n : {}),\n });\n } catch (error) {\n // The consumer reports a page it cannot store and carries on, so an\n // error that reaches here means the job cannot go on. Recording it ends\n // the crawl; the catch below would otherwise count it as one failed\n // page and, under `ignoreErrors`, crawl on.\n crawl.abortError ??= error instanceof Error ? error : new Error(String(error));\n throw error;\n }\n };\n\n try {\n // Pass signal to processItem\n const result = await this.processItem(item, options, signal);\n throwIfCrawlAborted();\n\n if (result.status === FetchStatus.NOT_MODIFIED) {\n // File/page hasn't changed, skip processing but count as processed\n logger.debug(`Page unchanged (304): ${item.url}`);\n await report(PageOutcome.Unchanged);\n this.recordChildPageCompletion(item, options, result);\n ensureFailureRateWithinThreshold();\n throwIfCrawlAborted();\n return result.queueItems ?? [];\n }\n\n if (result.status === FetchStatus.NOT_FOUND) {\n // A 404 at a representation is not a statement about the page. A\n // refresh asks the location the content came from, which for a\n // published Markdown file is not the page's own URL; a site that\n // withdraws those files still serves the pages they described.\n // Ask the identity before concluding anything, and send no stored\n // validator with it — that one was issued by the resource that is\n // now gone. If the identity 404s too, this item carries no further\n // fallback and the page is deleted then.\n const identityFallback: QueueItem[] =\n item.identityUrl !== undefined && item.identityUrl !== item.url\n ? // Spread so the item keeps whatever else governs how it is\n // fetched and scoped; only the address and the validator\n // change. `etag` is dropped because it was issued by the\n // resource that just answered 404, and `identityUrl` because\n // this IS the identity — a second 404 here is the page.\n [{ ...item, url: item.identityUrl, etag: null, identityUrl: undefined }]\n : [];\n // Deliberately not named `isRefreshDeletion`: the method of that\n // name answers \"is this a refresh 404?\" and is still consulted by\n // `shouldCountTowardFailureThreshold`, which must keep ignoring\n // these. This narrower question is whether the page is actually\n // removed, which a pending fallback defers.\n const deletesStoredPage =\n this.isRefreshDeletion(item, result) && identityFallback.length === 0;\n const fallbackQueueItems = [...(result.queueItems ?? []), ...identityFallback];\n const hasNewFallbackQueueItem = fallbackQueueItems.some(\n (queueItem) =>\n !this.visited.has(\n normalizeUrl(queueItem.url, this.getUrlNormalizerOptions(options)),\n ),\n );\n\n // Only the user's actual requested root should be fatal on 404 — an\n // llms.txt-seeded depth-0 item is just one of several discovery seeds\n // and a dead entry there shouldn't abort a scrape whose real root URL\n // resolved fine (see llmstxt-discovery spec: llms.txt link failures\n // are not supposed to fail the overall scrape).\n if (\n this.isRequestedRoot(item, options) &&\n !deletesStoredPage &&\n !hasNewFallbackQueueItem\n ) {\n throw new ScraperError(`Root page not found: ${item.url}`, false);\n }\n\n if (!deletesStoredPage) {\n this.recordChildPageFailure(item, options);\n ensureFailureRateWithinThreshold();\n }\n\n throwIfCrawlAborted();\n\n // File/page was deleted, count as processed\n logger.debug(`Page deleted (404): ${item.url}`);\n await report(PageOutcome.Absent, deletesStoredPage ? { deleted: true } : {});\n return fallbackQueueItems;\n }\n\n if (result.status === FetchStatus.SKIPPED) {\n // The resource was fetched but nothing can read its content type, so\n // the body was abandoned at the headers. This is neither a success nor\n // a failure: no page is stored, and the child-page failure rate is left\n // untouched so an asset-heavy site cannot trip abortOnFailureRate.\n // Only the user's actual requested root is fatal, matching the 404\n // branch above. An llms.txt seed is one of several discovery seeds,\n // and a refresh replays stored pages at their stored depth — neither\n // should abort a scrape whose real root resolved fine.\n if (item.depth === 0 && !item.fromLlmsTxt && item.pageId === undefined) {\n // Name the type: the user picked this URL, and \"some content type\"\n // does not tell them whether they mistyped it or asked for a format\n // this server cannot read.\n const contentType = result.sourceContentType ?? \"unknown content type\";\n throw new ScraperError(\n `Cannot process ${contentType} at ${item.url}: no pipeline can read it`,\n false,\n );\n }\n logger.debug(`Skipped (unprocessable content): ${item.url}`);\n await report(PageOutcome.Skipped);\n return result.queueItems ?? [];\n }\n\n if (result.status !== FetchStatus.SUCCESS) {\n // Unreachable while FetchStatus has only the four handled members, but\n // reporting here keeps \"every dequeued item reaches exactly one\n // outcome\" true by construction rather than by enumeration.\n logger.error(`❌ Unknown fetch status: ${result.status}`);\n await report(PageOutcome.Failed);\n return [];\n }\n\n // Handle successful processing - report result with content\n // Use the final URL from the result (which may differ due to redirects)\n //\n // Canonicalised so that spellings differing only by a trailing slash or\n // a fragment resolve to one page. Two routes to the same document —\n // `/config/` from a crawl and `/config.md` from an llms.txt index —\n // otherwise land as separate rows and split a page in two.\n const finalUrl = this.canonicalizeStoredUrl(result.url || item.url, options);\n\n // Register the resolved identity so the other route to this page is\n // recognised as already seen. The identity is only known after the\n // response, which is why it cannot be settled when the URL is queued.\n this.visited.add(normalizeUrl(finalUrl, this.getUrlNormalizerOptions(options)));\n\n // A result carrying no text is not a stored page. `WebScraperStrategy`\n // already gates on this, but the local-file and GitHub processors pass\n // their pipeline result through unconditionally, so an empty file would\n // otherwise report Stored, inflate the indexed count and consume the\n // page budget for a document the store then drops for having no chunks.\n const producedContent = !!result.content?.textContent?.trim();\n if (result.content && producedContent) {\n await report(PageOutcome.Stored, {\n currentUrl: finalUrl,\n result: {\n url: finalUrl,\n // Canonicalisation can move the identity too (`/docs/` to\n // `/docs`), and then the bytes came from somewhere the identity\n // no longer names. Record whichever URL actually served them.\n contentUrl:\n result.contentUrl ??\n (result.url && result.url !== finalUrl ? result.url : undefined),\n title: result.content.title?.trim() || result.title?.trim() || \"\",\n sourceContentType: result.sourceContentType || result.contentType || \"\",\n contentType: result.contentType || \"\",\n textContent: result.content.textContent || \"\",\n links: result.content.links || [],\n errors: result.content.errors || [],\n chunks: result.content.chunks || [],\n etag: result.etag || null,\n lastModified: result.lastModified || null,\n } satisfies ScrapeResult,\n });\n throwIfCrawlAborted();\n } else {\n // Fetched successfully but produced nothing to store: a directory\n // listing, or a page whose pipeline extracted no text. Either way the\n // item was processed, so it is reported rather than advancing the\n // counter silently.\n // A container that yields links — a directory listing, an archive — is\n // processed and produces nothing, but it is not a page and must not be\n // recorded as one.\n const wasPage = result.isContainer !== true;\n await report(PageOutcome.Empty, {\n currentUrl: finalUrl,\n // A stored row for a container was written by a version that kept\n // containers as pages, so a refresh deletes it.\n ...(!wasPage && item.pageId !== undefined ? { deleted: true } : {}),\n emptyPage: !wasPage\n ? undefined\n : {\n url: finalUrl,\n // An empty page still has a retrieval location: `/guide` can\n // be empty and have been read from `/guide.md`. Dropping it\n // would send the next refresh to the identity carrying a\n // validator the identity never issued.\n contentUrl:\n result.contentUrl ??\n (result.url && result.url !== finalUrl ? result.url : undefined),\n title: result.title?.trim() || \"\",\n sourceContentType: result.sourceContentType ?? null,\n contentType: result.contentType ?? null,\n // Withheld when the pipeline errored: storing the validator against\n // a failure we do not understand would make the next refresh answer\n // 304 and never retry, turning a transient fault permanent.\n etag: result.pipelineFailed ? null : (result.etag ?? null),\n lastModified: result.pipelineFailed\n ? null\n : (result.lastModified ?? null),\n pipelineFailed: result.pipelineFailed === true,\n },\n });\n throwIfCrawlAborted();\n }\n\n // Extract discovered links - use the final URL as the base for resolving relative links\n const nextItems = result.links || [];\n const linkBaseUrl = finalUrl ? new URL(finalUrl) : baseUrl;\n const internalAllowedFileRoots =\n result.internalAllowedFileRoots ?? item.internalAllowedFileRoots;\n\n this.recordChildPageCompletion(item, options, result);\n ensureFailureRateWithinThreshold();\n throwIfCrawlAborted();\n\n // Depth is invariant across these links, so reject the whole set at\n // once rather than parsing each URL and discarding it.\n //\n // Rejecting here rather than at dequeue is what keeps the progress\n // denominator honest, and the rejection deliberately does NOT add the\n // URL to `visited`. The queue is breadth-first in a normal crawl, so a\n // URL is first offered at its minimum reachable depth and this cannot\n // lose anything — but refresh mode builds its initial queue in database\n // order, which is not sorted by depth, so the same URL can legitimately\n // be offered again at a shallower depth later. Consuming a dedup slot\n // here would discard it.\n const childDepth = item.depth + 1;\n const linkQueueItems = (childDepth > maxDepth ? [] : nextItems)\n .map((value) => {\n try {\n const targetUrl = new URL(value, linkBaseUrl);\n // Filter using shouldProcessUrl\n if (\n !this.shouldProcessUrl(targetUrl.href, options, {\n internalAllowedFileRoots,\n })\n ) {\n return null;\n }\n return {\n url: targetUrl.href,\n depth: childDepth,\n ...(internalAllowedFileRoots ? { internalAllowedFileRoots } : {}),\n } satisfies QueueItem;\n } catch (_error) {\n // Invalid URL or path\n logger.warn(`❌ Invalid URL: ${value}`);\n }\n return null;\n })\n .filter((item): item is QueueItem => item !== null);\n\n return [...(result.queueItems ?? []), ...linkQueueItems];\n } catch (error) {\n if (\n error instanceof FailureThresholdExceededError ||\n error instanceof CancellationError\n ) {\n throw error;\n }\n\n // Never ignore errors for the root URL (depth 0) - if it fails, the job should fail\n // There's no point in \"successfully\" completing with 0 documents\n if (this.isRequestedRoot(item, options)) {\n throw error;\n }\n\n if (crawl.abortError) {\n throw crawl.abortError;\n }\n\n this.recordChildPageFailure(item, options);\n ensureFailureRateWithinThreshold();\n\n if (options.ignoreErrors) {\n logger.error(`❌ Failed to process ${item.url}: ${error}`);\n await report(PageOutcome.Failed);\n return [];\n }\n throw error;\n }\n }\n\n /**\n * Admits the offered items not yet seen and advances the queue totals.\n *\n * @param offered Items offered by one processed item, in discovery order.\n * @param options Scraper options supplying the effective page limit.\n * @returns The items admitted to the queue.\n */\n private admitToQueue(offered: QueueItem[], options: ScraperOptions): QueueItem[] {\n const admitted: QueueItem[] = [];\n\n for (const item of offered) {\n const normalizedUrl = normalizeUrl(item.url, this.getUrlNormalizerOptions(options));\n if (!this.visited.has(normalizedUrl)) {\n this.visited.add(normalizedUrl);\n admitted.push(item);\n\n // Always increment the unlimited counter\n this.totalDiscovered++;\n\n // Clamp at the processed-item budget, not flat at maxPages, so the\n // denominator stays reachable when items produce no content.\n if (this.effectiveTotal < this.processingBudget(options)) {\n this.effectiveTotal++;\n }\n }\n }\n\n return admitted;\n }\n\n async scrape(\n options: ScraperOptions,\n progressCallback: ProgressCallback<ScraperProgressEvent>,\n signal?: AbortSignal, // Add signal\n ): Promise<void> {\n this.visited.clear();\n this.storedIdentities.clear();\n this.pageCount = 0;\n this.pagesIndexed = 0;\n this.completedChildPageAttempts = 0;\n this.failedChildPages = 0;\n\n // Check if this is a refresh operation with pre-populated queue\n const initialQueue = options.initialQueue || [];\n const isRefreshMode = initialQueue.length > 0;\n\n // Set up base URL and queue\n this.canonicalBaseUrl = new URL(options.url);\n let baseUrl = this.canonicalBaseUrl;\n\n // Initialize queue: Start with root URL or use items from initialQueue (refresh mode)\n // The root URL is always processed (depth 0), but if it's in initialQueue, use that\n // version to preserve etag/pageId for conditional fetching\n const queue: QueueItem[] = [];\n const normalizedRootUrl = normalizeUrl(\n options.url,\n this.getUrlNormalizerOptions(options),\n );\n\n if (isRefreshMode) {\n logger.debug(\n `Starting refresh mode with ${initialQueue.length} pre-populated pages`,\n );\n\n // Add all items from initialQueue, using visited set to deduplicate\n for (const item of initialQueue) {\n const normalizedUrl = normalizeUrl(\n item.url,\n this.getUrlNormalizerOptions(options),\n );\n if (!this.visited.has(normalizedUrl)) {\n this.visited.add(normalizedUrl);\n queue.push(item);\n }\n }\n }\n\n // If root URL wasn't in initialQueue, add it now at depth 0\n if (!this.visited.has(normalizedRootUrl)) {\n this.visited.add(normalizedRootUrl);\n queue.unshift({ url: options.url, depth: 0 } satisfies QueueItem);\n }\n\n // Resolve optional values to defaults using temporary config lookup\n // (We'll replace this with proper config merging later)\n const maxPages = options.maxPages ?? this.config.scraper.maxPages;\n const maxConcurrency = options.maxConcurrency ?? this.config.scraper.maxConcurrency;\n\n // Initialize counters from the populated queue. The denominator is clamped\n // here as well as on increment: a refresh whose initial queue exceeds the\n // page limit would otherwise start with a total the numerator can never\n // reach, which is the defect this capability exists to remove.\n this.totalDiscovered = queue.length;\n this.effectiveTotal = Math.min(queue.length, this.processingBudget(options));\n\n // Unified processing loop for both normal and refresh modes.\n // `maxPages` bounds pages that produce content, not items processed: asking\n // for 100 pages should yield 100 pages, not stop at 100 attempts of which\n // some produced nothing.\n //\n // Items run in a sliding window: a slot is refilled as soon as its item\n // finishes. Fixed batches waited for their slowest member, so one URL\n // spending seconds in retry backoff idled every other slot and the crawl\n // looked frozen on whichever page happened to finish last.\n const crawl: CrawlAbortState = { abortError: null };\n const running = new Map<number, Promise<number>>();\n const finished = new Map<number, QueueItem[]>();\n let nextSeq = 0;\n let nextToAdmit = 0;\n\n // Items run on a signal of their own. When the crawl ends early, because an\n // item failed or the job was cancelled, aborting it stops the items still\n // running, and the crawl waits for them before it returns. Otherwise the\n // caller's cleanup would close the browser or delete files while they still\n // use them, and an item could launch a new browser that nobody closes.\n const items = new AbortController();\n const abortItems = (): void => items.abort(signal?.reason);\n signal?.addEventListener(\"abort\", abortItems, { once: true });\n\n try {\n // Runs until nothing is left running. Reaching `maxPages` only stops new\n // items from starting: an item counts its page before storing it, so\n // exiting on the count alone would resolve the crawl with that write\n // still pending.\n while (true) {\n // Check for cancellation at the start of each loop iteration\n if (signal?.aborted) {\n logger.debug(`${isRefreshMode ? \"Refresh\" : \"Scraping\"} cancelled by signal.`);\n throw new CancellationError(\n `${isRefreshMode ? \"Refresh\" : \"Scraping\"} cancelled by signal`,\n );\n }\n\n // Counting running items against the remaining budget is what stops\n // concurrent work overshooting the limit: at most `maxPages - pagesIndexed`\n // items run, so at most that many of them can index.\n while (\n running.size < maxConcurrency &&\n this.pagesIndexed + running.size < maxPages\n ) {\n const item = queue.shift();\n if (!item) break;\n const seq = nextSeq++;\n // Always use latest canonical base (may have been updated after first fetch)\n baseUrl = this.canonicalBaseUrl ?? baseUrl;\n running.set(\n seq,\n this.processQueueItem(\n item,\n baseUrl,\n options,\n progressCallback,\n crawl,\n items.signal,\n ).then((offered) => {\n finished.set(seq, offered);\n return seq;\n }),\n );\n }\n\n if (running.size === 0) {\n break;\n }\n\n running.delete(await Promise.race(running.values()));\n\n // Admit in dequeue order, not completion order, so the queue stays\n // breadth-first: a URL is first offered at its shortest depth however the\n // running items finish, and the crawl order does not depend on timing.\n for (\n let offered = finished.get(nextToAdmit);\n offered !== undefined;\n offered = finished.get(nextToAdmit)\n ) {\n finished.delete(nextToAdmit);\n nextToAdmit++;\n queue.push(...this.admitToQueue(offered, options));\n }\n }\n } catch (error) {\n items.abort(error);\n await Promise.allSettled(running.values());\n throw error;\n } finally {\n signal?.removeEventListener(\"abort\", abortItems);\n }\n }\n\n /**\n * Cleanup resources used by this strategy.\n * Default implementation does nothing - override in derived classes as needed.\n */\n async cleanup(): Promise<void> {\n // No-op by default\n }\n}\n\n/**\n * Returns true if `url` is a `file://` URL whose resolved filesystem path lies\n * inside one of the supplied internal roots. Used by the queue-time scope\n * bypass for archive-member URLs so that arbitrary `file://` links injected\n * into archive content cannot escape the archive sandbox.\n */\nfunction isFileUrlInsideRoots(url: string, roots: string[] | undefined): boolean {\n if (!roots || roots.length === 0) return false;\n let target: string;\n try {\n target = path.resolve(fileUrlToPathLoose(url));\n } catch {\n return false;\n }\n return roots.some((root) => {\n const resolvedRoot = path.resolve(root);\n if (resolvedRoot === target) return true;\n const relative = path.relative(resolvedRoot, target);\n return relative !== \"\" && !relative.startsWith(\"..\") && !path.isAbsolute(relative);\n });\n}\n","import type { ConstructorOptions } from \"jsdom\";\nimport { JSDOM, VirtualConsole } from \"jsdom\";\n\n/**\n * Creates a JSDOM instance with a pre-configured virtual console to suppress console noise.\n * This utility simplifies the setup of JSDOM by providing a standard configuration.\n *\n * @param html - The HTML content to parse.\n * @param options - Optional JSDOM configuration options. These will be merged with the default virtual console setup.\n * @returns A JSDOM instance.\n */\nexport function createJSDOM(html: string, options?: ConstructorOptions): JSDOM {\n const virtualConsole = new VirtualConsole();\n // Suppress console output from JSDOM by default\n virtualConsole.on(\"error\", () => {});\n virtualConsole.on(\"warn\", () => {});\n virtualConsole.on(\"info\", () => {});\n virtualConsole.on(\"debug\", () => {});\n virtualConsole.on(\"log\", () => {}); // Also suppress regular logs\n\n const defaultOptions: ConstructorOptions = {\n virtualConsole,\n };\n\n // Merge provided options with defaults, letting provided options override\n const finalOptions: ConstructorOptions = { ...defaultOptions, ...options };\n\n return new JSDOM(html, finalOptions);\n}\n","import { logger } from \"../utils\";\nimport type { Chunk, DocumentSplitter, SectionContentType } from \"./types\";\n\n/**\n * Takes small document chunks and greedily concatenates them into larger, more meaningful units\n * while preserving document structure and semantic boundaries.\n *\n * This approach improves embedding quality by:\n * - Maintaining context by keeping related content together\n * - Respecting natural document breaks at major section boundaries (H1/H2)\n * - Ensuring chunks are large enough to capture meaningful relationships\n * - Preventing chunks from becoming too large for effective embedding\n */\nexport class GreedySplitter implements DocumentSplitter {\n private baseSplitter: DocumentSplitter;\n private minChunkSize: number;\n private preferredChunkSize: number;\n private maxChunkSize: number;\n\n /**\n * Combines a base document splitter with size constraints to produce optimally-sized chunks.\n * The base splitter handles the initial semantic splitting, while this class handles\n * the concatenation strategy.\n */\n constructor(\n baseSplitter: DocumentSplitter,\n minChunkSize: number,\n preferredChunkSize: number,\n maxChunkSize: number,\n ) {\n this.baseSplitter = baseSplitter;\n this.minChunkSize = minChunkSize;\n this.preferredChunkSize = preferredChunkSize;\n this.maxChunkSize = maxChunkSize;\n }\n\n /**\n * Uses a greedy concatenation strategy to build optimally-sized chunks. Small chunks\n * are combined until they reach the minimum size, but splits are preserved at major\n * section boundaries to maintain document structure. This balances the need for\n * context with semantic coherence.\n */\n async splitText(markdown: string, contentType?: string): Promise<Chunk[]> {\n const initialChunks = await this.baseSplitter.splitText(markdown, contentType);\n const concatenatedChunks: Chunk[] = [];\n let currentChunk: Chunk | null = null;\n\n for (const nextChunk of initialChunks) {\n // Warn if a chunk from the base splitter already exceeds max size\n if (nextChunk.content.length > this.maxChunkSize) {\n logger.warn(\n `⚠ Chunk from base splitter exceeds max size: ${nextChunk.content.length} > ${this.maxChunkSize}`,\n );\n }\n\n if (currentChunk) {\n // Account for the newline separator that may be added when merging (see merge below)\n const separatorSize = currentChunk.content.endsWith(\"\\n\") ? 0 : 1;\n const combinedSize =\n currentChunk.content.length + separatorSize + nextChunk.content.length;\n\n // HARD LIMIT: Never exceed max chunk size\n if (combinedSize > this.maxChunkSize) {\n concatenatedChunks.push(currentChunk);\n currentChunk = this.cloneChunk(nextChunk);\n continue;\n }\n\n // STRUCTURE > SIZE: Respect major section boundaries (H1/H2) when current chunk\n // is large enough. This prevents headings from being merged with unrelated preceding\n // content while still allowing tiny chunks to be merged to avoid orphans.\n if (\n currentChunk.content.length >= this.minChunkSize &&\n this.startsNewMajorSection(nextChunk) &&\n !this.isSameSection(currentChunk, nextChunk)\n ) {\n concatenatedChunks.push(currentChunk);\n currentChunk = this.cloneChunk(nextChunk);\n continue;\n }\n\n // If combining would exceed preferred size AND we're already at min size, split\n // UNLESS the next chunk is very small (< min size), in which case merge it anyway\n if (\n combinedSize > this.preferredChunkSize &&\n currentChunk.content.length >= this.minChunkSize &&\n nextChunk.content.length >= this.minChunkSize\n ) {\n concatenatedChunks.push(currentChunk);\n currentChunk = this.cloneChunk(nextChunk);\n continue;\n }\n\n // Merge the chunks\n currentChunk.content += `${currentChunk.content.endsWith(\"\\n\") ? \"\" : \"\\n\"}${nextChunk.content}`;\n currentChunk.section = this.mergeSectionInfo(currentChunk, nextChunk);\n currentChunk.types = this.mergeTypes(currentChunk.types, nextChunk.types);\n } else {\n currentChunk = this.cloneChunk(nextChunk);\n }\n }\n\n if (currentChunk) {\n concatenatedChunks.push(currentChunk);\n }\n\n return concatenatedChunks;\n }\n\n private cloneChunk(chunk: Chunk): Chunk {\n return {\n types: [...chunk.types],\n content: chunk.content,\n section: {\n level: chunk.section.level,\n path: [...chunk.section.path],\n },\n };\n }\n\n /**\n * H1 and H2 headings represent major conceptual breaks in the document.\n * Preserving these splits helps maintain the document's logical structure.\n */\n private startsNewMajorSection(chunk: Chunk): boolean {\n return chunk.section.level === 1 || chunk.section.level === 2;\n }\n\n /**\n * Checks if two chunks belong to the same section by comparing their paths.\n * Returns true if the paths are identical or if one is a parent of the other.\n */\n private isSameSection(chunk1: Chunk, chunk2: Chunk): boolean {\n const path1 = chunk1.section.path;\n const path2 = chunk2.section.path;\n\n // Exact match\n if (path1.length === path2.length && path1.every((part, i) => part === path2[i])) {\n return true;\n }\n\n // Parent-child relationship (one path includes the other)\n return this.isPathIncluded(path1, path2) || this.isPathIncluded(path2, path1);\n }\n\n /**\n * Checks if one path is a prefix of another path, indicating a parent-child relationship\n */\n private isPathIncluded(parentPath: string[], childPath: string[]): boolean {\n if (parentPath.length >= childPath.length) return false;\n return parentPath.every((part, i) => part === childPath[i]);\n }\n\n /**\n * Merges section metadata when concatenating chunks, following these rules:\n * 1. Level: Always uses the lowest (most general) level between chunks\n * 2. Path selection:\n * - For parent-child relationships (one path includes the other), uses the child's path\n * - For siblings/unrelated sections, uses the common parent path\n * - If no common path exists, uses the root path ([])\n */\n private mergeSectionInfo(currentChunk: Chunk, nextChunk: Chunk): Chunk[\"section\"] {\n // Always use the lowest level\n const level = Math.min(currentChunk.section.level, nextChunk.section.level);\n\n // If sections are exactly equal, preserve all metadata\n if (\n currentChunk.section.level === nextChunk.section.level &&\n currentChunk.section.path.length === nextChunk.section.path.length &&\n currentChunk.section.path.every((p, i) => p === nextChunk.section.path[i])\n ) {\n return currentChunk.section;\n }\n\n // Check if one path includes the other\n if (this.isPathIncluded(currentChunk.section.path, nextChunk.section.path)) {\n return {\n path: nextChunk.section.path,\n level,\n };\n }\n\n if (this.isPathIncluded(nextChunk.section.path, currentChunk.section.path)) {\n return {\n path: currentChunk.section.path,\n level,\n };\n }\n\n // Find common parent path\n const commonPath = this.findCommonPrefix(\n currentChunk.section.path,\n nextChunk.section.path,\n );\n\n return {\n path: commonPath,\n level,\n };\n }\n\n private mergeTypes(\n currentTypes: SectionContentType[],\n nextTypes: SectionContentType[],\n ): SectionContentType[] {\n return [...new Set([...currentTypes, ...nextTypes])];\n }\n\n /**\n * Returns longest common prefix between two paths\n */\n private findCommonPrefix(path1: string[], path2: string[]): string[] {\n const common: string[] = [];\n for (let i = 0; i < Math.min(path1.length, path2.length); i++) {\n if (path1[i] === path2[i]) {\n common.push(path1[i]);\n } else {\n break;\n }\n }\n return common;\n }\n}\n","/**\n * Base error class for all splitter-related errors\n */\nexport class SplitterError extends Error {}\n\n/**\n * Thrown when content cannot be split further while maintaining its validity\n * (e.g., markdown tables require headers, code blocks require language and backticks)\n */\nexport class MinimumChunkSizeError extends SplitterError {\n constructor(size: number, maxSize: number) {\n super(\n `Cannot split content any further. Content requires minimum chunk size of ${size} bytes, but maximum allowed is ${maxSize} bytes.`,\n );\n }\n}\n\n/**\n * Generic error for content splitting failures\n */\nexport class ContentSplitterError extends SplitterError {}\n","import { MinimumChunkSizeError } from \"../errors\";\nimport type { ContentSplitter, ContentSplitterOptions } from \"./types\";\n\n/**\n * Splits code content while preserving language information and formatting.\n * Uses line boundaries for splitting and ensures each chunk is properly\n * wrapped with language-specific code block markers.\n */\nexport class CodeContentSplitter implements ContentSplitter {\n constructor(private options: ContentSplitterOptions) {}\n\n async split(content: string): Promise<string[]> {\n // Capture the full CommonMark info string verbatim (everything between the\n // opening ``` and the following newline) and re-emit it on each chunk's\n // rewritten opener. The previous `\\w+` regex only matched word characters\n // and failed for VitePress/Shiki tokens like `js{15-18} twoslash\n // [server.js]`, leaving the opener in place and producing a double-fenced\n // chunk. We deliberately preserve the entire info string — line-highlight\n // ranges, Twoslash hints, filename tabs and other renderer-specific\n // metadata — rather than reducing it to a single language word, so the\n // chunk remains a faithful copy of the source.\n const infoMatch = content.match(/^```([^\\n]*)\\n/);\n const infoString = (infoMatch?.[1] ?? \"\").trimEnd();\n const strippedContent = content.replace(/^```[^\\n]*\\n/, \"\").replace(/```\\s*$/, \"\");\n\n const lines = strippedContent.split(\"\\n\");\n const chunks: string[] = [];\n let currentChunkLines: string[] = [];\n\n for (const line of lines) {\n // Check if a single line with code block markers exceeds chunkSize\n const singleLineSize = this.wrap(line, infoString).length;\n if (singleLineSize > this.options.chunkSize) {\n throw new MinimumChunkSizeError(singleLineSize, this.options.chunkSize);\n }\n\n currentChunkLines.push(line);\n const newChunkContent = this.wrap(currentChunkLines.join(\"\\n\"), infoString);\n const newChunkSize = newChunkContent.length;\n\n if (newChunkSize > this.options.chunkSize && currentChunkLines.length > 1) {\n // remove last item\n const lastLine = currentChunkLines.pop();\n // wrap content and create chunk\n chunks.push(this.wrap(currentChunkLines.join(\"\\n\"), infoString));\n currentChunkLines = [lastLine as string];\n }\n }\n\n if (currentChunkLines.length > 0) {\n chunks.push(this.wrap(currentChunkLines.join(\"\\n\"), infoString));\n }\n\n return chunks;\n }\n\n protected wrap(content: string, infoString?: string | null): string {\n return `\\`\\`\\`${infoString || \"\"}\\n${content.replace(/\\n+$/, \"\")}\\n\\`\\`\\``;\n }\n}\n","/**\n * Tracks whether a given offset in a markdown string falls inside an open\n * fenced code block. Used by content splitters to avoid cutting chunks in the\n * middle of a fence, which would leave one chunk with an unmatched opener and\n * the next chunk with an unmatched closer.\n *\n * Follows CommonMark fence semantics for the cases that matter to us: a fence\n * is a line whose only leading non-whitespace content is three or more\n * identical backticks or three or more identical tildes, with up to three\n * leading spaces of indentation. The closing fence must use the same character\n * and at least as many of them as the opener. Backticks and tildes do not\n * pair across types.\n */\n\ninterface FenceRegion {\n /** Start offset of the line containing the opener. */\n startOffset: number;\n /** End offset (exclusive) of the line after the matching closer, or text.length if unclosed. */\n endOffset: number;\n}\n\ninterface LineInfo {\n content: string;\n /** Offset of the first character of this line in the source string. */\n offset: number;\n /** Length of the trailing newline (0 for the last line if no trailing newline). */\n newlineLength: number;\n}\n\n// Recognise a fence opener with any leading horizontal whitespace and any\n// number of blockquote (`>`) prefix markers. CommonMark itself restricts\n// fences to ≤3 leading spaces, but Turndown emits 4-space indented fences\n// inside list items and blockquote-prefixed fences inside `> ` blocks, and\n// downstream consumers (LLMs, renderers not strictly CommonMark-aware) still\n// treat the literal ``` / ~~~ as a fence. For our balance invariant we\n// recognise any leading indentation/blockquote-prefix combination.\nconst FENCE_PREFIX = \"[ \\\\t]*(?:>[ \\\\t]*)*\";\nconst FENCE_OPENER = new RegExp(`^${FENCE_PREFIX}(\\`{3,}|~{3,})`);\n\nfunction splitLinesWithOffsets(text: string): LineInfo[] {\n const lines: LineInfo[] = [];\n let offset = 0;\n while (offset <= text.length) {\n const nlIndex = text.indexOf(\"\\n\", offset);\n if (nlIndex === -1) {\n if (offset < text.length) {\n lines.push({ content: text.slice(offset), offset, newlineLength: 0 });\n }\n return lines;\n }\n lines.push({\n content: text.slice(offset, nlIndex),\n offset,\n newlineLength: 1,\n });\n offset = nlIndex + 1;\n }\n return lines;\n}\n\nfunction isClosingFence(line: string, delimiter: string, openerCount: number): boolean {\n // Match the opener's permissiveness (see FENCE_OPENER): allow any leading\n // horizontal whitespace plus blockquote markers.\n const closerRegex = new RegExp(\n `^${FENCE_PREFIX}\\\\${delimiter}{${openerCount},}[ \\\\t]*$`,\n );\n return closerRegex.test(line);\n}\n\n/**\n * Scan the input and return non-overlapping fence regions. Each region covers\n * the line containing the opener through the line containing the matching\n * closer (inclusive of trailing newlines). Unclosed openers produce a region\n * extending to the end of input.\n */\nfunction findFenceRegions(text: string): FenceRegion[] {\n const regions: FenceRegion[] = [];\n const lines = splitLinesWithOffsets(text);\n\n let i = 0;\n while (i < lines.length) {\n const opener = FENCE_OPENER.exec(lines[i].content);\n if (!opener) {\n i += 1;\n continue;\n }\n\n const delimiter = opener[1][0]; // '`' or '~'\n const count = opener[1].length;\n const startOffset = lines[i].offset;\n\n let closerLineIndex = -1;\n for (let j = i + 1; j < lines.length; j++) {\n if (isClosingFence(lines[j].content, delimiter, count)) {\n closerLineIndex = j;\n break;\n }\n }\n\n if (closerLineIndex === -1) {\n regions.push({ startOffset, endOffset: text.length });\n break;\n }\n\n const closerLine = lines[closerLineIndex];\n const endOffset =\n closerLine.offset + closerLine.content.length + closerLine.newlineLength;\n regions.push({ startOffset, endOffset });\n i = closerLineIndex + 1;\n }\n\n return regions;\n}\n\n/**\n * Returns true when `offset` falls strictly inside a fence — after the start\n * of an opener line and before the end of its closer line. An offset exactly\n * on a fence opener's start or exactly past a closer's end is outside.\n */\nexport function isOpenAt(text: string, offset: number): boolean {\n for (const region of findFenceRegions(text)) {\n if (offset > region.startOffset && offset < region.endOffset) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * If `candidateOffset` falls inside a fence, returns the offset immediately\n * after the corresponding closer (or `text.length` if the fence is unclosed).\n * Otherwise returns `candidateOffset` unchanged.\n */\nexport function nextSafeOffset(text: string, candidateOffset: number): number {\n for (const region of findFenceRegions(text)) {\n if (candidateOffset > region.startOffset && candidateOffset < region.endOffset) {\n return region.endOffset;\n }\n }\n return candidateOffset;\n}\n\n/**\n * Returns true if `chunk` ends while inside an open fence — i.e. its triple-\n * backtick/tilde count is odd in a way that leaves a dangling opener.\n */\nexport function hasOpenFenceAtEnd(chunk: string): boolean {\n const regions = findFenceRegions(chunk);\n if (regions.length === 0) return false;\n const last = regions[regions.length - 1];\n if (last.endOffset !== chunk.length) return false;\n // Region reached end of input — confirm it's because there was no closer.\n const lines = splitLinesWithOffsets(chunk.slice(last.startOffset));\n if (lines.length < 2) return true;\n const opener = FENCE_OPENER.exec(lines[0].content);\n if (!opener) return false;\n return !isClosingFence(lines[lines.length - 1].content, opener[1][0], opener[1].length);\n}\n","import { RecursiveCharacterTextSplitter } from \"@langchain/textsplitters\";\nimport { logger } from \"../../utils/logger\";\nimport { MinimumChunkSizeError } from \"../errors\";\nimport { hasOpenFenceAtEnd } from \"./fenceState\";\nimport type { ContentSplitter, ContentSplitterOptions } from \"./types\";\n\n/**\n * Splits text content using a hierarchical approach:\n * 1. Try splitting by paragraphs (double newlines)\n * 2. If chunks still too large, split by single newlines\n * 3. Finally, use word boundaries via LangChain's splitter\n *\n * Across all strategies the splitter preserves fenced code block balance: if\n * splitting would leave a chunk ending inside an open ``` or ~~~ fence, that\n * chunk is merged with the following chunk until the fence closes. When this\n * merging forces a chunk past `chunkSize`, the splitter accepts the oversize\n * chunk and emits a warning rather than break the fence.\n */\nexport class TextContentSplitter implements ContentSplitter {\n constructor(private options: ContentSplitterOptions) {}\n\n /**\n * Splits text content into chunks while trying to preserve semantic boundaries.\n * Prefers paragraph breaks, then line breaks, finally falling back to word boundaries.\n * Always preserves formatting - trimming should be done by higher-level splitters if needed.\n */\n async split(content: string): Promise<string[]> {\n if (content.length <= this.options.chunkSize) {\n return [content];\n }\n\n // Check for unsplittable content (e.g., a single word longer than chunkSize)\n const words = content.split(/\\s+/);\n const longestWord = words.reduce((max: string, word: string) =>\n word.length > max.length ? word : max,\n );\n if (longestWord.length > this.options.chunkSize) {\n throw new MinimumChunkSizeError(longestWord.length, this.options.chunkSize);\n }\n\n // First try splitting by paragraphs (double newlines)\n const paragraphChunks = this.mergeForFenceBalance(\n this.splitByParagraphs(content),\n \"\",\n );\n if (this.areChunksValid(paragraphChunks)) {\n // No merging for paragraph chunks; they are already semantically separated\n return paragraphChunks;\n }\n\n // If that doesn't work, try splitting by single newlines\n const lineChunks = this.mergeForFenceBalance(this.splitByLines(content), \"\");\n if (this.areChunksValid(lineChunks)) {\n return this.mergeChunks(lineChunks, \"\"); // No separator needed - newlines are preserved in chunks\n }\n\n // Finally, fall back to word-based splitting using LangChain. Re-merge for\n // fence balance after word splitting, then collapse small chunks. Any chunk\n // still over `chunkSize` after this step is an oversize-for-fence-balance\n // case — emit it and warn rather than break the fence.\n const wordChunks = this.mergeForFenceBalance(await this.splitByWords(content), \" \");\n const merged = this.mergeChunks(wordChunks, \" \");\n this.warnOversize(merged);\n return merged;\n }\n\n /**\n * Walks `chunks` left to right and merges adjacent chunks whenever the running\n * buffer ends inside an open fenced code block. Guarantees that every emitted\n * chunk has balanced fences (i.e. `hasOpenFenceAtEnd` returns false).\n */\n private mergeForFenceBalance(chunks: string[], separator: string): string[] {\n const result: string[] = [];\n let buffer = \"\";\n\n for (const chunk of chunks) {\n buffer = buffer ? `${buffer}${separator}${chunk}` : chunk;\n if (!hasOpenFenceAtEnd(buffer)) {\n result.push(buffer);\n buffer = \"\";\n }\n }\n\n if (buffer) {\n // No closing fence in the rest of the input — emit the dangling buffer as\n // a single chunk. The fence balance check downstream will catch this and\n // it will surface in logs as an oversize-chunk warning if applicable.\n result.push(buffer);\n }\n\n return result;\n }\n\n private warnOversize(chunks: string[]): void {\n for (const chunk of chunks) {\n if (chunk.length > this.options.chunkSize) {\n logger.warn(\n `⚠ TextContentSplitter emitted oversize chunk to preserve fence balance: ${chunk.length} > ${this.options.chunkSize}`,\n );\n }\n }\n }\n\n /**\n * Checks if all chunks are within the maximum size limit\n */\n private areChunksValid(chunks: string[]): boolean {\n return chunks.every((chunk) => chunk.length <= this.options.chunkSize);\n }\n\n /**\n * Splits text into chunks by paragraph boundaries (double newlines)\n * Preserves all formatting and whitespace including the paragraph separators\n */\n private splitByParagraphs(text: string): string[] {\n const chunks: string[] = [];\n let startPos = 0;\n\n // Find all paragraph boundaries\n const paragraphRegex = /\\n\\s*\\n/g;\n let match = paragraphRegex.exec(text);\n\n while (match !== null) {\n // Include the paragraph separator in the current chunk\n const endPos = match.index + match[0].length;\n const chunk = text.slice(startPos, endPos);\n if (chunk.length > 2) {\n chunks.push(chunk);\n }\n startPos = endPos;\n match = paragraphRegex.exec(text);\n }\n\n // Add the remaining text\n if (startPos < text.length) {\n const remainingChunk = text.slice(startPos);\n if (remainingChunk.length > 2) {\n chunks.push(remainingChunk);\n }\n }\n\n return chunks.filter(Boolean);\n }\n\n /**\n * Splits text into chunks by line boundaries\n * Preserves all formatting and whitespace, including newlines at the end of each line\n */\n private splitByLines(text: string): string[] {\n const chunks: string[] = [];\n let startPos = 0;\n\n // Find all line boundaries\n for (let i = 0; i < text.length; i++) {\n if (text[i] === \"\\n\") {\n // Include the newline in the current chunk\n const chunk = text.slice(startPos, i + 1);\n chunks.push(chunk);\n startPos = i + 1;\n }\n }\n\n // Add the remaining text (if any) without a trailing newline\n if (startPos < text.length) {\n chunks.push(text.slice(startPos));\n }\n\n return chunks;\n }\n\n /**\n * Uses LangChain's recursive splitter for word-based splitting as a last resort\n */\n private async splitByWords(text: string): Promise<string[]> {\n const splitter = new RecursiveCharacterTextSplitter({\n chunkSize: this.options.chunkSize,\n chunkOverlap: 0,\n });\n\n const chunks = await splitter.splitText(text);\n return chunks;\n }\n\n /**\n * Attempts to merge small chunks with previous chunks to minimize fragmentation.\n * Only merges if combined size is within maxChunkSize.\n */\n protected mergeChunks(chunks: string[], separator: string): string[] {\n const mergedChunks: string[] = [];\n let currentChunk: string | null = null;\n\n for (const chunk of chunks) {\n if (currentChunk === null) {\n currentChunk = chunk;\n continue;\n }\n\n const currentChunkSize = this.getChunkSize(currentChunk);\n const nextChunkSize = this.getChunkSize(chunk);\n\n if (currentChunkSize + nextChunkSize + separator.length <= this.options.chunkSize) {\n // Merge chunks\n currentChunk = `${currentChunk}${separator}${chunk}`;\n } else {\n // Add the current chunk to the result and start a new one\n mergedChunks.push(currentChunk);\n currentChunk = chunk;\n }\n }\n\n if (currentChunk) {\n mergedChunks.push(currentChunk);\n }\n\n return mergedChunks;\n }\n\n protected getChunkSize(chunk: string): number {\n return chunk.length;\n }\n\n protected wrap(content: string): string {\n return content;\n }\n}\n","import { TextContentSplitter } from \"./TextContentSplitter\";\nimport type { ContentSplitter, ContentSplitterOptions } from \"./types\";\n\nexport class ListContentSplitter implements ContentSplitter {\n private textSplitter: TextContentSplitter;\n\n constructor(private options: ContentSplitterOptions) {\n this.textSplitter = new TextContentSplitter(options);\n }\n\n async split(content: string): Promise<string[]> {\n if (content.length <= this.options.chunkSize) {\n return [content];\n }\n\n // Split by list items\n // This regex looks for lines starting with -, *, or digits followed by dot, at the start of line or after newline\n // It captures the delimiter to keep it\n const listItems = this.splitByListItems(content);\n\n // Merge items that fit together\n const mergedChunks = this.mergeChunks(listItems);\n\n // Check if any chunk is still too large\n const finalChunks: string[] = [];\n for (const chunk of mergedChunks) {\n if (chunk.length > this.options.chunkSize) {\n // Fallback to text splitting for huge items\n const subChunks = await this.textSplitter.split(chunk);\n finalChunks.push(...subChunks);\n } else {\n finalChunks.push(chunk);\n }\n }\n\n return finalChunks;\n }\n\n private splitByListItems(content: string): string[] {\n const lines = content.split(\"\\n\");\n const items: string[] = [];\n let currentItem = \"\";\n\n // Regex for list item start: optional whitespace, then -, *, or 1., then space\n const listItemRegex = /^\\s*([-*]|\\d+\\.)\\s/;\n\n for (const line of lines) {\n if (listItemRegex.test(line)) {\n // Start of new item\n if (currentItem) {\n items.push(currentItem);\n }\n currentItem = line;\n } else {\n // Continuation of current item (or content before first item)\n if (currentItem) {\n currentItem += `\\n${line}`;\n } else {\n // Content before first list item? Should rarely happen if we passed a list\n // But valid markdown can have text before list in same block if not carefully separated\n currentItem = line;\n }\n }\n }\n\n if (currentItem) {\n items.push(currentItem);\n }\n\n return items;\n }\n\n private mergeChunks(chunks: string[]): string[] {\n const mergedChunks: string[] = [];\n let currentChunk = \"\";\n\n for (const chunk of chunks) {\n if (!currentChunk) {\n currentChunk = chunk;\n continue;\n }\n\n // Check if adding this chunk exceeds size\n // We add a newline separator since we split by lines originally\n if (currentChunk.length + 1 + chunk.length <= this.options.chunkSize) {\n currentChunk += `\\n${chunk}`;\n } else {\n mergedChunks.push(currentChunk);\n currentChunk = chunk;\n }\n }\n\n if (currentChunk) {\n mergedChunks.push(currentChunk);\n }\n\n return mergedChunks;\n }\n}\n","import { MinimumChunkSizeError } from \"../errors\";\nimport type { ContentSplitter, ContentSplitterOptions } from \"./types\";\n\n/**\n * Interface representing the structure of a parsed markdown table\n */\ninterface ParsedTable {\n headers: string[];\n separator: string;\n rows: string[];\n}\n\n/**\n * Splits table content while preserving headers and table formatting.\n * Each chunk maintains the table structure with headers and separator row.\n */\nexport class TableContentSplitter implements ContentSplitter {\n constructor(private options: ContentSplitterOptions) {}\n\n /**\n * Splits table content into chunks while preserving table structure\n */\n async split(content: string): Promise<string[]> {\n const parsedTable = this.parseTable(content);\n if (!parsedTable) {\n return [content];\n }\n\n const { headers, rows } = parsedTable;\n\n const chunks: string[] = [];\n let currentRows: string[] = [];\n\n for (const row of rows) {\n // Check if a single row with headers exceeds chunkSize\n const singleRowSize = this.wrap(row, headers).length;\n if (singleRowSize > this.options.chunkSize) {\n throw new MinimumChunkSizeError(singleRowSize, this.options.chunkSize);\n }\n\n const newChunkContent = this.wrap([...currentRows, row].join(\"\\n\"), headers);\n const newChunkSize = newChunkContent.length;\n if (newChunkSize > this.options.chunkSize && currentRows.length > 0) {\n // Add current chunk, start new\n chunks.push(this.wrap(currentRows.join(\"\\n\"), headers));\n currentRows = [row];\n } else {\n currentRows.push(row);\n }\n }\n\n if (currentRows.length > 0) {\n chunks.push(this.wrap(currentRows.join(\"\\n\"), headers));\n }\n\n // No merging of table chunks\n return chunks;\n }\n\n protected wrap(content: string, headers: string[]): string {\n const headerRow = `| ${headers.join(\" | \")} |`;\n const separatorRow = `|${headers.map(() => \"---\").join(\"|\")}|`;\n return [headerRow, separatorRow, content].join(\"\\n\");\n }\n\n private parseTable(content: string): ParsedTable | null {\n const lines = content.trim().split(\"\\n\");\n if (lines.length < 3) return null; // Need at least headers, separator, and one data row\n\n const headers = this.parseRow(lines[0]);\n if (!headers) return null;\n\n const separator = lines[1];\n if (!this.isValidSeparator(separator)) return null;\n\n const rows = lines.slice(2).filter((row) => row.trim() !== \"\");\n\n return { headers, separator, rows };\n }\n\n /**\n * Parses a table row into cells\n */\n private parseRow(row: string): string[] | null {\n if (!row.includes(\"|\")) return null;\n return row\n .split(\"|\")\n .map((cell) => cell.trim())\n .filter((cell) => cell !== \"\");\n }\n\n /**\n * Validates the separator row of the table\n */\n private isValidSeparator(separator: string): boolean {\n return separator.includes(\"|\") && /^\\|?[\\s-|]+\\|?$/.test(separator);\n }\n}\n","import { RecursiveCharacterTextSplitter } from \"@langchain/textsplitters\";\nimport matter from \"gray-matter\";\nimport remarkGfm from \"remark-gfm\";\nimport remarkHtml from \"remark-html\";\nimport remarkParse from \"remark-parse\";\nimport TurndownService from \"turndown\";\nimport { unified } from \"unified\";\nimport { createJSDOM } from \"../utils/dom\";\nimport { logger } from \"../utils/logger\";\nimport { fullTrim } from \"../utils/string\";\nimport { ContentSplitterError, MinimumChunkSizeError } from \"./errors\";\nimport { CodeContentSplitter } from \"./splitters/CodeContentSplitter\";\nimport { ListContentSplitter } from \"./splitters/ListContentSplitter\";\nimport { TableContentSplitter } from \"./splitters/TableContentSplitter\";\nimport { TextContentSplitter } from \"./splitters/TextContentSplitter\";\nimport type { Chunk, DocumentSplitter, SectionContentType } from \"./types\";\n\n/**\n * Removes an explicit anchor annotation from the end of a heading.\n *\n * Markdown dialects let authors pin a heading's id rather than let it be\n * derived. MDX writes it as a comment and several Markdown extensions use\n * `{#adding-styles}`. Neither is prose — both are instructions to the renderer\n * — yet they survive into the text we index, landing in the embedded content\n * and in the section path shown to readers.\n *\n * The MDX form reaches here already chewed: this runs after markdown has been\n * converted to HTML, and the conversion consumes the comment's asterisks as\n * emphasis markers, so `{/*adding-styles*\\/}` arrives as `{/adding-styles/}`.\n * Both spellings are matched, since which one appears depends on the converter.\n *\n * Anchored to the end of the string, so a heading that legitimately contains\n * braces earlier on — `Use {count} in JSX` — keeps them.\n *\n * @param heading The heading text as rendered.\n * @returns The heading without a trailing anchor annotation.\n */\nfunction stripHeadingAnchors(heading: string): string {\n return heading\n .replace(/\\s*\\{\\/\\*?[\\s\\S]*?\\*?\\/\\}\\s*$/, \"\")\n .replace(/\\s*\\{#[^}\\s]*\\}\\s*$/, \"\")\n .trimEnd();\n}\n\n/**\n * Represents a section of content within a document,\n * typically defined by a heading\n */\ninterface DocumentSection {\n level: number;\n path: string[]; // Full path including parent headings\n content: {\n type: SectionContentType;\n text: string;\n }[];\n}\n\n/**\n * Splits markdown documents into semantic chunks while preserving\n * structure and distinguishing between different content types.\n *\n * The splitting process happens in two steps:\n * 1. Split document into sections based on headings (H1-H3 only)\n * 2. Split section content into smaller chunks based on preferredChunkSize\n */\nexport class SemanticMarkdownSplitter implements DocumentSplitter {\n private turndownService: TurndownService;\n public textSplitter: TextContentSplitter;\n public codeSplitter: CodeContentSplitter;\n public tableSplitter: TableContentSplitter;\n public listSplitter: ListContentSplitter;\n\n constructor(\n private preferredChunkSize: number,\n private maxChunkSize: number,\n ) {\n this.turndownService = new TurndownService({\n headingStyle: \"atx\",\n hr: \"---\",\n bulletListMarker: \"-\",\n codeBlockStyle: \"fenced\",\n emDelimiter: \"_\",\n strongDelimiter: \"**\",\n linkStyle: \"inlined\",\n });\n\n // Add table rule to preserve markdown table format\n this.turndownService.addRule(\"table\", {\n filter: [\"table\"],\n replacement: (_content, node) => {\n const table = node as HTMLTableElement;\n const headers = Array.from(table.querySelectorAll(\"th\")).map(\n (th) => th.textContent?.trim() || \"\",\n );\n const rows = Array.from(table.querySelectorAll(\"tr\")).filter(\n (tr) => !tr.querySelector(\"th\"),\n );\n\n if (headers.length === 0 && rows.length === 0) return \"\";\n\n let markdown = \"\\n\";\n if (headers.length > 0) {\n markdown += `| ${headers.join(\" | \")} |\\n`;\n markdown += `|${headers.map(() => \"---\").join(\"|\")}|\\n`;\n }\n\n for (const row of rows) {\n const cells = Array.from(row.querySelectorAll(\"td\")).map(\n (td) => td.textContent?.trim() || \"\",\n );\n markdown += `| ${cells.join(\" | \")} |\\n`;\n }\n\n return markdown;\n },\n });\n\n // Text splitter uses preferred chunk size (keeps paragraphs together if possible)\n this.textSplitter = new TextContentSplitter({\n chunkSize: this.preferredChunkSize,\n });\n // Code/table splitters use the hard chunk size (avoid splitting unless necessary)\n this.codeSplitter = new CodeContentSplitter({\n chunkSize: this.maxChunkSize,\n });\n this.tableSplitter = new TableContentSplitter({\n chunkSize: this.maxChunkSize,\n });\n this.listSplitter = new ListContentSplitter({\n chunkSize: this.preferredChunkSize, // Lists prefer to stay together, so use preferred size\n });\n }\n\n /**\n * Main entry point for splitting markdown content\n */\n async splitText(markdown: string, _contentType?: string): Promise<Chunk[]> {\n // Note: JSON content is now handled by dedicated JsonDocumentSplitter in JsonPipeline\n // This splitter focuses on markdown, HTML, and plain text content\n\n let contentToProcess = markdown;\n let frontmatterBlock: string | null = null;\n\n try {\n // Check for frontmatter\n const file = matter(markdown);\n if (\n SemanticMarkdownSplitter.hasClosedFrontmatterBlock(markdown) &&\n SemanticMarkdownSplitter.hasFrontmatterData(file.data)\n ) {\n frontmatterBlock = SemanticMarkdownSplitter.extractRawFrontmatter(markdown, file);\n contentToProcess = file.content;\n }\n } catch (err) {\n // Log warning but continue with original content if parsing fails\n logger.warn(\n `Failed to parse frontmatter in splitter: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n\n // For markdown, HTML, or plain text, process normally\n const html = await this.markdownToHtml(contentToProcess);\n const dom = await this.parseHtml(html);\n const sections = await this.splitIntoSections(dom);\n const chunks = await this.splitSectionContent(sections);\n\n if (frontmatterBlock) {\n // Size-bounded like every other chunk. It is prepended after splitting,\n // so nothing else would bound it, and a page carrying a long `summary:`\n // or a generated field list produced a single chunk many times the limit.\n //\n // A block that cannot be divided — one unbroken token longer than the\n // limit, such as an embedded key or data URI — keeps its oversized chunk\n // rather than failing the page. That is the behaviour this replaces, so\n // the worst case is unchanged and the common case is now bounded.\n let parts: string[];\n try {\n parts = await this.textSplitter.split(frontmatterBlock);\n } catch (err) {\n logger.warn(\n `Keeping an oversized frontmatter chunk; it could not be split: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n parts = [frontmatterBlock];\n }\n chunks.unshift(\n ...parts.map(\n (content): Chunk => ({\n types: [\"frontmatter\"],\n content,\n section: { level: 0, path: [] },\n }),\n ),\n );\n }\n\n return chunks;\n }\n\n /**\n * Reports whether the document actually opens with a closed frontmatter block.\n *\n * gray-matter has no delimiter to stop at when a document opens with a\n * thematic break and never closes it, so it parses the entire body as YAML.\n * When that body happens to be a valid mapping — a page whose first line is\n * `---` followed by `Replacement: use the createClient helper`, or any\n * `Key: value` prose — the parse looks exactly like real frontmatter, and the\n * whole document is filed as one frontmatter chunk with no headings and no\n * sections. Turndown renders `<hr>` as `---`, so HTML pages reach this too.\n *\n * Checked against the source rather than the parse, because only the source\n * says whether a closing delimiter was ever there.\n *\n * @param markdown The original markdown passed to gray-matter.\n * @returns True when a `---` delimited block opens the document and closes.\n */\n private static hasClosedFrontmatterBlock(markdown: string): boolean {\n return /^\\uFEFF?---[^\\S\\n]*\\r?\\n[\\s\\S]*?\\r?\\n---[^\\S\\n]*(\\r?\\n|$)/.test(markdown);\n }\n\n /**\n * Reports whether a gray-matter parse produced real frontmatter.\n *\n * gray-matter hands back whatever YAML parsed to, which is not necessarily a mapping.\n * A document opening with a thematic break (`---`) has its entire body parsed as YAML\n * and can yield a bare string or array, and `Object.keys` on those returns character or\n * element indices — so a naive emptiness check treats the whole document as frontmatter\n * and discards its heading structure. Only a plain object with at least one key counts.\n *\n * @param data The `data` property of a gray-matter result.\n * @returns True when the parse yielded a non-empty mapping.\n */\n private static hasFrontmatterData(data: unknown): data is Record<string, unknown> {\n return (\n typeof data === \"object\" &&\n data !== null &&\n !Array.isArray(data) &&\n Object.keys(data).length > 0\n );\n }\n\n /**\n * Recovers the raw frontmatter block, including its delimiters, from the original markdown.\n *\n * gray-matter exposes the raw block as `file.matter`, but that property is non-enumerable\n * and the library caches parsed results: a repeated parse of the same string returns a\n * shallow `Object.assign({}, cached)` copy, which drops it. Our pipeline parses the same\n * content more than once (see MarkdownMetadataExtractorMiddleware), so `file.matter` is\n * `undefined` here in practice. `file.content` is the input with the frontmatter block\n * stripped from the front, so the block is recovered by slicing that suffix off instead,\n * which also preserves the author's original formatting and YAML comments.\n *\n * @param markdown The original markdown passed to gray-matter.\n * @param file The parsed gray-matter result for that markdown.\n * @returns The frontmatter block with delimiters, e.g. `---\\ntitle: Quick Start\\n---`.\n */\n private static extractRawFrontmatter(\n markdown: string,\n file: matter.GrayMatterFile<string>,\n ): string {\n if (markdown.endsWith(file.content)) {\n const block = markdown.slice(0, markdown.length - file.content.length).trimEnd();\n if (block.length > 0) {\n return block;\n }\n }\n // Defensive fallback: re-serialize the parsed data if the content is not a suffix.\n return matter.stringify(\"\", file.data).trimEnd();\n }\n\n /**\n * Step 1: Split document into sections based on H1-H6 headings,\n * as well as code blocks, tables, lists, blockquotes, and media.\n */\n private async splitIntoSections(dom: Document): Promise<DocumentSection[]> {\n const body = dom.querySelector(\"body\");\n if (!body) {\n throw new Error(\"Invalid HTML structure: no body element found\");\n }\n\n let currentSection = this.createRootSection();\n const sections: DocumentSection[] = [];\n const stack: DocumentSection[] = [currentSection];\n\n // Process each child of the body\n for (const element of Array.from(body.children)) {\n const headingMatch = element.tagName.match(/H([1-6])/);\n\n if (headingMatch) {\n // Create new section for H1-H6 heading\n const level = Number.parseInt(headingMatch[1], 10);\n const title = stripHeadingAnchors(fullTrim(element.textContent || \"\"));\n\n // Pop sections from stack until we find the parent level\n while (stack.length > 1 && stack[stack.length - 1].level >= level) {\n stack.pop();\n }\n\n // Start new section with the header\n currentSection = {\n level,\n path: [\n ...stack.slice(1).reduce((acc: string[], s) => {\n const lastPath = s.path[s.path.length - 1];\n if (lastPath) acc.push(lastPath);\n return acc;\n }, []),\n title,\n ],\n content: [\n {\n type: \"heading\",\n text: `${\"#\".repeat(level)} ${title}`,\n },\n ],\n };\n\n sections.push(currentSection);\n stack.push(currentSection);\n } else if (element.tagName === \"PRE\") {\n // Code blocks are kept as separate chunks\n const code = element.querySelector(\"code\");\n const language = code?.className.replace(\"language-\", \"\") || \"\";\n const content = code?.textContent || element.textContent || \"\";\n const markdown = `${\"```\"}${language}\\n${content}\\n${\"```\"}`;\n\n currentSection = {\n level: currentSection.level,\n path: currentSection.path,\n content: [\n {\n type: \"code\",\n text: markdown,\n },\n ],\n } satisfies DocumentSection;\n sections.push(currentSection);\n } else if (element.tagName === \"TABLE\") {\n this.addSectionFromElement(element, \"table\", currentSection, sections);\n } else if (element.tagName === \"UL\" || element.tagName === \"OL\") {\n this.addSectionFromElement(element, \"list\", currentSection, sections);\n } else if (element.tagName === \"BLOCKQUOTE\") {\n this.addSectionFromElement(element, \"blockquote\", currentSection, sections);\n } else if (element.tagName === \"IMG\") {\n this.addSectionFromElement(element, \"media\", currentSection, sections);\n } else if (\n element.tagName === \"P\" &&\n element.children.length === 1 &&\n element.children[0].tagName === \"IMG\" &&\n (!element.textContent || element.textContent.trim() === \"\")\n ) {\n // Handle images wrapped in paragraphs\n this.addSectionFromElement(\n element.children[0],\n \"media\",\n currentSection,\n sections,\n );\n } else if (element.tagName === \"HR\") {\n } else {\n const markdown = fullTrim(this.turndownService.turndown(element.innerHTML));\n if (markdown) {\n // Create a new section for the text content\n currentSection = {\n level: currentSection.level,\n path: currentSection.path,\n content: [\n {\n type: \"text\",\n text: markdown,\n },\n ],\n } satisfies DocumentSection;\n sections.push(currentSection);\n }\n }\n }\n\n return sections;\n }\n\n /**\n * Helper to create a new section from a specific DOM element type\n */\n private addSectionFromElement(\n element: Element,\n type: SectionContentType,\n currentSection: DocumentSection,\n sections: DocumentSection[],\n ): void {\n const markdown = fullTrim(this.turndownService.turndown(element.outerHTML));\n const newSection = {\n level: currentSection.level,\n path: currentSection.path,\n content: [\n {\n type,\n text: markdown,\n },\n ],\n } satisfies DocumentSection;\n sections.push(newSection);\n }\n\n /**\n * Step 2: Split section content into smaller chunks\n */\n private async splitSectionContent(sections: DocumentSection[]): Promise<Chunk[]> {\n const chunks: Chunk[] = [];\n\n for (const section of sections) {\n for (const content of section.content) {\n let splitContent: string[] = [];\n\n try {\n switch (content.type) {\n case \"heading\":\n case \"text\":\n case \"blockquote\":\n case \"media\": {\n // Trim markdown content before splitting\n splitContent = await this.textSplitter.split(fullTrim(content.text));\n break;\n }\n case \"code\": {\n splitContent = await this.codeSplitter.split(content.text);\n break;\n }\n case \"table\": {\n splitContent = await this.tableSplitter.split(content.text);\n break;\n }\n case \"list\": {\n splitContent = await this.listSplitter.split(content.text);\n break;\n }\n default: {\n // Fallback for any unknown type\n splitContent = await this.textSplitter.split(fullTrim(content.text));\n }\n }\n } catch (err) {\n // If it's a MinimumChunkSizeError, use RecursiveCharacterTextSplitter directly\n if (err instanceof MinimumChunkSizeError) {\n logger.warn(\n `⚠ Cannot split ${content.type} chunk normally, using RecursiveCharacterTextSplitter: ${err.message}`,\n );\n\n // Create a RecursiveCharacterTextSplitter with aggressive settings to ensure splitting\n const splitter = new RecursiveCharacterTextSplitter({\n chunkSize: this.maxChunkSize,\n chunkOverlap: Math.min(20, Math.floor(this.maxChunkSize * 0.1)),\n // Use more aggressive separators including empty string as last resort\n separators: [\n \"\\n\\n\",\n \"\\n\",\n \" \",\n \"\\t\",\n \".\",\n \",\",\n \";\",\n \":\",\n \"-\",\n \"(\",\n \")\",\n \"[\",\n \"]\",\n \"{\",\n \"}\",\n \"\",\n ],\n });\n\n const chunks = await splitter.splitText(content.text);\n if (chunks.length === 0) {\n // If still no chunks, use the most extreme approach: just truncate\n splitContent = [content.text.substring(0, this.maxChunkSize)];\n } else {\n splitContent = chunks;\n }\n } else {\n // Convert other error message to string, handling non-Error objects\n const errMessage = err instanceof Error ? err.message : String(err);\n throw new ContentSplitterError(\n `Failed to split ${content.type} content: ${errMessage}`,\n );\n }\n }\n\n // Create chunks from split content\n chunks.push(\n ...splitContent.map(\n (text): Chunk => ({\n types: [content.type],\n content: text,\n section: {\n level: section.level,\n path: section.path,\n },\n }),\n ),\n );\n }\n }\n\n return chunks;\n }\n\n /**\n * Helper to create the root section\n */\n private createRootSection(): DocumentSection {\n return {\n level: 0,\n path: [],\n content: [],\n };\n }\n\n /**\n * Convert markdown to HTML using remark\n */\n private async markdownToHtml(markdown: string): Promise<string> {\n const html = await unified()\n .use(remarkParse)\n .use(remarkGfm)\n .use(remarkHtml)\n .process(markdown);\n\n return `<!DOCTYPE html>\n <html>\n <body>\n ${String(html)}\n </body>\n </html>`;\n }\n\n /**\n * Parse HTML\n */\n private async parseHtml(html: string): Promise<Document> {\n // Use createJSDOM which includes default options like virtualConsole\n const { window } = createJSDOM(html);\n return window.document;\n }\n}\n","import { ScraperError } from \"../../utils/errors\";\nimport type { ContentFetcher, RawContent } from \"../fetcher/types\";\nimport type { ContentProcessorMiddleware, MiddlewareContext } from \"../middleware/types\";\nimport type { ScraperOptions } from \"../types\";\nimport type { ContentPipeline, PipelineResult } from \"./types\";\n\n/**\n * Base class for content processing pipelines.\n * Provides common functionality for executing middleware stacks.\n */\nexport class BasePipeline implements ContentPipeline {\n /**\n * Determines if this pipeline can process content with the given MIME type.\n * Must be implemented by derived classes.\n */\n public canProcess(_mimeType: string, _content?: Buffer): boolean {\n throw new Error(\"Method not implemented.\");\n }\n\n /**\n * Processes the raw content through the pipeline.\n * Must be implemented by derived classes.\n */\n public async process(\n _rawContent: RawContent,\n _options: ScraperOptions,\n _fetcher?: ContentFetcher,\n ): Promise<PipelineResult> {\n throw new Error(\"Method not implemented.\");\n }\n\n /**\n * Cleanup resources used by this pipeline.\n * Default implementation does nothing - override in derived classes as needed.\n */\n public async close(): Promise<void> {\n // No-op by default\n }\n\n /**\n * Executes a middleware stack on the given context.\n * This is a utility method used by derived pipeline classes.\n *\n * A middleware error is recorded in `context.errors` and the pipeline goes on\n * with what is left, except a `ScraperError`, which fails the page.\n *\n * @param middleware - The middleware stack to execute\n * @param context - The context to process\n * @throws {ScraperError} When a middleware throws one.\n */\n protected async executeMiddlewareStack(\n middleware: ContentProcessorMiddleware[],\n context: MiddlewareContext,\n ): Promise<void> {\n let index = -1;\n const dispatch = async (i: number): Promise<void> => {\n if (i <= index) throw new Error(\"next() called multiple times\");\n index = i;\n const mw = middleware[i];\n if (!mw) return;\n await mw.process(context, dispatch.bind(null, i + 1));\n };\n\n try {\n await dispatch(0);\n } catch (error) {\n if (error instanceof ScraperError) {\n throw error;\n }\n context.errors.push(error instanceof Error ? error : new Error(String(error)));\n }\n }\n}\n","/**\n * DocumentPipeline - Processes binary document formats using Xberg for text extraction,\n * then splits semantically.\n *\n * Supported formats:\n * - PDF (.pdf)\n * - Modern Office: Word (.docx), Excel (.xlsx), PowerPoint (.pptx)\n * - Legacy Office: Word (.doc), Excel (.xls), PowerPoint (.ppt)\n * - OpenDocument: Text (.odt), Spreadsheet (.ods), Presentation (.odp)\n * - Rich Text Format (.rtf)\n * - eBooks: EPUB (.epub), FictionBook (.fb2)\n * - Jupyter Notebook (.ipynb)\n *\n * The pipeline requests Markdown output from Xberg (`@xberg-io/xberg`) via\n * `outputFormat: OutputFormat.Markdown`, aligning with the project's Markdown-first\n * processing pipeline. Xberg's Markdown renderer emits fully structured output for\n * every format — including spreadsheets, where each sheet appears as a heading\n * followed by a Markdown table — so `content` is the preferred representation and\n * `tables[].markdown` only serves as a fallback when `content` comes back empty.\n *\n * Documents exceeding the configured maximum size are skipped with a warning.\n */\n\nimport {\n type ExtractedDocument,\n ExtractInputKind,\n extract,\n OutputFormat,\n} from \"@xberg-io/xberg\";\nimport { GreedySplitter } from \"../../splitter/GreedySplitter\";\nimport { SemanticMarkdownSplitter } from \"../../splitter/SemanticMarkdownSplitter\";\nimport type { AppConfig } from \"../../utils/config\";\nimport { logger } from \"../../utils/logger\";\nimport { MimeTypeUtils } from \"../../utils/mimeTypeUtils\";\nimport type { RawContent } from \"../fetcher/types\";\nimport type { ScraperOptions } from \"../types\";\nimport { BasePipeline } from \"./BasePipeline\";\nimport type { PipelineResult } from \"./types\";\n\nexport class DocumentPipeline extends BasePipeline {\n private readonly splitter: GreedySplitter;\n private readonly maxSize: number;\n\n constructor(config: AppConfig) {\n super();\n this.maxSize = config.scraper.document.maxSize;\n\n const semanticSplitter = new SemanticMarkdownSplitter(\n config.splitter.preferredChunkSize,\n config.splitter.maxChunkSize,\n );\n this.splitter = new GreedySplitter(\n semanticSplitter,\n config.splitter.minChunkSize,\n config.splitter.preferredChunkSize,\n config.splitter.maxChunkSize,\n );\n }\n\n canProcess(mimeType: string): boolean {\n return MimeTypeUtils.isSupportedDocument(mimeType);\n }\n\n async process(\n rawContent: RawContent,\n _options: ScraperOptions,\n ): Promise<PipelineResult> {\n const buffer = Buffer.isBuffer(rawContent.content)\n ? rawContent.content\n : Buffer.from(rawContent.content);\n\n // Check size limit\n if (buffer.length > this.maxSize) {\n logger.warn(\n `Document exceeds size limit (${buffer.length} > ${this.maxSize}): ${rawContent.source}`,\n );\n return {\n title: null,\n contentType: rawContent.mimeType,\n textContent: null,\n links: [],\n errors: [new Error(`Document exceeds maximum size of ${this.maxSize} bytes`)],\n chunks: [],\n };\n }\n\n // Resolve the actual MIME type when the server sends a generic type.\n // This is common with S3, CDNs, and other file storage services that\n // serve documents as application/octet-stream.\n const mimeType = this.resolveMimeType(rawContent.mimeType, rawContent.source);\n if (!mimeType) {\n logger.warn(\n `Could not determine document type for ${rawContent.source} (MIME type: ${rawContent.mimeType})`,\n );\n return {\n title: null,\n contentType: rawContent.mimeType,\n textContent: null,\n links: [],\n errors: [new Error(\"Could not determine document type\")],\n chunks: [],\n };\n }\n\n try {\n const result = await extract(\n { kind: ExtractInputKind.Bytes, bytes: buffer, mimeType },\n { outputFormat: OutputFormat.Markdown },\n );\n\n // `extract` returns an envelope that can carry several documents. A\n // single-input call yields at most one; a per-input failure is reported\n // in `errors` instead of throwing.\n const document = result.results?.[0];\n if (!document) {\n const reason = result.errors?.[0]?.message;\n throw new Error(\n reason\n ? `Extraction produced no result: ${reason}`\n : \"Extraction produced no result\",\n );\n }\n\n const content = this.extractContent(document);\n\n if (!content) {\n logger.warn(`No content extracted from document: ${rawContent.source}`);\n return {\n title: null,\n contentType: rawContent.mimeType,\n textContent: null,\n links: [],\n errors: [],\n chunks: [],\n };\n }\n\n // Use title from Xberg metadata, fall back to filename\n const title = document.metadata?.title || this.extractFilename(rawContent.source);\n\n // Split the content (Xberg output is Markdown)\n const chunks = await this.splitter.splitText(content, \"text/markdown\");\n\n return {\n title,\n contentType: \"text/markdown\", // Output is always markdown\n textContent: content,\n links: [], // Documents don't have extractable links\n errors: [],\n chunks,\n };\n } catch (error) {\n // Surface the underlying cause chain so environmental failures\n // (e.g. missing native bindings, glibc mismatches) are diagnosable\n // from the logs instead of silently dropping documents. Each cause's\n // message is truncated to keep potentially binary data out of logs.\n const errorName = error instanceof Error ? error.name : \"UnknownError\";\n const reasons = collectErrorReasons(error);\n const safeMessage = `Failed to convert document: ${errorName}`;\n const detail = reasons.length > 0 ? ` — ${reasons.join(\" | \")}` : \"\";\n\n logger.error(`❌ ${safeMessage} (${mimeType}) for ${rawContent.source}${detail}`);\n\n return {\n title: null,\n contentType: rawContent.mimeType,\n textContent: null,\n links: [],\n errors: [new Error(safeMessage)],\n chunks: [],\n };\n }\n }\n\n /**\n * Selects the best content representation from an Xberg extraction result.\n *\n * `content` is preferred for every format: Xberg's Markdown renderer emits the\n * full document structure there, including sheet headings and Markdown tables\n * for spreadsheets, so it is always a superset of `tables[].markdown`. The\n * concatenated table Markdown is only used when `content` comes back empty.\n */\n private extractContent(document: ExtractedDocument): string | null {\n const content = document.content ?? \"\";\n if (content.trim().length > 0) {\n return content;\n }\n\n const tableContent = (document.tables ?? [])\n .map((t) => t.markdown ?? \"\")\n .filter((markdown) => markdown.trim().length > 0)\n .join(\"\\n\\n\");\n\n return tableContent.length > 0 ? tableContent : null;\n }\n\n /**\n * Resolves the effective MIME type for document processing.\n * When the provided MIME type is generic (`application/octet-stream`), attempts to\n * detect the actual type from the source URL's file extension. Returns `null` if\n * the resolved type is not a supported document format.\n */\n private resolveMimeType(mimeType: string, source: string): string | null {\n if (mimeType !== \"application/octet-stream\") {\n return mimeType;\n }\n\n // detectMimeTypeFromPath handles query params and hash fragments internally\n const detected = MimeTypeUtils.detectMimeTypeFromPath(source);\n if (detected && MimeTypeUtils.isSupportedDocument(detected)) {\n return detected;\n }\n\n return null;\n }\n\n private extractFilename(source: string): string | null {\n try {\n const url = new URL(source);\n const pathname = url.pathname;\n const lastSlash = pathname.lastIndexOf(\"/\");\n return pathname.substring(lastSlash + 1) || null;\n } catch {\n const lastSlash = source.lastIndexOf(\"/\");\n return source.substring(lastSlash + 1) || null;\n }\n }\n}\n\n/**\n * Maximum length (in characters) of any single error message included in\n * extraction failure logs. Xberg errors may embed parts of the input\n * document; truncating defends the logs against accidental binary dumps\n * while still surfacing enough text to diagnose the root cause.\n */\nconst MAX_ERROR_DETAIL_LENGTH = 500;\n\n/**\n * Walks an `Error.cause` chain and returns a deduplicated, truncated list\n * of each link's `message`. Used to surface the underlying cause of a\n * Xberg extraction failure (e.g. \"GLIBC_2.38 not found\") rather than\n * just the wrapper's generic name.\n */\nfunction collectErrorReasons(error: unknown): string[] {\n const messages: string[] = [];\n const seen = new Set<unknown>();\n let current: unknown = error;\n let depth = 0;\n while (current && !seen.has(current) && depth < 10) {\n seen.add(current);\n if (current instanceof Error && current.message) {\n const trimmed = current.message\n .replace(/\\s+/g, \" \")\n .trim()\n .slice(0, MAX_ERROR_DETAIL_LENGTH);\n if (trimmed && !messages.includes(trimmed)) {\n messages.push(trimmed);\n }\n }\n current = (current as { cause?: unknown }).cause;\n depth++;\n }\n return messages;\n}\n","import * as cheerio from \"cheerio\";\nimport { logger } from \"../../utils/logger\";\nimport type { ContentProcessorMiddleware, MiddlewareContext } from \"./types\";\n\n/**\n * Middleware to parse HTML string/buffer content into a Cheerio object.\n * It populates the `context.dom` property.\n * Assumes the input HTML in `context.content` is the final version to be parsed\n * (e.g., after potential rendering by Playwright or modification by JS execution).\n */\nexport class HtmlCheerioParserMiddleware implements ContentProcessorMiddleware {\n async process(context: MiddlewareContext, next: () => Promise<void>): Promise<void> {\n try {\n logger.debug(`Parsing HTML content with Cheerio from ${context.source}`);\n // Load the HTML string using Cheerio\n const $ = cheerio.load(context.content);\n\n // Add the Cheerio API object to the context\n context.dom = $;\n\n // Proceed to the next middleware\n await next();\n } catch (error) {\n logger.error(\n `❌ Failed to parse HTML with Cheerio for ${context.source}: ${error}`,\n );\n context.errors.push(\n error instanceof Error\n ? error\n : new Error(`Cheerio HTML parsing failed: ${String(error)}`),\n );\n // Do not proceed further down the pipeline if parsing fails\n return;\n }\n }\n}\n","import { logger } from \"../../utils/logger\";\nimport type { ContentProcessorMiddleware, MiddlewareContext } from \"./types\";\n\n/**\n * Middleware to extract links (href attributes from <a> tags) from HTML content using Cheerio.\n * It expects the Cheerio API object to be available in `context.dom`.\n * This should run *after* parsing but *before* conversion to Markdown.\n */\nexport class HtmlLinkExtractorMiddleware implements ContentProcessorMiddleware {\n /**\n * Processes the context to extract links from the sanitized HTML body.\n * @param context The current middleware context.\n * @param next Function to call the next middleware.\n */\n async process(context: MiddlewareContext, next: () => Promise<void>): Promise<void> {\n // Check if we have a Cheerio object from a previous step\n const $ = context.dom;\n if (!$) {\n logger.warn(\n `⏭️ Skipping ${this.constructor.name}: context.dom is missing. Ensure HtmlCheerioParserMiddleware runs before this.`,\n );\n await next();\n return;\n }\n\n try {\n // Determine effective document base (first <base href> if present)\n let docBase = context.source;\n try {\n const baseEl = $(\"base[href]\").first();\n const rawBase = baseEl.attr(\"href\");\n if (rawBase && rawBase.trim() !== \"\") {\n try {\n const trimmed = rawBase.trim();\n // Attempt to resolve candidate base against the document source.\n const candidate = new URL(trimmed, context.source);\n // Heuristic validation:\n // Accept if:\n // - Starts with a valid scheme (e.g. https:, data:, etc.) OR\n // - Protocol-relative (//...) OR\n // - Root-relative (/...) OR\n // - Dot-relative (./ or ../...) OR\n // - Otherwise a plain relative path segment WITHOUT a suspicious leading colon\n //\n // Reject (fallback to original page URL) if the first character is a colon or\n // there is a colon before any slash that does NOT form a valid scheme.\n const hasScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed);\n const protocolRelative = trimmed.startsWith(\"//\");\n const firstSlash = trimmed.indexOf(\"/\");\n const firstColon = trimmed.indexOf(\":\");\n const colonBeforeSlash =\n firstColon !== -1 && (firstSlash === -1 || firstColon < firstSlash);\n const suspiciousColon = colonBeforeSlash && !hasScheme && !protocolRelative;\n if (suspiciousColon || trimmed.startsWith(\":\")) {\n logger.debug(\n `Ignoring suspicious <base href> value (colon misuse): ${rawBase}`,\n );\n } else {\n // Accept candidate (valid scheme, protocol/root/dot relative, or plain relative segment)\n docBase = candidate.href;\n }\n } catch {\n logger.debug(`Ignoring invalid <base href> value: ${rawBase}`);\n }\n }\n } catch {\n // Ignore base parsing errors\n }\n\n const linkElements = $(\"a[href]\");\n logger.debug(\n `Found ${linkElements.length} potential links in ${context.source} (base=${docBase})`,\n );\n\n const extractedLinks: string[] = [];\n linkElements.each((_index, element) => {\n const href = $(element).attr(\"href\");\n if (href && href.trim() !== \"\") {\n try {\n const urlObj = new URL(href, docBase);\n if (![\"http:\", \"https:\", \"file:\"].includes(urlObj.protocol)) {\n logger.debug(`Ignoring link with invalid protocol: ${href}`);\n return;\n }\n extractedLinks.push(urlObj.href);\n } catch (_e) {\n logger.debug(`Ignoring invalid URL syntax: ${href}`);\n }\n }\n });\n\n context.links = [...new Set(extractedLinks)];\n logger.debug(\n `Extracted ${context.links.length} unique, valid links from ${context.source}`,\n );\n } catch (error) {\n logger.error(`❌ Error extracting links from ${context.source}: ${error}`);\n context.errors.push(\n new Error(\n `Failed to extract links from HTML: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n }\n\n await next();\n }\n}\n","import { logger } from \"../../utils/logger\";\nimport type { ContentProcessorMiddleware, MiddlewareContext } from \"./types\";\n\n/**\n * Middleware to extract the title from HTML content using Cheerio.\n * Assumes context.dom (Cheerio API object) is populated by a preceding middleware\n * (e.g., HtmlCheerioParserMiddleware).\n */\nexport class HtmlMetadataExtractorMiddleware implements ContentProcessorMiddleware {\n /**\n * Processes the context to extract the HTML title.\n * @param context The current processing context.\n * @param next Function to call the next middleware.\n */\n async process(context: MiddlewareContext, next: () => Promise<void>): Promise<void> {\n // Check if Cheerio DOM exists from previous middleware\n const $ = context.dom;\n if (!$) {\n logger.warn(\n `⏭️ Skipping ${this.constructor.name}: context.dom is missing. Ensure HtmlCheerioParserMiddleware runs before this.`,\n );\n await next();\n return;\n }\n\n // Only process if we have a Cheerio object (implicitly means it's HTML)\n try {\n // Extract title (using title tag, fallback to h1 if title is empty/missing)\n let title = $(\"title\").first().text().trim();\n\n if (!title) {\n // Fallback to the first H1 if title is empty\n title = $(\"h1\").first().text().trim();\n }\n\n // Default to \"Untitled\" if both are empty\n title = title || \"Untitled\";\n\n // Basic cleanup (replace multiple spaces with single space)\n title = title.replace(/\\s+/g, \" \").trim();\n\n context.title = title;\n logger.debug(`Extracted title: \"${title}\" from ${context.source}`);\n } catch (error) {\n logger.error(`❌ Error extracting metadata from ${context.source}: ${error}`);\n context.errors.push(\n new Error(\n `Failed to extract metadata from HTML: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n // Optionally decide whether to stop the pipeline here\n }\n\n // Call the next middleware in the chain\n await next();\n\n // No cleanup needed for Cheerio\n }\n}\n","import type * as cheerio from \"cheerio\";\nimport type { AnyNode } from \"domhandler\";\nimport { logger } from \"../../utils/logger\";\nimport type { ContentProcessorMiddleware, MiddlewareContext } from \"./types\";\n\n/**\n * Middleware that normalizes URLs and links in HTML content after DOM parsing.\n *\n * This middleware performs the following transformations:\n * - Converts relative image URLs to absolute URLs\n * - Removes tracking/ad images (1x1 pixels, analytics beacons)\n * - Converts relative link URLs to absolute URLs\n * - Removes anchor links (#...) but preserves their text content\n * - Removes non-HTTP links (javascript:, mailto:, etc.) but preserves their text content\n *\n * This ensures that indexed documents contain functional absolute URLs and removes\n * non-functional links while preserving contextually valuable text content.\n */\nexport class HtmlNormalizationMiddleware implements ContentProcessorMiddleware {\n private readonly presentationalAnchorWrapperTags = new Set([\"div\", \"p\"]);\n\n // Known tracking/analytics domains and patterns to filter out\n private readonly trackingPatterns = [\n \"adroll.com\",\n \"doubleclick.net\",\n \"google-analytics.com\",\n \"googletagmanager.com\",\n \"analytics.twitter.com\",\n \"twitter.com/1/i/adsct\",\n \"t.co/1/i/adsct\",\n \"bat.bing.com\",\n \"pixel.rubiconproject.com\",\n \"casalemedia.com\",\n \"tremorhub.com\",\n \"rlcdn.com\",\n \"facebook.com/tr\",\n \"linkedin.com/px\",\n \"quantserve.com\",\n \"scorecardresearch.com\",\n \"hotjar.com\",\n \"mouseflow.com\",\n \"crazyegg.com\",\n \"clarity.ms\",\n ];\n async process(context: MiddlewareContext, next: () => Promise<void>): Promise<void> {\n if (!context.dom) {\n logger.debug(\n `Skipping HTML normalization for ${context.source} - no DOM available`,\n );\n await next();\n return;\n }\n\n try {\n logger.debug(`Normalizing HTML URLs and links for ${context.source}`);\n\n const $ = context.dom;\n const baseUrl = context.source;\n\n // Normalize image URLs\n this.normalizeImageUrls($, baseUrl);\n\n // Normalize and clean links\n this.normalizeLinks($, baseUrl);\n\n // Simplify purely presentational wrappers inside links before markdown conversion\n this.simplifyAnchorContent($);\n\n logger.debug(`Successfully normalized HTML content for ${context.source}`);\n } catch (error) {\n logger.error(`❌ Failed to normalize HTML for ${context.source}: ${error}`);\n context.errors.push(\n error instanceof Error\n ? error\n : new Error(`HTML normalization failed: ${String(error)}`),\n );\n }\n\n await next();\n }\n\n /**\n * Checks if an image should be kept based on its source URL.\n * Filters out tracking pixels and analytics beacons.\n */\n private shouldKeepImage(src: string): boolean {\n const srcLower = src.toLowerCase();\n return !this.trackingPatterns.some((pattern) => srcLower.includes(pattern));\n }\n\n /**\n * Normalizes image URLs by converting relative URLs to absolute URLs.\n * Removes tracking/analytics images.\n * Preserves data URIs (inline images).\n */\n private normalizeImageUrls($: cheerio.CheerioAPI, baseUrl: string): void {\n $(\"img\").each((_index, element) => {\n const $img = $(element);\n const src = $img.attr(\"src\");\n\n if (!src) {\n // Remove images without src\n $img.remove();\n return;\n }\n\n // Keep data URIs (inline images) as-is\n if (src.startsWith(\"data:\")) {\n return;\n }\n\n // Check if this is a tracking image\n if (!this.shouldKeepImage(src)) {\n $img.remove();\n return;\n }\n\n try {\n // If it's already an absolute URL, leave it unchanged\n new URL(src);\n } catch {\n // It's a relative URL, convert to absolute\n try {\n const absoluteUrl = new URL(src, baseUrl).href;\n $img.attr(\"src\", absoluteUrl);\n } catch (error) {\n logger.debug(`Failed to resolve relative image URL: ${src} - ${error}`);\n // Remove images we can't resolve\n $img.remove();\n }\n }\n });\n }\n\n /**\n * Normalizes links by:\n * - Converting relative URLs to absolute URLs\n * - Unwrapping anchor links (preserving text content)\n * - Unwrapping non-HTTP links (preserving text content)\n */\n private normalizeLinks($: cheerio.CheerioAPI, baseUrl: string): void {\n $(\"a\").each((_index, element) => {\n const $link = $(element);\n const href = $link.attr(\"href\");\n\n if (!href) {\n // Links without href - unwrap them (preserve content, remove tag)\n this.unwrapElement($, $link);\n return;\n }\n\n // Handle anchor links (starting with #)\n if (href.startsWith(\"#\")) {\n this.unwrapElement($, $link);\n return;\n }\n\n // Check if it's already an absolute URL\n try {\n const url = new URL(href);\n\n // Handle non-HTTP protocols (javascript:, mailto:, etc.)\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n this.unwrapElement($, $link);\n return;\n }\n\n // It's already a valid HTTP/HTTPS absolute URL, leave it unchanged\n } catch {\n // It's a relative URL, convert to absolute\n try {\n const absoluteUrl = new URL(href, baseUrl).href;\n $link.attr(\"href\", absoluteUrl);\n } catch (error) {\n logger.debug(`Failed to resolve relative link URL: ${href} - ${error}`);\n // If we can't resolve it, unwrap it to preserve the text content\n this.unwrapElement($, $link);\n }\n }\n });\n }\n\n /**\n * Removes single presentational block wrappers inside anchors so Turndown does not\n * emit multi-line link labels for layout-only structures.\n */\n private simplifyAnchorContent($: cheerio.CheerioAPI): void {\n $(\"a\").each((_index, element) => {\n const $link = $(element);\n let simplified = true;\n\n while (simplified) {\n simplified = false;\n\n const significantChildren = $link\n .contents()\n .toArray()\n .filter((node) => node.type !== \"text\" || (node.data || \"\").trim().length > 0);\n\n if (significantChildren.length !== 1) {\n continue;\n }\n\n const wrapperNode = significantChildren[0];\n if (wrapperNode.type !== \"tag\") {\n continue;\n }\n\n const tagName = wrapperNode.tagName.toLowerCase();\n if (!this.presentationalAnchorWrapperTags.has(tagName)) {\n continue;\n }\n\n const $wrapper = $(wrapperNode);\n if (this.hasProtectedDescendants($wrapper)) {\n continue;\n }\n\n this.insertSpacesBetweenSiblingTextFragments($, $wrapper);\n $wrapper.replaceWith($wrapper.contents());\n simplified = true;\n }\n });\n }\n\n private hasProtectedDescendants($element: cheerio.Cheerio<AnyNode>): boolean {\n return $element.find(\"img, pre, table, ul, ol, li, blockquote\").length > 0;\n }\n\n private insertSpacesBetweenSiblingTextFragments(\n $: cheerio.CheerioAPI,\n $element: cheerio.Cheerio<AnyNode>,\n ): void {\n const children = $element.contents().toArray();\n\n for (let index = 1; index < children.length; index++) {\n const previousNode = children[index - 1];\n const currentNode = children[index];\n\n if (\n !this.nodeHasVisibleText($, previousNode) ||\n !this.nodeHasVisibleText($, currentNode)\n ) {\n continue;\n }\n\n if (this.hasWhitespaceBoundary($, previousNode, currentNode)) {\n continue;\n }\n\n $(currentNode).before(\" \");\n }\n }\n\n private nodeHasVisibleText($: cheerio.CheerioAPI, node: AnyNode): boolean {\n if (node.type === \"text\") {\n return (node.data || \"\").trim().length > 0;\n }\n\n return $(node).text().trim().length > 0;\n }\n\n private hasWhitespaceBoundary(\n $: cheerio.CheerioAPI,\n previousNode: AnyNode,\n currentNode: AnyNode,\n ): boolean {\n const previousText = this.getNodeText($, previousNode);\n const currentText = this.getNodeText($, currentNode);\n\n return /\\s$/.test(previousText) || /^\\s/.test(currentText);\n }\n\n private getNodeText($: cheerio.CheerioAPI, node: AnyNode): string {\n if (node.type === \"text\") {\n return node.data || \"\";\n }\n\n return $(node).text();\n }\n\n /**\n * Unwraps an element by replacing it with its HTML content.\n * This preserves the inner HTML (including nested elements) while removing the wrapping tag.\n */\n private unwrapElement(\n _$: cheerio.CheerioAPI,\n $element: cheerio.Cheerio<AnyNode>,\n ): void {\n const htmlContent = $element.html() || $element.text();\n $element.replaceWith(htmlContent);\n }\n}\n","/**\n * A simple in-memory LRU (Least Recently Used) cache.\n * When the cache reaches maxSize, the oldest (least recently used) entry is evicted.\n *\n * This implementation uses a Map to maintain insertion order, where:\n * - get() moves the accessed key to the end (marks as recently used)\n * - set() adds to the end (most recent)\n * - When full, the first key (oldest) is deleted\n */\nexport class SimpleMemoryCache<K, V> {\n private cache: Map<K, V>;\n private readonly maxSize: number;\n\n constructor(maxSize: number) {\n if (maxSize <= 0) {\n throw new Error(\"maxSize must be positive\");\n }\n this.cache = new Map();\n this.maxSize = maxSize;\n }\n\n /**\n * Retrieve a value from the cache.\n * Marks the key as recently used (moves to end of Map).\n */\n get(key: K): V | undefined {\n const value = this.cache.get(key);\n if (value !== undefined) {\n // Move to end (mark as recently used)\n this.cache.delete(key);\n this.cache.set(key, value);\n }\n return value;\n }\n\n /**\n * Store a value in the cache.\n * If cache is full, evicts the oldest entry first.\n */\n set(key: K, value: V): void {\n // If key exists, delete it first so we can re-add at end\n if (this.cache.has(key)) {\n this.cache.delete(key);\n } else if (this.cache.size >= this.maxSize) {\n // Cache is full and this is a new key - evict oldest (first key)\n const oldestKey = this.cache.keys().next().value;\n if (oldestKey !== undefined) {\n this.cache.delete(oldestKey);\n }\n }\n\n this.cache.set(key, value);\n }\n\n /**\n * Check if a key exists in the cache.\n * Marks the key as recently used (moves to end of Map) to maintain LRU semantics.\n */\n has(key: K): boolean {\n const exists = this.cache.has(key);\n if (exists) {\n // Move to end (mark as recently used) to maintain LRU semantics\n const value = this.cache.get(key);\n if (value !== undefined) {\n this.cache.delete(key);\n this.cache.set(key, value);\n }\n }\n return exists;\n }\n\n /**\n * Get current cache size.\n */\n get size(): number {\n return this.cache.size;\n }\n\n /**\n * Clear all entries from the cache.\n */\n clear(): void {\n this.cache.clear();\n }\n}\n","/**\n * Built-in blocklist of third-party sub-resource origins that pages commonly\n * load during rendering but that never carry documentation content.\n *\n * Consulted from `HtmlPlaywrightMiddleware.setupCachingRouteInterception` to\n * abort matching requests before any bytes transfer. The list is intentionally\n * hand-curated and lives in code (not config) so that new entries ship to every\n * user on release — see `openspec/changes/add-subresource-blocklist/design.md`\n * for the rationale.\n *\n * Categories included: Analytics, Session Replay, Chat Widgets, Captcha, and\n * Social Embed runtimes. Two categories are deliberately excluded:\n *\n * - **Advertising networks** (e.g. doubleclick.net, googlesyndication.com) —\n * blocking these can trigger anti-adblock detection on monetized sites.\n * - **Generic CDNs** (e.g. unpkg.com, cdn.jsdelivr.net) — pages legitimately\n * fetch content-bearing libraries (Mermaid, KaTeX, MathJax) from them.\n */\n\nexport type BlocklistCategory =\n | \"Analytics\"\n | \"Session Replay\"\n | \"Chat Widget\"\n | \"Captcha\"\n | \"Social Embed\";\n\ninterface HostEntry {\n host: string;\n category: BlocklistCategory;\n}\n\ninterface HostPathEntry {\n host: string;\n pathPrefix: string;\n category: BlocklistCategory;\n}\n\ntype BlocklistEntry = HostEntry | HostPathEntry;\n\nexport type BlocklistMatch =\n | { blocked: true; category: BlocklistCategory }\n | { blocked: false };\n\nconst BLOCKLIST_NOT_BLOCKED: BlocklistMatch = Object.freeze({ blocked: false });\n\nexport const SUBRESOURCE_BLOCKLIST: ReadonlyArray<BlocklistEntry> = Object.freeze([\n // Analytics — page-view and event tracking SDKs; no content.\n { host: \"google-analytics.com\", category: \"Analytics\" },\n { host: \"googletagmanager.com\", category: \"Analytics\" },\n { host: \"segment.io\", category: \"Analytics\" },\n { host: \"segment.com\", category: \"Analytics\" },\n { host: \"mixpanel.com\", category: \"Analytics\" },\n { host: \"amplitude.com\", category: \"Analytics\" },\n { host: \"plausible.io\", category: \"Analytics\" },\n { host: \"matomo.cloud\", category: \"Analytics\" },\n { host: \"stats.wp.com\", category: \"Analytics\" },\n\n // Session Replay — record user interactions; never content.\n { host: \"hotjar.com\", category: \"Session Replay\" },\n { host: \"fullstory.com\", category: \"Session Replay\" },\n { host: \"logrocket.com\", category: \"Session Replay\" },\n { host: \"lr-ingest.io\", category: \"Session Replay\" },\n { host: \"smartlook.com\", category: \"Session Replay\" },\n\n // Chat Widgets — UI overlays the sanitizer strips post-fetch anyway.\n { host: \"intercom.io\", category: \"Chat Widget\" },\n { host: \"intercomcdn.com\", category: \"Chat Widget\" },\n { host: \"widget.kapa.ai\", category: \"Chat Widget\" },\n { host: \"drift.com\", category: \"Chat Widget\" },\n { host: \"driftt.com\", category: \"Chat Widget\" },\n { host: \"crisp.chat\", category: \"Chat Widget\" },\n { host: \"tawk.to\", category: \"Chat Widget\" },\n { host: \"zdassets.com\", category: \"Chat Widget\" },\n\n // Captcha — challenge runtimes; documentation pages don't need them.\n { host: \"hcaptcha.com\", category: \"Captcha\" },\n { host: \"recaptcha.net\", category: \"Captcha\" },\n\n // Social Embed runtimes — the embed-document iframe is allowed (document type\n // is exempt at the route handler); only the runtime JS is blocked.\n {\n host: \"youtube-nocookie.com\",\n pathPrefix: \"/s/_/ytembeds/\",\n category: \"Social Embed\",\n },\n { host: \"platform.twitter.com\", category: \"Social Embed\" },\n { host: \"connect.facebook.net\", category: \"Social Embed\" },\n { host: \"platform.linkedin.com\", category: \"Social Embed\" },\n] satisfies ReadonlyArray<BlocklistEntry>);\n\n// Validate entries at module load — catches typos before any request fires.\nfor (const entry of SUBRESOURCE_BLOCKLIST) {\n if (!entry.host || entry.host.includes(\"/\") || entry.host.includes(\":\")) {\n throw new Error(\n `Invalid blocklist entry: host must be a bare hostname (got \"${entry.host}\")`,\n );\n }\n if (\"pathPrefix\" in entry && !entry.pathPrefix.startsWith(\"/\")) {\n throw new Error(\n `Invalid blocklist entry for \"${entry.host}\": pathPrefix must start with \"/\" (got \"${entry.pathPrefix}\")`,\n );\n }\n}\n\nfunction hostMatches(requestHost: string, entryHost: string): boolean {\n if (requestHost === entryHost) return true;\n return requestHost.endsWith(`.${entryHost}`);\n}\n\n/**\n * Checks whether a URL is on the built-in blocklist.\n *\n * Matching rules:\n * - Hostname matches when it equals an entry's host or ends with `.<entry-host>`\n * (label boundary), so `evil-google-analytics.com` does not match\n * `google-analytics.com`.\n * - When an entry has a `pathPrefix`, the URL's pathname must also start with\n * that prefix.\n * - Invalid URLs return `{ blocked: false }` rather than throwing.\n */\nexport function isBlockedSubresource(url: string): BlocklistMatch {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return BLOCKLIST_NOT_BLOCKED;\n }\n\n const host = parsed.hostname;\n for (const entry of SUBRESOURCE_BLOCKLIST) {\n if (!hostMatches(host, entry.host)) continue;\n if (\"pathPrefix\" in entry && !parsed.pathname.startsWith(entry.pathPrefix)) {\n continue;\n }\n return { blocked: true, category: entry.category };\n }\n return BLOCKLIST_NOT_BLOCKED;\n}\n","import type {\n APIResponse,\n Browser,\n BrowserContext,\n ElementHandle,\n Frame,\n Page,\n Route,\n} from \"playwright\";\nimport { ScraperAccessPolicy } from \"../../utils/accessPolicy\";\nimport { type AppConfig, defaults } from \"../../utils/config\";\nimport { firstErrorLine, RenderError } from \"../../utils/errors\";\nimport { logger } from \"../../utils/logger\";\nimport { MimeTypeUtils } from \"../../utils/mimeTypeUtils\";\nimport { withTimeout } from \"../../utils/timeout\";\nimport { ManagedBrowser } from \"../fetcher\";\nimport { DEFAULT_BROWSER_USER_AGENT, getHeader } from \"../fetcher/headers\";\nimport { ScrapeMode } from \"../types\";\nimport { SimpleMemoryCache } from \"../utils/SimpleMemoryCache\";\nimport { isBlockedSubresource } from \"./subresourceBlocklist\";\nimport type { ContentProcessorMiddleware, MiddlewareContext } from \"./types\";\n\n/**\n * Shadow DOM mapping structure for non-invasive extraction\n */\ninterface ShadowMapping {\n shadowContent: string;\n hostTagName: string;\n hostClasses: string;\n hostId: string;\n hostOuterHTML: string;\n elementIndex: number;\n parentTagName: string;\n positionTop: number;\n positionLeft: number;\n}\n\n/**\n * Cached resource structure containing body and content type\n */\ninterface CachedResource {\n body: string;\n contentType: string;\n}\n\n/**\n * Most redirects a sub-resource fetch follows. Matches Playwright's own default\n * (20): the renderer follows redirects itself only to check every hop against\n * the access policy, not to change the allowed depth.\n */\nconst MAX_SUBRESOURCE_REDIRECTS = 20;\n\n/** The Playwright objects a render opens, held where the caller can close them. */\ninterface RenderHandles {\n page: Page | null;\n browserContext: BrowserContext | null;\n}\n\n/**\n * Middleware to process HTML content using Playwright for rendering dynamic content,\n * *if* the scrapeMode option requires it ('playwright' or 'auto').\n * It updates `context.content` with the rendered HTML if Playwright runs.\n * Subsequent middleware (e.g., HtmlCheerioParserMiddleware) should handle parsing this content.\n *\n * This middleware also supports URLs with embedded credentials (user:password@host) and ensures\n * credentials are used for all same-origin resource requests (not just the main page) via HTTP Basic Auth.\n *\n * Additionally, all custom headers from context.options?.headers are forwarded to Playwright requests.\n */\nexport class HtmlPlaywrightMiddleware implements ContentProcessorMiddleware {\n private readonly managedBrowser: ManagedBrowser;\n private readonly config: AppConfig[\"scraper\"];\n private readonly accessPolicy: ScraperAccessPolicy;\n\n // Static LRU cache for all fetched resources, shared across instances\n private static readonly resourceCache = new SimpleMemoryCache<string, CachedResource>(\n defaults.scraper.fetcher.maxCacheItems,\n );\n\n /**\n * @param config - Scraper settings (timeouts, network policy).\n * @param managedBrowser - The browser to render with; pass one to share it\n * with the browser fetcher.\n */\n constructor(config: AppConfig[\"scraper\"], managedBrowser = new ManagedBrowser(config)) {\n this.config = config;\n this.managedBrowser = managedBrowser;\n this.accessPolicy = new ScraperAccessPolicy(config.security);\n }\n\n private async isRequestAllowed(url: string): Promise<boolean> {\n try {\n await this.accessPolicy.assertNetworkUrlAllowed(url);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Returns true if the request was handled (aborted) by the built-in tracker\n * blocklist; the caller should bail out of further processing in that case.\n * Returns false when the blocklist is disabled, when the request is a\n * top-level/iframe document navigation, or when no entry matches.\n */\n private async tryBlocklistAbort(route: Route, reqUrl: string): Promise<boolean> {\n if (!this.config.skipKnownTrackers) return false;\n if (route.request().resourceType() === \"document\") return false;\n const match = isBlockedSubresource(reqUrl);\n if (!match.blocked) return false;\n\n logger.debug(`Blocked sub-resource (${match.category}): ${reqUrl}`);\n try {\n await route.abort(\"blockedbyclient\");\n } catch (error) {\n if (this.isRouteAlreadyHandledError(error)) {\n logger.debug(`Route already handled (blocklist abort): ${reqUrl}`);\n return true;\n }\n throw error;\n }\n return true;\n }\n\n private getPageTimeoutMs(): number {\n return this.config.pageTimeoutMs ?? defaults.scraper.pageTimeoutMs;\n }\n\n private getBrowserTimeoutMs(): number {\n return this.config.browserTimeoutMs ?? defaults.scraper.browserTimeoutMs;\n }\n\n /**\n * Upper bound for one page render. Navigation has its own timeout; the waits\n * and extraction after it share six page timeouts of headroom. Several of those\n * Playwright calls take no timeout at all, and a wedged Chromium leaves them\n * pending, so the whole render runs under this bound.\n */\n private getRenderTimeoutMs(): number {\n return this.getBrowserTimeoutMs() + 6 * this.getPageTimeoutMs();\n }\n\n /**\n * Closes the browser this middleware renders with.\n * Should be called during application shutdown.\n */\n async closeBrowser(): Promise<void> {\n await this.managedBrowser.close();\n }\n\n /**\n * Removes the page's routes and closes the page and its context, each within\n * the page timeout.\n *\n * @returns Whether the page and context closed. A route that fails to clear\n * is only logged: it says nothing about whether Chromium still responds.\n */\n private async cleanupPageAndContext(\n page: Page | null,\n browserContext: BrowserContext | null,\n source: string,\n ): Promise<boolean> {\n let closed = true;\n const timeoutMs = this.getPageTimeoutMs();\n\n if (page) {\n try {\n await withTimeout(\n page.unroute(\"**/*\"),\n timeoutMs,\n `Playwright route cleanup for ${source}`,\n );\n } catch (error) {\n logger.warn(`⚠️ Playwright route cleanup failed for ${source}: ${error}`);\n }\n\n try {\n await withTimeout(page.close(), timeoutMs, `Playwright page close for ${source}`);\n } catch (error) {\n closed = false;\n logger.warn(`⚠️ Playwright page cleanup failed for ${source}: ${error}`);\n }\n }\n\n if (browserContext) {\n try {\n await withTimeout(\n browserContext.close(),\n timeoutMs,\n `Playwright browser context close for ${source}`,\n );\n } catch (error) {\n closed = false;\n logger.warn(`⚠️ Playwright context cleanup failed for ${source}: ${error}`);\n }\n }\n\n return closed;\n }\n\n /**\n * Injects the shadow DOM extractor script into the page.\n * This script performs non-invasive extraction that preserves document structure.\n * The extraction function is called just-in-time when content is actually needed, ensuring we capture\n * the final state of all shadow DOMs after page loading is complete.\n * Returns an array of shadow mappings directly (empty array = no shadow DOMs found).\n */\n private async injectShadowDOMExtractor(page: Page): Promise<void> {\n await page.addInitScript(`\n window.shadowExtractor = {\n extract() {\n // Extract shadow DOM mappings\n const shadowMappings = [];\n \n function createShadowMapping(root, depth = 0) {\n if (depth > 15) return;\n \n // Use TreeWalker to traverse in document order\n const walker = document.createTreeWalker(\n root,\n NodeFilter.SHOW_ELEMENT,\n null,\n false\n );\n \n let currentNode = walker.nextNode();\n while (currentNode) {\n const element = currentNode;\n if (element.shadowRoot) {\n try {\n // Extract shadow DOM content without modifying anything\n const shadowChildren = Array.from(element.shadowRoot.children);\n const shadowHTML = shadowChildren.map(child => child.outerHTML).join('\\\\n');\n \n if (shadowHTML.trim()) {\n // Get position info for precise insertion later\n const rect = element.getBoundingClientRect();\n const elementIndex = Array.from(element.parentNode?.children || []).indexOf(element);\n \n shadowMappings.push({\n shadowContent: shadowHTML,\n hostTagName: element.tagName,\n hostClasses: element.className || '',\n hostId: element.id || '',\n hostOuterHTML: element.outerHTML,\n elementIndex: elementIndex,\n parentTagName: element.parentNode?.tagName || '',\n positionTop: rect.top,\n positionLeft: rect.left\n });\n }\n \n // Recursively process nested shadow DOMs\n createShadowMapping(element.shadowRoot, depth + 1);\n \n } catch (error) {\n console.debug('Shadow DOM access error:', error);\n }\n }\n currentNode = walker.nextNode();\n }\n }\n \n createShadowMapping(document);\n \n return shadowMappings;\n }\n };\n \n `);\n }\n\n /**\n * Extracts content using either shadow DOM non-invasive extraction or standard page.content() method.\n * Returns the extracted content and the method used.\n *\n * Performs just-in-time shadow DOM extraction after all page loading is complete.\n */\n private async extractContentWithShadowDOMSupport(page: Page): Promise<{\n content: string;\n method: string;\n }> {\n // Force fresh extraction right now (when everything is loaded)\n const [shadowMappings, originalPageContent] = await Promise.all([\n page.evaluate(() => {\n // Extract fresh data right now - just-in-time extraction\n // biome-ignore lint/suspicious/noExplicitAny: no type for injected script\n return (window as any).shadowExtractor?.extract() || [];\n }),\n page.content(),\n ]);\n\n if (shadowMappings.length === 0) {\n // No shadow DOMs - use standard page.content()\n logger.debug(\"No shadow DOMs detected - using page.content()\");\n return { content: originalPageContent, method: \"page.content()\" };\n } else {\n // Shadow DOMs found - combine content outside the browser (non-invasive)\n logger.debug(\n `Shadow DOMs detected - found ${shadowMappings.length} shadow host(s)`,\n );\n logger.debug(\"Combining content outside browser (non-invasive)\");\n\n // Combine original content with shadow content outside the browser\n const finalContent = this.combineContentSafely(originalPageContent, shadowMappings);\n return { content: finalContent, method: \"non-invasive shadow DOM extraction\" };\n }\n }\n\n /**\n * Waits for common loading indicators (spinners, loaders) that are currently visible to disappear from the page or frame.\n * Only waits for selectors that are present and visible at the time of check.\n *\n * @param pageOrFrame The Playwright page or frame instance to operate on.\n */\n private async waitForLoadingToComplete(\n pageOrFrame:\n | Page\n | { waitForSelector: Page[\"waitForSelector\"]; isVisible: Page[\"isVisible\"] },\n ): Promise<void> {\n const commonLoadingSelectors = [\n '[class*=\"loading\"]',\n '[class*=\"spinner\"]',\n '[class*=\"loader\"]',\n '[id*=\"loading\"]',\n '[class*=\"preload\"]',\n \"#loading\",\n '[aria-label*=\"loading\" i]',\n '[aria-label*=\"spinner\" i]',\n ];\n\n // Wait for all visible loading indicators in parallel\n const waitPromises: Promise<unknown>[] = [];\n for (const selector of commonLoadingSelectors) {\n try {\n // Use page.isVisible to check if any matching element is visible (legacy API, but works for any visible match)\n const isVisible = await pageOrFrame.isVisible(selector).catch(() => false);\n if (isVisible) {\n waitPromises.push(\n pageOrFrame\n .waitForSelector(selector, {\n state: \"hidden\",\n timeout: this.config.pageTimeoutMs,\n })\n .catch(() => {}),\n );\n }\n } catch {\n // Ignore errors (e.g., selector not found or timeout)\n }\n }\n if (waitPromises.length > 0) {\n await Promise.all(waitPromises);\n }\n }\n\n /**\n * Waits for all iframes on the page to load their content.\n * For each iframe, waits for the body to appear and loading indicators to disappear.\n *\n * @param page The Playwright page instance to operate on.\n */\n private async waitForIframesToLoad(page: Page): Promise<void> {\n try {\n // Get all iframe elements\n const iframes = await page.$$(\"iframe\");\n if (iframes.length === 0) {\n return;\n }\n\n logger.debug(`Found ${iframes.length} iframe(s) on ${page.url()}`);\n\n // Wait for all iframes to load in parallel\n const iframePromises = iframes.map((iframe, index) =>\n this.processIframe(iframe, index),\n );\n\n await Promise.all(iframePromises);\n logger.debug(`Finished waiting for all iframes to load`);\n } catch (error) {\n logger.debug(`Error during iframe loading for ${page.url()}: ${error}`);\n }\n }\n\n /**\n * Processes a single iframe: validates, extracts content, and replaces in main page.\n *\n * @param iframe The iframe element handle\n * @param index The iframe index for logging\n */\n private async processIframe(\n iframe: ElementHandle<HTMLIFrameElement>,\n index: number,\n ): Promise<void> {\n try {\n const src = await iframe.getAttribute(\"src\");\n if (this.shouldSkipIframeSrc(src)) {\n logger.debug(`Skipping iframe ${index + 1} - no valid src (${src})`);\n return;\n }\n\n logger.debug(`Waiting for iframe ${index + 1} to load: ${src}`);\n\n // Get the frame content\n const frame = await iframe.contentFrame();\n if (!frame) {\n logger.debug(`Could not access content frame for iframe ${index + 1}`);\n return;\n }\n\n // Wait for the iframe body to load - if this times out, skip the rest of processing\n try {\n await frame.waitForSelector(\"body\", {\n timeout: this.config.pageTimeoutMs,\n });\n } catch {\n logger.debug(\n `Timeout waiting for body in iframe ${index + 1} - skipping content extraction`,\n );\n return;\n }\n\n // Wait for loading indicators in the iframe to complete (with timeout protection)\n try {\n await this.waitForLoadingToComplete(frame);\n } catch {\n logger.debug(\n `Timeout waiting for loading indicators in iframe ${index + 1} - proceeding anyway`,\n );\n }\n\n // Extract and replace iframe content (with timeout protection)\n let content: string | null = null;\n try {\n content = await this.extractIframeContent(frame);\n } catch (error) {\n logger.debug(`Error extracting content from iframe ${index + 1}: ${error}`);\n return;\n }\n\n if (content && content.trim().length > 0) {\n await this.replaceIframeWithContent(iframe, content);\n logger.debug(\n `Successfully extracted and replaced content for iframe ${index + 1}: ${src}`,\n );\n } else {\n logger.debug(`Iframe ${index + 1} body content is empty: ${src}`);\n }\n\n logger.debug(`Successfully loaded iframe ${index + 1}: ${src}`);\n } catch (error) {\n logger.debug(`Error processing iframe ${index + 1}: ${error}`);\n }\n }\n\n /**\n * Determines if an iframe src should be skipped during processing.\n *\n * @param src The iframe src attribute value\n * @returns true if the iframe should be skipped\n */\n private shouldSkipIframeSrc(src: string | null): boolean {\n return (\n !src ||\n src.startsWith(\"data:\") ||\n src.startsWith(\"javascript:\") ||\n src === \"about:blank\"\n );\n }\n\n /**\n * Extracts the body innerHTML from an iframe.\n *\n * @param frame The iframe's content frame\n * @returns The extracted HTML content or null if extraction fails\n */\n private async extractIframeContent(frame: Frame): Promise<string | null> {\n try {\n return await frame.$eval(\"body\", (el: HTMLElement) => el.innerHTML);\n } catch (error) {\n logger.debug(`Error extracting iframe content: ${error}`);\n return null;\n }\n }\n\n /**\n * Replaces an iframe element with its extracted content in the main page.\n *\n * Acts on the iframe's own handle: iframes are processed in parallel, and\n * each replacement shifts the position of the iframes after it.\n *\n * @param iframe The iframe element handle\n * @param content The extracted content to replace the iframe with\n */\n private async replaceIframeWithContent(\n iframe: ElementHandle<HTMLIFrameElement>,\n content: string,\n ): Promise<void> {\n await iframe.evaluate((element, bodyContent) => {\n const replacement = document.createElement(\"div\");\n replacement.innerHTML = bodyContent;\n element.replaceWith(replacement);\n }, content);\n }\n\n /**\n * Waits for and processes framesets on the page by extracting content from each frame\n * and replacing the frameset with merged content.\n *\n * @param page The Playwright page instance to operate on.\n */\n private async waitForFramesetsToLoad(page: Page): Promise<void> {\n try {\n // Check if the page contains framesets\n const framesets = await page.$$(\"frameset\");\n if (framesets.length === 0) {\n return;\n }\n\n logger.debug(`Found ${framesets.length} frameset(s) on ${page.url()}`);\n\n // Extract all frame URLs from the frameset structure\n const frameUrls = await this.extractFrameUrls(page);\n if (frameUrls.length === 0) {\n logger.debug(\"No frame URLs found in framesets\");\n return;\n }\n\n logger.debug(`Found ${frameUrls.length} frame(s) to process`);\n\n // Fetch content from each frame\n const frameContents: Array<{ url: string; content: string; name?: string }> = [];\n for (const frameInfo of frameUrls) {\n try {\n const content = await this.fetchFrameContent(page, frameInfo.src);\n if (content && content.trim().length > 0) {\n frameContents.push({\n url: frameInfo.src,\n content,\n name: frameInfo.name,\n });\n logger.debug(`Successfully fetched content from frame: ${frameInfo.src}`);\n } else {\n logger.debug(`Frame content is empty: ${frameInfo.src}`);\n }\n } catch (error) {\n logger.debug(`Error fetching frame content from ${frameInfo.src}: ${error}`);\n }\n }\n\n // Merge frame contents and replace frameset\n if (frameContents.length > 0) {\n await this.mergeFrameContents(page, frameContents);\n logger.debug(\n `Successfully merged ${frameContents.length} frame(s) into main page`,\n );\n }\n\n logger.debug(`Finished processing framesets`);\n } catch (error) {\n logger.debug(`Error during frameset processing for ${page.url()}: ${error}`);\n }\n }\n\n /**\n * Extracts frame URLs from all framesets on the page in document order.\n *\n * @param page The Playwright page instance to operate on.\n * @returns Array of frame information objects with src and optional name.\n */\n private async extractFrameUrls(\n page: Page,\n ): Promise<Array<{ src: string; name?: string }>> {\n try {\n return await page.evaluate(() => {\n const frames: Array<{ src: string; name?: string }> = [];\n const frameElements = document.querySelectorAll(\"frame\");\n\n for (const frame of frameElements) {\n const src = frame.getAttribute(\"src\");\n if (src?.trim() && !src.startsWith(\"javascript:\") && src !== \"about:blank\") {\n const name = frame.getAttribute(\"name\") || undefined;\n frames.push({ src: src.trim(), name });\n }\n }\n\n return frames;\n });\n } catch (error) {\n logger.debug(`Error extracting frame URLs: ${error}`);\n return [];\n }\n }\n\n /**\n * Sets up caching route interception for a Playwright page.\n * This handles:\n * - Aborting non-essential resources (images, fonts, media)\n * - Caching GET requests to speed up subsequent loads\n * - Forwarding custom headers and credentials for same-origin requests\n *\n * @param page The Playwright page to set up routing for\n * @param customHeaders Custom headers to forward with requests\n * @param credentials Optional credentials for same-origin requests\n * @param origin The origin for same-origin credential checking\n */\n /**\n * Checks if an error is a Playwright \"Route is already handled\" error.\n * This specific error occurs when multiple handlers attempt to handle the same route.\n */\n private isRouteAlreadyHandledError(error: unknown): boolean {\n if (error instanceof Error) {\n return error.message.includes(\"Route is already handled\");\n }\n return false;\n }\n\n private isTargetClosedError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n return error.message.includes(\"Target page, context or browser has been closed\");\n }\n\n private isSpeculativePrefetch(route: Route): boolean {\n const headers = route.request().headers();\n return (\n headers[\"next-router-prefetch\"] === \"1\" ||\n headers.purpose?.toLowerCase() === \"prefetch\" ||\n headers[\"sec-purpose\"]?.toLowerCase().includes(\"prefetch\") === true\n );\n }\n\n private isCacheableResponseContent(contentType: string): boolean {\n const { mimeType } = MimeTypeUtils.parseContentType(contentType);\n return (\n MimeTypeUtils.isHtml(mimeType) ||\n MimeTypeUtils.isMarkdown(mimeType) ||\n MimeTypeUtils.isSafeForTextProcessing(mimeType)\n );\n }\n\n private getRequestOrigin(url: string): string | null {\n try {\n return new URL(url).origin;\n } catch {\n return null;\n }\n }\n\n private ignoreRouteLifecycleError(\n error: unknown,\n action: string,\n reqUrl: string,\n ): boolean {\n if (this.isRouteAlreadyHandledError(error)) {\n logger.debug(`Route already handled (${action}): ${reqUrl}`);\n return true;\n }\n if (this.isTargetClosedError(error)) {\n logger.debug(`Route target closed (${action}): ${reqUrl}`);\n return true;\n }\n return false;\n }\n\n private async abortRoute(\n route: Route,\n reqUrl: string,\n action: string,\n reason?: Parameters<Route[\"abort\"]>[0],\n ): Promise<void> {\n try {\n await route.abort(reason);\n } catch (error) {\n if (this.ignoreRouteLifecycleError(error, action, reqUrl)) {\n return;\n }\n throw error;\n }\n }\n\n private async fulfillRoute(\n route: Route,\n reqUrl: string,\n options: Parameters<Route[\"fulfill\"]>[0],\n action: string,\n ): Promise<void> {\n try {\n await route.fulfill(options);\n } catch (error) {\n if (this.ignoreRouteLifecycleError(error, action, reqUrl)) {\n return;\n }\n throw error;\n }\n }\n\n private async continueRoute(\n route: Route,\n reqUrl: string,\n resourceType: string,\n options: Parameters<Route[\"continue\"]>[0],\n ): Promise<void> {\n try {\n await route.continue(options);\n } catch (error) {\n if (this.ignoreRouteLifecycleError(error, \"continue\", reqUrl)) {\n return;\n }\n\n const errorMessage = firstErrorLine(error);\n logger.debug(`Error continuing ${resourceType} ${reqUrl}: ${errorMessage}`);\n await this.abortRoute(route, reqUrl, \"abort after continue error\", \"failed\");\n }\n }\n\n private async cacheResponseIfEligible(\n reqUrl: string,\n resourceType: string,\n response: Awaited<ReturnType<Route[\"fetch\"]>>,\n ): Promise<void> {\n const contentType = response.headers()[\"content-type\"] || \"application/octet-stream\";\n\n if (response.status() < 200 || response.status() >= 300) {\n return;\n }\n\n if (!this.isCacheableResponseContent(contentType)) {\n logger.debug(\n `Skipping cache for unsupported content type \"${contentType}\" (${resourceType}): ${reqUrl}`,\n );\n return;\n }\n\n const body = await response.text();\n if (body.length === 0) {\n return;\n }\n\n const contentSizeBytes = Buffer.byteLength(body, \"utf8\");\n const maxCacheItemSizeBytes =\n this.config?.fetcher?.maxCacheItemSizeBytes ??\n defaults.scraper.fetcher.maxCacheItemSizeBytes;\n\n if (contentSizeBytes > maxCacheItemSizeBytes) {\n logger.debug(\n `Resource too large to cache: ${reqUrl} (${contentSizeBytes} bytes > ${maxCacheItemSizeBytes} bytes limit)`,\n );\n return;\n }\n\n HtmlPlaywrightMiddleware.resourceCache.set(reqUrl, { body, contentType });\n logger.debug(\n `Cached ${resourceType}: ${reqUrl} (${contentSizeBytes} bytes, cache size: ${HtmlPlaywrightMiddleware.resourceCache.size})`,\n );\n }\n\n private async handleSubresourceRoute(\n route: Route,\n customHeaders: Record<string, string>,\n credentials?: { username: string; password: string },\n origin?: string,\n ): Promise<void> {\n const reqUrl = route.request().url();\n const reqOrigin = this.getRequestOrigin(reqUrl);\n const resourceType = route.request().resourceType();\n\n if (!(await this.isRequestAllowed(reqUrl))) {\n await this.abortRoute(route, reqUrl, \"policy abort\", \"blockedbyclient\");\n return;\n }\n\n if (await this.tryBlocklistAbort(route, reqUrl)) {\n return;\n }\n\n if (this.isSpeculativePrefetch(route)) {\n logger.debug(`Aborting speculative prefetch ${resourceType}: ${reqUrl}`);\n await this.abortRoute(route, reqUrl, \"prefetch abort\", \"aborted\");\n return;\n }\n\n if ([\"image\", \"font\", \"media\"].includes(resourceType)) {\n await this.abortRoute(route, reqUrl, \"abort\");\n return;\n }\n\n const headers = mergePlaywrightHeaders(\n route.request().headers(),\n customHeaders,\n credentials,\n origin,\n reqOrigin ?? undefined,\n );\n\n if (route.request().method() !== \"GET\") {\n await this.continueRoute(route, reqUrl, resourceType, { headers });\n return;\n }\n\n const cached = HtmlPlaywrightMiddleware.resourceCache.get(reqUrl);\n if (cached !== undefined) {\n logger.debug(`✓ Cache hit for ${resourceType}: ${reqUrl}`);\n await this.fulfillRoute(\n route,\n reqUrl,\n { status: 200, contentType: cached.contentType, body: cached.body },\n \"fulfill cached\",\n );\n return;\n }\n\n try {\n const response = await this.fetchFollowingAllowedRedirects(route, headers);\n if (response === null) {\n await this.abortRoute(route, reqUrl, \"redirect policy abort\", \"blockedbyclient\");\n return;\n }\n // Cached under the URL the page asked for, which is what the next page\n // looks up; every hop to this response passed the access policy.\n await this.cacheResponseIfEligible(reqUrl, resourceType, response);\n await this.fulfillRoute(route, reqUrl, { response }, \"fulfill\");\n } catch (error) {\n if (this.ignoreRouteLifecycleError(error, `fetch ${resourceType}`, reqUrl)) {\n return;\n }\n\n const errorMessage = firstErrorLine(error);\n logger.debug(`Network error fetching ${resourceType} ${reqUrl}: ${errorMessage}`);\n await this.abortRoute(route, reqUrl, \"abort after error\", \"failed\");\n }\n }\n\n /**\n * Fetches a routed request in Node, following its redirects one hop at a time\n * so that the access policy checks each target before it is requested.\n *\n * `route.fetch` would follow the redirects unchecked, and Chromium follows a\n * redirect it is handed without Playwright routing the next request, so no\n * 3xx response may leave this method.\n *\n * @param route - The intercepted request.\n * @param headers - The headers to send with the first hop.\n * @returns The final response, or null when the policy denies a redirect target.\n */\n private async fetchFollowingAllowedRedirects(\n route: Route,\n headers: Record<string, string>,\n ): Promise<APIResponse | null> {\n let url = route.request().url();\n let hopHeaders = headers;\n\n for (let redirectCount = 0; ; redirectCount++) {\n const response = await route.fetch({ url, headers: hopHeaders, maxRedirects: 0 });\n const status = response.status();\n const location = response.headers().location;\n if (status < 300 || status >= 400 || !location) {\n return response;\n }\n await response.dispose();\n\n if (redirectCount >= MAX_SUBRESOURCE_REDIRECTS) {\n throw new Error(`Too many redirects while fetching ${route.request().url()}`);\n }\n\n const redirectUrl = new URL(location, url).href;\n if (!(await this.isRequestAllowed(redirectUrl))) {\n logger.debug(`Blocked redirect from ${url} to ${redirectUrl}`);\n return null;\n }\n // Playwright's rule when it follows redirects itself: credentials do not\n // follow a redirect to another origin.\n if (new URL(redirectUrl).origin !== new URL(url).origin) {\n hopHeaders = Object.fromEntries(\n Object.entries(hopHeaders).filter(\n ([name]) => name.toLowerCase() !== \"authorization\",\n ),\n );\n }\n url = redirectUrl;\n }\n }\n\n private async setupCachingRouteInterception(\n page: Page,\n customHeaders: Record<string, string> = {},\n credentials?: { username: string; password: string },\n origin?: string,\n ): Promise<void> {\n await page.route(\"**/*\", async (route) => {\n await this.handleSubresourceRoute(route, customHeaders, credentials, origin);\n });\n }\n\n /**\n * Fetches content from a frame URL by navigating to it in a new page.\n * Uses LRU cache to avoid re-fetching identical frames across multiple pages.\n *\n * @param parentPage The parent page (used to resolve relative URLs and share context)\n * @param frameUrl The URL of the frame to fetch content from\n * @returns The HTML content of the frame\n */\n private async fetchFrameContent(parentPage: Page, frameUrl: string): Promise<string> {\n // Resolve relative URLs against the parent page URL\n const resolvedUrl = new URL(frameUrl, parentPage.url()).href;\n // The route handler caches the frame's raw document under its URL; this\n // entry holds the body the frame rendered.\n const cacheKey = `frame:${resolvedUrl}`;\n\n // The cache is shared by every instance, so the policy is checked first.\n if (!(await this.isRequestAllowed(resolvedUrl))) {\n return \"\";\n }\n\n const cached = HtmlPlaywrightMiddleware.resourceCache.get(cacheKey);\n if (cached !== undefined) {\n logger.debug(`✓ Cache hit for frame: ${resolvedUrl}`);\n return cached.body;\n }\n\n logger.debug(`Cache miss for frame: ${resolvedUrl}`);\n\n let framePage: Page | null = null;\n try {\n // Create a new page in the same browser context for consistency\n framePage = await parentPage.context().newPage();\n\n // Set up the same caching route interception as the parent page\n await this.setupCachingRouteInterception(framePage);\n\n logger.debug(`Fetching frame content from: ${resolvedUrl}`);\n\n // Navigate to the frame URL\n await framePage.goto(resolvedUrl, {\n waitUntil: \"load\",\n timeout: this.config.pageTimeoutMs,\n });\n await framePage.waitForSelector(\"body\", {\n timeout: this.config.pageTimeoutMs,\n });\n\n // Wait for loading indicators to complete\n await this.waitForLoadingToComplete(framePage);\n\n // Extract the body content (not full HTML to avoid conflicts)\n const bodyContent = await framePage.$eval(\n \"body\",\n (el: HTMLElement) => el.innerHTML,\n );\n\n const content = bodyContent || \"\";\n\n // Only cache if content is small enough (avoid caching large content pages)\n const contentSizeBytes = Buffer.byteLength(content, \"utf8\");\n if (contentSizeBytes <= this.config.fetcher.maxCacheItemSizeBytes) {\n // Frame content is always HTML\n HtmlPlaywrightMiddleware.resourceCache.set(cacheKey, {\n body: content,\n contentType: \"text/html\",\n });\n logger.debug(\n `Cached frame content: ${resolvedUrl} (${contentSizeBytes} bytes, cache size: ${HtmlPlaywrightMiddleware.resourceCache.size})`,\n );\n } else {\n logger.debug(\n `Frame content too large to cache: ${resolvedUrl} (${contentSizeBytes} bytes > ${this.config.fetcher.maxCacheItemSizeBytes} bytes limit)`,\n );\n }\n\n logger.debug(`Successfully fetched frame content from: ${resolvedUrl}`);\n return content;\n } catch (error) {\n logger.debug(`Error fetching frame content from ${frameUrl}: ${error}`);\n return \"\";\n } finally {\n if (framePage) {\n await framePage.unroute(\"**/*\");\n await framePage.close();\n }\n }\n }\n\n /**\n * Merges frame contents and replaces the frameset structure with the merged content.\n *\n * @param page The main page containing the frameset\n * @param frameContents Array of frame content objects with URL, content, and optional name\n */\n private async mergeFrameContents(\n page: Page,\n frameContents: Array<{ url: string; content: string; name?: string }>,\n ): Promise<void> {\n try {\n // Build merged content sequentially, preserving frameset definition order\n const mergedContent = frameContents\n .map((frame, index) => {\n const frameName = frame.name ? ` (${frame.name})` : \"\";\n const frameHeader = `<!-- Frame ${index + 1}${frameName}: ${frame.url} -->`;\n return `${frameHeader}\\n<div data-frame-url=\"${frame.url}\" data-frame-name=\"${frame.name || \"\"}\">\\n${frame.content}\\n</div>`;\n })\n .join(\"\\n\\n\");\n\n // Replace the entire frameset structure with merged content\n await page.evaluate((mergedHtml: string) => {\n // Find all framesets and replace them with the merged content\n const framesets = document.querySelectorAll(\"frameset\");\n if (framesets.length > 0) {\n // Create a body element with the merged content\n const body = document.createElement(\"body\");\n body.innerHTML = mergedHtml;\n\n // Replace the first frameset with our body element\n // (typically there's only one root frameset)\n const firstFrameset = framesets[0];\n if (firstFrameset.parentNode) {\n firstFrameset.parentNode.replaceChild(body, firstFrameset);\n }\n\n // Remove any remaining framesets\n for (let i = 1; i < framesets.length; i++) {\n const frameset = framesets[i];\n if (frameset.parentNode) {\n frameset.parentNode.removeChild(frameset);\n }\n }\n }\n }, mergedContent);\n\n logger.debug(\"Successfully replaced frameset with merged content\");\n } catch (error) {\n logger.debug(`Error merging frame contents: ${error}`);\n }\n }\n\n /**\n * Processes the context using Playwright, rendering dynamic content and propagating credentials for all same-origin requests.\n *\n * - Parses credentials from the URL (if present).\n * - Uses browser.newContext({ httpCredentials }) for HTTP Basic Auth on the main page and subresources.\n * - Injects Authorization header for all same-origin requests if credentials are present and not already set.\n * - Forwards all custom headers from context.options?.headers to Playwright requests.\n * - Waits for common loading indicators to disappear before extracting HTML.\n * - When rendering fails, `auto` mode records the error and keeps the fetched HTML.\n *\n * @param context The middleware context containing the HTML and source URL.\n * @param next The next middleware function in the pipeline.\n * @throws {RenderError} When rendering fails in `playwright` mode.\n */\n async process(context: MiddlewareContext, next: () => Promise<void>): Promise<void> {\n // Check if we have a MIME type from the raw content and if it's suitable for HTML processing\n const contentType = context.options?.headers?.[\"content-type\"] || context.contentType;\n\n // Safety check: If we detect this is definitely not HTML content, skip Playwright\n if (\n contentType &&\n typeof contentType === \"string\" &&\n !MimeTypeUtils.isHtml(contentType)\n ) {\n logger.debug(\n `Skipping Playwright rendering for ${context.source} - content type '${contentType}' is not HTML`,\n );\n await next();\n return;\n }\n\n // Determine if Playwright should run based on scrapeMode\n const scrapeMode = context.options?.scrapeMode ?? ScrapeMode.Auto;\n const shouldRunPlaywright =\n scrapeMode === ScrapeMode.Playwright || scrapeMode === ScrapeMode.Auto;\n\n if (!shouldRunPlaywright) {\n // Handle gracefully although the middleware shouldn't even be in the pipeline\n logger.debug(\n `Skipping Playwright rendering for ${context.source} as scrapeMode is '${scrapeMode}'.`,\n );\n await next();\n return;\n }\n\n logger.debug(\n `Running Playwright rendering for ${context.source} (scrapeMode: '${scrapeMode}')`,\n );\n\n const handles: RenderHandles = { page: null, browserContext: null };\n let renderedHtml: string | null = null;\n let browser: Browser | null = null;\n\n try {\n // Outside the deadline: launching has its own timeout, and a browser that\n // finished launching after the deadline would have no owner to close it.\n browser = await this.managedBrowser.get();\n renderedHtml = await withTimeout(\n this.renderPage(browser, context, handles),\n this.getRenderTimeoutMs(),\n `Playwright render for ${context.source}`,\n );\n } catch (error) {\n logger.error(`❌ Playwright failed to render ${context.source}: ${error}`);\n const renderError =\n error instanceof Error\n ? error\n : new Error(`Playwright rendering failed: ${String(error)}`);\n // Only `auto` falls back to the page as fetched. `playwright` mode asked\n // for the rendered page, and indexing the fetched HTML in its place would\n // report success for content the browser never produced. The cleanup\n // below still runs first.\n if (scrapeMode === ScrapeMode.Playwright) {\n throw new RenderError(context.source, renderError);\n }\n context.errors.push(renderError);\n } finally {\n const closed = await this.cleanupPageAndContext(\n handles.page,\n handles.browserContext,\n context.source,\n );\n // A page or context that will not close may have left Chromium stuck, and\n // so may a render that failed before it had a context of its own: that\n // call was waiting on the browser itself. Either way, replace it. A failed\n // render alone does not: its context closed cleanly, and other pages may be\n // using the same browser.\n const failedBeforeContext =\n renderedHtml === null && handles.browserContext === null;\n if (browser && (!closed || failedBeforeContext)) {\n await this.managedBrowser.retire(\n browser,\n closed\n ? `reset after Playwright could not open a context for ${context.source}`\n : `reset after Playwright cleanup failure for ${context.source}`,\n );\n }\n }\n\n if (renderedHtml !== null) {\n context.content = renderedHtml;\n logger.debug(\n `Playwright middleware updated content for ${context.source}. Proceeding.`,\n );\n }\n\n await next();\n }\n\n /**\n * Renders `context.content` in a new browser context and returns the result.\n *\n * Records the context and page in `handles` as soon as they exist, so the caller\n * can close them even when it abandons the render midway.\n */\n private async renderPage(\n browser: Browser,\n context: MiddlewareContext,\n handles: RenderHandles,\n ): Promise<string> {\n const { credentials, origin } = extractCredentialsAndOrigin(context.source);\n const customHeaders: Record<string, string> = context.options?.headers ?? {};\n\n // Always create a browser context (with or without credentials)\n const browserContext = await browser.newContext({\n userAgent: getHeader(customHeaders, \"user-agent\") || DEFAULT_BROWSER_USER_AGENT,\n viewport: { width: 1920, height: 1080 },\n ignoreHTTPSErrors: this.accessPolicy.shouldAllowInvalidTls(\n \"https://browser-context.local\",\n ),\n ...(credentials ? { httpCredentials: credentials } : {}),\n });\n handles.browserContext = browserContext;\n const page = await browserContext.newPage();\n handles.page = page;\n\n logger.debug(`Playwright: Processing ${context.source}`);\n\n // Inject shadow DOM extractor script early\n await this.injectShadowDOMExtractor(page);\n\n const initialRequestUrl = (() => {\n try {\n const initialUrl = new URL(context.source);\n initialUrl.hash = \"\";\n return initialUrl.toString();\n } catch {\n return context.source;\n }\n })();\n\n // Set up route interception with special handling for the initial page load\n await page.route(\"**/*\", async (route) => {\n const reqUrl = route.request().url();\n\n // Serve the initial HTML for the main page (bypass cache and fetch)\n if (reqUrl === initialRequestUrl) {\n try {\n return await route.fulfill({\n status: 200,\n contentType: \"text/html; charset=utf-8\",\n body: context.content,\n });\n } catch (error) {\n if (this.isRouteAlreadyHandledError(error)) {\n logger.debug(`Route already handled (initial page): ${reqUrl}`);\n return;\n }\n // Re-throw other errors\n throw error;\n }\n }\n\n // For all other requests, use the standard caching logic\n await this.handleSubresourceRoute(\n route,\n customHeaders,\n credentials ?? undefined,\n origin ?? undefined,\n );\n });\n\n // Wait for either body (normal HTML) or frameset (frameset documents) to appear\n const pageTimeoutMs = this.getPageTimeoutMs();\n\n // Load initial HTML content\n await page.goto(context.source, {\n waitUntil: \"load\",\n timeout: this.getBrowserTimeoutMs(),\n });\n\n await page.waitForSelector(\"body, frameset\", {\n timeout: pageTimeoutMs,\n });\n\n // Wait for network idle to let dynamic content initialize\n try {\n await page.waitForLoadState(\"networkidle\", {\n timeout: pageTimeoutMs,\n });\n } catch {\n logger.debug(\"Network idle timeout, proceeding anyway\");\n }\n\n await this.waitForLoadingToComplete(page);\n await this.waitForIframesToLoad(page);\n await this.waitForFramesetsToLoad(page);\n\n // Extract content using shadow DOM-aware method\n const { content, method } = await this.extractContentWithShadowDOMSupport(page);\n logger.debug(\n `Playwright: Successfully rendered content for ${context.source} using ${method}`,\n );\n return content;\n }\n\n /**\n * Safely combines original page content with shadow DOM content outside the browser context.\n * This avoids triggering any anti-scraping detection mechanisms.\n */\n private combineContentSafely(\n originalContent: string,\n shadowMappings: ShadowMapping[],\n ): string {\n let combinedContent = originalContent;\n\n // Add shadow content at the end of the body to avoid breaking the document structure\n const bodyCloseIndex = combinedContent.lastIndexOf(\"</body>\");\n if (bodyCloseIndex !== -1) {\n let shadowContentHTML = \"\\n<!-- SHADOW DOM CONTENT EXTRACTED SAFELY -->\\n\";\n\n // Sort by content length (largest first) to prioritize important content\n const sortedMappings = shadowMappings.sort(\n (a, b) => b.shadowContent.length - a.shadowContent.length,\n );\n\n sortedMappings.forEach((mapping) => {\n shadowContentHTML += `\\n<!-- SHADOW CONTENT: ${mapping.hostTagName} (${mapping.shadowContent.length} chars) -->\\n`;\n shadowContentHTML += mapping.shadowContent;\n shadowContentHTML += `\\n<!-- END SHADOW CONTENT: ${mapping.hostTagName} -->\\n`;\n });\n\n shadowContentHTML += \"\\n<!-- END ALL SHADOW DOM CONTENT -->\\n\";\n\n // Insert before closing body tag\n combinedContent =\n combinedContent.slice(0, bodyCloseIndex) +\n shadowContentHTML +\n combinedContent.slice(bodyCloseIndex);\n }\n\n return combinedContent;\n }\n}\n\n/**\n * Extracts credentials and origin from a URL string.\n * Returns { credentials, origin } where credentials is null if not present.\n */\nexport function extractCredentialsAndOrigin(urlString: string): {\n credentials: { username: string; password: string } | null;\n origin: string | null;\n} {\n try {\n const url = new URL(urlString);\n const origin = url.origin;\n if (url.username && url.password) {\n return {\n credentials: { username: url.username, password: url.password },\n origin,\n };\n }\n return { credentials: null, origin };\n } catch {\n return { credentials: null, origin: null };\n }\n}\n\n/**\n * Merges Playwright request headers, custom headers, and credentials.\n * - Custom headers are merged in unless already present (except Authorization, see below).\n * - If credentials are present and the request is same-origin, injects Authorization if not already set.\n */\nexport function mergePlaywrightHeaders(\n requestHeaders: Record<string, string>,\n customHeaders: Record<string, string>,\n credentials?: { username: string; password: string },\n origin?: string,\n reqOrigin?: string,\n): Record<string, string> {\n let headers = { ...requestHeaders };\n for (const [key, value] of Object.entries(customHeaders)) {\n if (key.toLowerCase() === \"authorization\" && headers.authorization) continue;\n headers[key] = value;\n }\n if (credentials && origin && reqOrigin === origin && !headers.authorization) {\n const basic = Buffer.from(`${credentials.username}:${credentials.password}`).toString(\n \"base64\",\n );\n headers = {\n ...headers,\n Authorization: `Basic ${basic}`,\n };\n }\n return headers;\n}\n","import type * as cheerio from \"cheerio\";\nimport type { Element } from \"domhandler\";\nimport { logger } from \"../../utils/logger\";\nimport type { ContentProcessorMiddleware, MiddlewareContext } from \"./types\";\n\n/**\n * Minimum share of the sanitized body's visible text that the main-content\n * region must hold before extraction is scoped to it. Tuning value: measured\n * across a sample of documentation sites the region holds >98% of the\n * remaining text, so a floor of 0.5 never fires on a well-formed page while\n * still refusing to scope when `<main>` marks a small decorative shell and\n * the real content lives elsewhere.\n */\nconst MAIN_CONTENT_MIN_TEXT_RATIO = 0.5;\n\n/**\n * Elements whose text a reader never sees: script source, style rules, and\n * `<noscript>` fallbacks, which the parser keeps as raw markup text. They are\n * removed before the safety net captures the body, so its measure and the\n * body it restores never contain them.\n */\nconst NON_TEXT_SELECTOR = \"script, style, noscript\";\n\n/**\n * Length of an element's text as a reader would see it, with runs of\n * whitespace collapsed to a single space.\n *\n * Cheerio's `.text()` returns raw text nodes, so on pretty-printed markup the\n * indentation between tags counts as content. That matters for the\n * main-content ratio: removing a chrome element leaves its surrounding\n * whitespace node behind, outside the content region, which deflates the\n * region's measured share and can push a dominant `<main>` below the floor.\n */\nfunction visibleTextLength(text: string): number {\n return text.replace(/\\s+/g, \" \").trim().length;\n}\n\n/**\n * Options for HtmlSanitizerMiddleware.\n */\nexport interface HtmlSanitizerOptions {\n /** CSS selectors for elements to remove *in addition* to the defaults. */\n excludeSelectors?: string[];\n}\n\n/**\n * Middleware to remove unwanted elements from parsed HTML content using Cheerio.\n * It expects the Cheerio API object (`context.dom`) to be populated by a preceding middleware\n * (e.g., HtmlCheerioParserMiddleware).\n * It modifies the `context.dom` object in place.\n *\n * Sanitization runs in two passes:\n * 1. Selector removal — strips known chrome, ads, and search widgets.\n * 2. Main-content scoping — when the page declares its content region with\n * `<main>` or `role=\"main\"`, everything outside that region is dropped.\n * This catches site-specific promo banners and sponsor blocks that no\n * selector list can enumerate. Guarded by\n * {@link MAIN_CONTENT_MIN_TEXT_RATIO} so a page whose content sits outside\n * the declared region is left untouched.\n */\nexport class HtmlSanitizerMiddleware implements ContentProcessorMiddleware {\n // Default selectors to remove. Script, style and noscript are not listed:\n // `NON_TEXT_SELECTOR` removes them before this list runs.\n private readonly defaultSelectorsToRemove = [\n \"aside\",\n \"nav\",\n \"footer\",\n \"svg\",\n \"link\",\n \"meta\",\n \"iframe\",\n \"header\",\n \"button\",\n \"input\",\n \"textarea\",\n \"select\",\n // \"form\", // Keep commented\n \".ads\",\n \".advertisement\",\n \".banner\",\n \".cookie-banner\",\n \".cookie-consent\",\n \".hidden\",\n \".hide\",\n \".mobile-menu\",\n \".mobile-nav\",\n \".modal\",\n \".nav-bar\",\n \".overlay\",\n \".popup\",\n \".promo\",\n \".mw-editsection\",\n \".search-bar\",\n \".search-form\",\n \".side-bar\",\n \".sidebar\",\n \".social-share\",\n \".sticky\",\n \".table-of-contents\",\n \".toc\",\n \"#ads\",\n \"#banner\",\n \"#cookieBanner\",\n \"#mobile-menu\",\n \"#mobile-nav\",\n \"#modal\",\n \"#nav\",\n \"#overlay\",\n \"#popup\",\n \"#sidebar\",\n \"#socialMediaBox\",\n \"#stickyHeader\",\n \"#ad-container\",\n \".ad-container\",\n \".login-form\",\n \".signup-form\",\n \".tooltip\",\n \".dropdown-menu\",\n // \".alert\", // Keep commented\n \".breadcrumb\",\n \".pagination\",\n // '[role=\"alert\"]', // Keep commented\n '[role=\"banner\"]',\n '[role=\"complementary\"]',\n '[role=\"dialog\"]',\n '[role=\"alertdialog\"]',\n '[role=\"navigation\"]',\n '[role=\"search\"]',\n '[role=\"region\"][aria-label*=\"skip\" i]',\n '[aria-modal=\"true\"]',\n \".noprint\",\n // Skip-links and screen-reader-only anchors (e.g. \"Skip to main content\").\n // Scoped to <a> so icon-button labels (`<span class=\"sr-only\">`) are left alone.\n \"a.sr-only\",\n \"a.skip-link\",\n \"a.skip-nav\",\n \"a.screen-reader-only\",\n \"a.visually-hidden\",\n // Breadcrumb variants beyond the .breadcrumb class above (ARIA + schema.org).\n '[aria-label=\"Breadcrumb\" i]',\n '[itemtype*=\"BreadcrumbList\"]',\n // Ad networks — removed at sanitization time (after render) rather than at\n // network level, to avoid triggering anti-adblock detection on monetized\n // sites. See subresourceBlocklist.ts for the rationale on why ads are not\n // network-blocked.\n // Carbon Ads (Vite, Astro, Tailwind, MDN, …)\n \"#carbonads\",\n \".carbonads\",\n \".carbon-wrap\",\n \".carbon-text\",\n \".carbon-img\",\n \".carbon-poweredby\",\n // Scoped to the click-redirect host (srv.carbonads.net) rather than the\n // apex domain so that legitimate prose links to carbonads.net survive.\n 'a[href*=\"srv.carbonads.net\"]',\n // BuySellAds\n \".bsa-promotion\",\n \".bsa-cpc\",\n '[id^=\"bsap_\"]',\n '[id^=\"bsa-zone_\"]',\n 'img[src*=\"buysellads.com\"]',\n 'img[src*=\"buysellads.net\"]',\n // EthicalAds (ReadTheDocs, Python/Django docs)\n \".ethical-rtd\",\n \".ethical-fixedfooter\",\n \".ethical-bottom-right\",\n \"[data-ea-publisher]\",\n \".keep-us-sustainable\",\n 'img[src*=\"ethicalads.io\"]',\n // Google AdSense\n \".adsbygoogle\",\n \"ins.adsbygoogle\",\n '[id^=\"google_ads_iframe\"]',\n 'img[src*=\"googlesyndication.com\"]',\n 'img[src*=\"doubleclick.net\"]',\n // Outbrain / Taboola — content-recommendation widgets, indistinguishable\n // from ads on doc pages.\n \".OUTBRAIN\",\n '[data-widget-id^=\"OB_\"]',\n \".taboola\",\n '[id^=\"taboola-\"]',\n // Tracker pixels that escape via async injection\n 'img[src*=\"bidr.io\"]',\n 'img[src*=\"adnxs.com\"]',\n 'img[src*=\"adsrvr.org\"]',\n 'img[src*=\"analytics.yahoo.com\"]',\n // Third-party search widgets injected outside of nav/header.\n // Algolia DocSearch (dominant in technical docs)\n \".DocSearch\",\n \".DocSearch-Button\",\n \".DocSearch-Container\",\n \".DocSearch-Modal\",\n \"#docsearch\",\n '[id^=\"docsearch-\"]',\n \".algolia-autocomplete\",\n \".algolia-docsearch-suggestion\",\n // MkDocs Material result containers (the search box is in nav; results can\n // render standalone)\n \".md-search-result\",\n \".md-search__output\",\n // Sphinx / ReadTheDocs search\n \"#searchbox\",\n \"#search-results\",\n \".wy-side-search\",\n // Swiftype / Elastic Site Search\n \"#st-search-input\",\n \"#st-results-container\",\n \".st-default-search-input\",\n ];\n\n /**\n * Replace the body with the page's main-content region, when the page\n * declares one and it holds the bulk of the remaining visible text.\n *\n * Runs after selector removal so the ratio is measured against content that\n * already has nav, footers, ads, and search widgets stripped — at that point\n * anything still outside `<main>` is site chrome (promo banners, sponsor\n * strips, cookie notices, keyboard-shortcut help).\n *\n * @param $ The Cheerio DOM, modified in place.\n * @param source Source URL, used for logging only.\n */\n private scopeToMainContent($: cheerio.CheerioAPI, source: string): void {\n const candidates = $(\"main\").length > 0 ? $(\"main\") : $('[role=\"main\"]');\n if (candidates.length === 0) return;\n\n // Keep every declared region, not the richest one. Pages do carry more than\n // one `<main>` (invalid but common) — a guide beside an API reference, an\n // article beside a pre-rendered version picker — and each is content the\n // author marked as such. Choosing between them discarded whole sections\n // with nothing above `debug` to say so.\n const regions: Element[] = [];\n candidates.each((_, element) => {\n const tagName = $(element).prop(\"tagName\")?.toLowerCase();\n if (tagName === \"html\" || tagName === \"body\") return;\n // A region nested inside one already kept is the same region declared\n // twice; keeping both would index its text twice. Only same-kind nesting\n // reaches here — the candidate set is `<main>` or `[role=main]`, never\n // both — so this is a `<main>` inside a `<main>`.\n if (\n $(element)\n .parents()\n .toArray()\n .some((parent) => regions.includes(parent as Element))\n ) {\n return;\n }\n regions.push(element as Element);\n });\n if (regions.length === 0) return;\n\n const regionLengths = regions.map((element) => visibleTextLength($(element).text()));\n const keptLength = regionLengths.reduce((total, length) => total + length, 0);\n if (keptLength === 0) return;\n\n const bodyLength = visibleTextLength($(\"body\").text());\n if (bodyLength === 0) return;\n\n // Measured on the largest single region, not on their sum. The floor asks\n // \"does a declared region actually hold this page's content?\", and summing\n // answers a different question: two regions of 30% each would clear it and\n // scope the page, discarding the 40% outside that the floor exists to\n // protect. Whether to scope is decided by the best region; what to keep,\n // once scoping, is all of them.\n const ratio = Math.max(...regionLengths) / bodyLength;\n if (ratio < MAIN_CONTENT_MIN_TEXT_RATIO) {\n logger.debug(\n `Main-content region holds only ${(ratio * 100).toFixed(1)}% of the text for ${source}; keeping full body`,\n );\n return;\n }\n\n const kept = regions.map((element) => $(element).clone());\n $(\"body\")\n .empty()\n .append(...kept);\n logger.debug(\n `Scoped content to ${regions.length} main region(s) (${keptLength}/${bodyLength} chars) for ${source}`,\n );\n }\n\n async process(context: MiddlewareContext, next: () => Promise<void>): Promise<void> {\n // Check if Cheerio DOM exists\n const $ = context.dom;\n if (!$) {\n logger.warn(\n `⏭️ Skipping ${this.constructor.name}: context.dom is missing. Ensure HtmlCheerioParserMiddleware runs before this.`,\n );\n await next();\n return;\n }\n\n try {\n // Remove what is never readable before the safety net captures the\n // body. Cheerio's `.text()` counts script source, so with scripts still\n // in, a page with no visible text (an empty container that a script\n // fills in the browser) passes as having content, and the restore below\n // would bring the script back to be indexed as the page's text.\n $(NON_TEXT_SELECTOR).remove();\n\n // Capture the body content before sanitization for safety net\n const bodyBeforeSanitization = $(\"body\").html() || \"\";\n const textLengthBefore = $(\"body\").text().trim().length;\n\n // Remove unwanted elements using Cheerio\n const selectorsToRemove = [\n ...(context.options.excludeSelectors || []), // Use options from the context\n ...this.defaultSelectorsToRemove,\n ];\n logger.debug(\n `Removing elements matching ${selectorsToRemove.length} selectors for ${context.source}`,\n );\n let removedCount = 0;\n for (const selector of selectorsToRemove) {\n try {\n const elements = $(selector); // Use Cheerio selector\n // Filter out html and body tags to prevent removing them or their entire content\n const filteredElements = elements.filter(function () {\n const tagName = $(this).prop(\"tagName\")?.toLowerCase();\n return tagName !== \"html\" && tagName !== \"body\";\n });\n const count = filteredElements.length;\n if (count > 0) {\n filteredElements.remove(); // Use Cheerio remove\n removedCount += count;\n }\n } catch (selectorError) {\n // Log invalid selectors but continue with others\n // Cheerio is generally more tolerant of invalid selectors than querySelectorAll\n logger.warn(\n `⚠️ Potentially invalid selector \"${selector}\" during element removal: ${selectorError}`,\n );\n context.errors.push(\n new Error(`Invalid selector \"${selector}\": ${selectorError}`),\n );\n }\n }\n logger.debug(`Removed ${removedCount} elements for ${context.source}`);\n\n // Second pass: narrow to the page's declared main-content region.\n this.scopeToMainContent($, context.source);\n\n // Safety net: Check if sanitization removed all content\n const textLengthAfter = $(\"body\").text().trim().length;\n if (textLengthBefore > 0 && textLengthAfter === 0) {\n logger.warn(\n `⚠️ Sanitization removed all content from ${context.source}. Reverting to pre-sanitization state.`,\n );\n // Restore the body content\n $(\"body\").html(bodyBeforeSanitization);\n }\n\n // The context.dom object ($) has been modified in place.\n } catch (error) {\n logger.error(\n `❌ Error during HTML element removal for ${context.source}: ${error}`,\n );\n context.errors.push(\n error instanceof Error\n ? error\n : new Error(`HTML element removal failed: ${String(error)}`),\n );\n // Decide if pipeline should stop? For now, continue.\n }\n\n // Proceed to the next middleware\n await next();\n }\n}\n","// @ts-expect-error\nimport { gfm } from \"@joplin/turndown-plugin-gfm\";\nimport type * as cheerio from \"cheerio\";\nimport type { AnyNode, Element } from \"domhandler\";\nimport TurndownService from \"turndown\";\nimport { logger } from \"../../utils/logger\";\nimport { fullTrim } from \"../../utils/string\";\nimport type { ContentProcessorMiddleware, MiddlewareContext } from \"./types\";\n\nconst maxGfmTableRows = 500;\nconst maxGfmTableCells = 1_000;\nconst maxGfmTableHtmlLength = 100_000;\nconst gfmTableChunkRows = 100;\nconst preservedTablePlaceholderAttribute = \"data-docs-mcp-preserved-table-id\";\nconst ELEMENT_NODE = 1;\nconst TEXT_NODE = 3;\n\n/**\n * How far the node-by-node salvage will descend before taking a subtree's text.\n *\n * Real documentation pages nest 12-25 levels deep, so this never engages on\n * one; it bounds the cost on documents built by a generator that emits\n * thousands of nested wrappers, which are also the documents whose conversion\n * fails in the first place.\n */\nconst MAX_SALVAGE_DEPTH = 100;\n\n/**\n * Middleware to convert the final processed HTML content (from Cheerio object in context.dom)\n * into Markdown using Turndown, applying custom rules.\n */\nexport class HtmlToMarkdownMiddleware implements ContentProcessorMiddleware {\n private turndownService: TurndownService;\n private readonly preservedTableHtml = new Map<string, string>();\n private preservedTableSequence = 0;\n\n constructor() {\n this.turndownService = new TurndownService({\n headingStyle: \"atx\",\n hr: \"---\",\n bulletListMarker: \"-\",\n codeBlockStyle: \"fenced\",\n emDelimiter: \"_\",\n strongDelimiter: \"**\",\n linkStyle: \"inlined\",\n });\n\n this.turndownService.use(gfm);\n\n this.addCustomRules();\n }\n\n private addCustomRules(): void {\n // Preserve code blocks and syntax (replicated from HtmlProcessor)\n this.turndownService.addRule(\"pre\", {\n filter: [\"pre\"],\n replacement: (_content: string, node: Node) => {\n const element = node as unknown as HTMLElement;\n let language = element.getAttribute(\"data-language\") || \"\";\n if (!language) {\n // Try to infer the language from the class name\n // This is a common pattern in syntax highlighters\n const highlightElement =\n element.closest(\n '[class*=\"highlight-source-\"], [class*=\"highlight-\"], [class*=\"language-\"]',\n ) ||\n element.querySelector(\n '[class*=\"highlight-source-\"], [class*=\"highlight-\"], [class*=\"language-\"]',\n );\n if (highlightElement) {\n const className = highlightElement.className;\n const match = className.match(\n /(?:highlight-source-|highlight-|language-)(\\w+)/,\n );\n if (match) language = match[1];\n }\n }\n\n const text = this.extractPreText(element);\n\n return `\\n\\`\\`\\`${language}\\n${text.replace(/^\\n+|\\n+$/g, \"\")}\\n\\`\\`\\`\\n`;\n },\n });\n this.turndownService.addRule(\"anchor\", {\n filter: [\"a\"],\n replacement: (content: string, node: Node) => {\n const element = node as HTMLElement;\n const href = element.getAttribute(\"href\");\n const normalizedContent = this.normalizeLinkContent(content);\n\n if (!normalizedContent || normalizedContent === \"#\") {\n return \"\"; // Remove if content is # or empty\n }\n if (!href) {\n return normalizedContent; // Preserve content if href is missing or empty\n }\n return `[${normalizedContent}](${href})`; // Standard link conversion\n },\n });\n this.turndownService.addRule(\"preservedOversizedTable\", {\n filter: (node: Node) => {\n const element = node as HTMLElement;\n return (\n element.nodeName === \"DIV\" &&\n element.hasAttribute(preservedTablePlaceholderAttribute)\n );\n },\n replacement: (_content: string, node: Node) => {\n const element = node as HTMLElement;\n const tableId = element.getAttribute(preservedTablePlaceholderAttribute);\n const tableHtml = tableId ? this.preservedTableHtml.get(tableId) : undefined;\n return tableHtml ? `\\n\\n${tableHtml}\\n\\n` : \"\";\n },\n });\n }\n\n /**\n * Reads the text of a `<pre>` block, inserting the line breaks its markup\n * only implies visually.\n *\n * The walk is deliberately read-only. Cloning or mutating the node would be\n * the obvious way to splice newlines in, but `cloneNode` recreates each\n * element through `document.createElement`, which rejects any name the DOM\n * considers invalid. Real pages carry such names — a generator that emits\n * `<lt;200 cores/socket>` for text it failed to escape leaves elements no\n * DOM will recreate — and a throw here fails the whole page conversion.\n */\n private extractPreText(element: HTMLElement): string {\n // Modern syntax highlighters (Shiki, Prism, highlight.js, etc.) split each\n // line into a `<span class=\"line\">` or `<div class=\"line\">` with no\n // surrounding whitespace, relying on CSS `display: block` for the visual\n // line break. `textContent` collapses those into a single line, so we emit\n // a newline after every line container except the last.\n const lineNodes = Array.from(\n element.querySelectorAll(\"span.line, div.line, [data-line]\"),\n );\n const lineNodeSet = new Set<Node>(lineNodes);\n const lastLineNode = lineNodes[lineNodes.length - 1];\n\n let text = \"\";\n const visit = (node: Node): void => {\n if (node.nodeType === TEXT_NODE) {\n text += node.nodeValue ?? \"\";\n return;\n }\n if (node.nodeType !== ELEMENT_NODE) {\n return;\n }\n if (node.nodeName === \"BR\") {\n text += \"\\n\";\n return;\n }\n for (const child of Array.from(node.childNodes)) {\n visit(child);\n }\n if (lineNodeSet.has(node) && node !== lastLineNode) {\n text += \"\\n\";\n }\n };\n for (const child of Array.from(element.childNodes)) {\n visit(child);\n }\n return text;\n }\n\n /**\n * Converts as much of a subtree as Turndown will accept, descending past the\n * parts it rejects.\n *\n * Turndown converts a document in one call, so a single node it cannot\n * handle costs the whole page. Retrying node by node confines the damage:\n * every subtree that converts keeps its Markdown — headings included, which\n * is what the semantic splitter chunks on — and only the subtree that keeps\n * throwing falls back to its text. Formatting inside that subtree flattens;\n * the point is to keep the words.\n */\n private convertNodeWithFallback(\n $: cheerio.CheerioAPI,\n node: AnyNode,\n depth = 0,\n ): string {\n if (node.type === \"text\") {\n return fullTrim(node.data);\n }\n if (node.type !== \"tag\") {\n return \"\";\n }\n\n // Each level serializes its whole subtree to hand Turndown a string, so\n // descending costs O(depth x size) and a pathologically nested document\n // spends minutes on one page. Past this depth the remaining structure is\n // not carrying meaning anyway, so take the words and stop.\n if (depth >= MAX_SALVAGE_DEPTH) {\n return fullTrim($(node).text());\n }\n\n try {\n return this.turndownService.turndown($.html(node)).trim();\n } catch {\n const parts = $(node)\n .contents()\n .toArray()\n .map((child) => this.convertNodeWithFallback($, child, depth + 1))\n .filter((part) => part.length > 0);\n\n return parts.length > 0 ? parts.join(\"\\n\\n\") : fullTrim($(node).text());\n }\n }\n\n /**\n * Salvages Markdown from a document whose whole-document conversion threw.\n */\n private salvageMarkdown($: cheerio.CheerioAPI): string {\n const roots = $(\"body\").length > 0 ? $(\"body\").contents() : $.root().contents();\n return roots\n .toArray()\n .map((node) => this.convertNodeWithFallback($, node))\n .filter((part) => part.length > 0)\n .join(\"\\n\\n\")\n .trim();\n }\n\n private normalizeLinkContent(content: string): string {\n return fullTrim(content).replace(/[ \\t]*[\\r\\n]+[ \\t]*/g, \" \");\n }\n\n private splitOversizedTables($: cheerio.CheerioAPI, source: string): void {\n $(\"table\").each((_index, element) => {\n const $table = $(element);\n const rowCount = $table.find(\"tr\").length;\n const cellCount = $table.find(\"td, th\").length;\n const htmlLength = $.html(element).length;\n\n if (\n rowCount <= maxGfmTableRows &&\n cellCount <= maxGfmTableCells &&\n htmlLength <= maxGfmTableHtmlLength\n ) {\n return;\n }\n\n const replacement = this.buildSplitTableHtml($, $table);\n if (!replacement) {\n const tableId = `table-${++this.preservedTableSequence}`;\n this.preservedTableHtml.set(tableId, $.html(element));\n logger.warn(\n `⚠️ Preserving oversized HTML table for ${source} as HTML before GFM conversion: ${rowCount} rows, ${cellCount} cells, ${htmlLength} chars`,\n );\n $table.replaceWith(\n `<div ${preservedTablePlaceholderAttribute}=\"${tableId}\">preserved table</div>`,\n );\n return;\n }\n\n logger.warn(\n `⚠️ Splitting oversized HTML table for ${source} before GFM conversion: ${rowCount} rows, ${cellCount} cells, ${htmlLength} chars`,\n );\n $table.replaceWith(replacement);\n });\n }\n\n private buildSplitTableHtml(\n $: cheerio.CheerioAPI,\n $table: cheerio.Cheerio<Element>,\n ): string | null {\n const headerRows = this.getHeaderRows($table);\n const headerRowSet = new Set(headerRows);\n const dataRows = $table\n .find(\"tr\")\n .toArray()\n .filter((row): row is Element => row.type === \"tag\" && !headerRowSet.has(row));\n\n if (dataRows.length <= gfmTableChunkRows) {\n return null;\n }\n\n const chunks: string[] = [];\n const headerHtml = headerRows.map((row) => $.html(row)).join(\"\");\n const preservedChildHtml = this.getPreservedTableChildHtml($, $table);\n\n for (let index = 0; index < dataRows.length; index += gfmTableChunkRows) {\n const rowsHtml = dataRows\n .slice(index, index + gfmTableChunkRows)\n .map((row) => $.html(row))\n .join(\"\");\n const tableParts = [\"<table>\", preservedChildHtml];\n if (headerHtml) {\n tableParts.push(\"<thead>\", headerHtml, \"</thead>\");\n }\n tableParts.push(\"<tbody>\", rowsHtml, \"</tbody></table>\");\n chunks.push(tableParts.join(\"\"));\n }\n\n return chunks.join(\"\\n\");\n }\n\n private getPreservedTableChildHtml(\n $: cheerio.CheerioAPI,\n $table: cheerio.Cheerio<Element>,\n ): string {\n return $table\n .children(\"caption, colgroup\")\n .toArray()\n .filter((child): child is Element => child.type === \"tag\")\n .map((child) => $.html(child))\n .join(\"\");\n }\n\n private getHeaderRows($table: cheerio.Cheerio<Element>): Element[] {\n const theadRows = $table\n .children(\"thead\")\n .find(\"tr\")\n .toArray()\n .filter((row): row is Element => row.type === \"tag\");\n\n if (theadRows.length > 0) {\n return theadRows;\n }\n\n const firstRow = $table.find(\"tr\").first();\n if (firstRow.length === 0) {\n return [];\n }\n\n const cells = firstRow.children(\"th, td\").toArray();\n const isHeaderRow =\n cells.length > 0 &&\n cells.every((cell) => cell.type === \"tag\" && cell.tagName === \"th\");\n\n return isHeaderRow ? (firstRow.toArray() as Element[]) : [];\n }\n\n /**\n * Processes the context to convert the sanitized HTML body node to Markdown.\n * @param context The current processing context.\n * @param next Function to call the next middleware.\n */\n async process(context: MiddlewareContext, next: () => Promise<void>): Promise<void> {\n // Check if we have a Cheerio object from a previous step\n const $ = context.dom;\n if (!$) {\n logger.warn(\n `⏭️ Skipping ${this.constructor.name}: context.dom is missing. Ensure HtmlCheerioParserMiddleware ran correctly.`,\n );\n await next();\n return;\n }\n\n // Only process if we have a Cheerio object (implicitly means it's HTML)\n try {\n logger.debug(`Converting HTML content to Markdown for ${context.source}`);\n this.preservedTableHtml.clear();\n this.splitOversizedTables($, context.source);\n // Convert the body alone. The head holds the title, which is metadata:\n // converting it too stores the title as the text of a page whose body\n // is empty. Only a document with no body element, such as a frameset\n // page, is converted whole.\n const body = $(\"body\");\n const htmlToConvert = body.length > 0 ? (body.html() ?? \"\") : $.html();\n const markdown = this.turndownService.turndown(htmlToConvert).trim();\n\n if (!markdown) {\n // If conversion results in empty markdown, log a warning but treat as valid empty markdown\n const warnMsg = `HTML to Markdown conversion resulted in empty content for ${context.source}.`;\n logger.warn(`⚠️ ${warnMsg}`);\n context.content = \"\";\n } else {\n // Conversion successful and produced non-empty markdown\n context.content = markdown;\n logger.debug(`Successfully converted HTML to Markdown for ${context.source}`);\n }\n\n // Update contentType to reflect the converted format\n context.contentType = \"text/markdown\";\n } catch (error) {\n logger.error(\n `❌ Error converting HTML to Markdown for ${context.source}: ${error}`,\n );\n context.errors.push(\n new Error(\n `Failed to convert HTML to Markdown: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n // A failed conversion leaves `context.content` holding the HTML we were\n // handed, and the rest of the pipeline would split and embed that markup\n // as if it were prose. Convert what we can instead, node by node.\n //\n // Guarded in turn, because the salvage runs the same converter and walks\n // the same document: whatever defeated the first pass can defeat it too,\n // and an escaping throw would skip the assignment below and leave the\n // markup in place — the one outcome this whole branch exists to prevent.\n let salvaged = \"\";\n try {\n salvaged = this.salvageMarkdown($);\n } catch (salvageError) {\n logger.warn(\n `⚠️ Could not salvage any Markdown for ${context.source}: ${\n salvageError instanceof Error ? salvageError.message : String(salvageError)\n }`,\n );\n }\n if (salvaged) {\n logger.warn(\n `⚠️ Recovered ${salvaged.length} characters of Markdown for ${context.source} after a failed conversion`,\n );\n context.contentType = \"text/markdown\";\n }\n // Empty means we salvaged nothing. Paired with the recorded error that\n // reads downstream as \"we learned nothing about this page\", which leaves\n // any previously stored content untouched.\n context.content = salvaged;\n } finally {\n this.preservedTableHtml.clear();\n }\n\n // Call the next middleware in the chain regardless of whether conversion happened\n await next();\n\n // No need to close/free Cheerio object explicitly\n // context.dom = undefined; // Optionally clear the dom property if no longer needed downstream\n }\n}\n","/**\n * Utility functions for enhanced charset detection and handling.\n */\n\nimport { logger } from \"../../utils/logger\";\n\n/**\n * Detects charset from HTML meta tags.\n * Looks for both <meta charset=\"...\"> and <meta http-equiv=\"Content-Type\" content=\"text/html; charset=...\">\n */\nexport function detectCharsetFromHtml(htmlContent: string): string | undefined {\n // Match <meta charset=\"...\"> (HTML5 style)\n const charsetMatch = htmlContent.match(\n /<meta\\s+charset\\s*=\\s*[\"']?([^\"'>\\s]+)[\"']?[^>]*>/i,\n );\n if (charsetMatch) {\n return charsetMatch[1].toLowerCase();\n }\n\n // Match <meta http-equiv=\"Content-Type\" content=\"...charset=...\"> (HTML4 style)\n const httpEquivMatch = htmlContent.match(\n /<meta\\s+http-equiv\\s*=\\s*[\"']?content-type[\"']?\\s+content\\s*=\\s*[\"']?[^\"'>]*charset=([^\"'>\\s;]+)/i,\n );\n if (httpEquivMatch) {\n return httpEquivMatch[1].toLowerCase();\n }\n\n return undefined;\n}\n\n/**\n * Determines the best charset to use for decoding content.\n * Prioritizes HTML meta tags over HTTP headers for HTML content.\n */\nexport function resolveCharset(\n httpCharset: string | undefined,\n htmlContent: string | Buffer,\n mimeType: string,\n): string {\n // For non-HTML content, use HTTP charset or default to UTF-8\n if (!mimeType.includes(\"html\")) {\n return httpCharset || \"utf-8\";\n }\n\n // For HTML content, try to detect charset from meta tags\n let htmlString: string;\n try {\n // Try to decode as UTF-8 first to look for meta tags\n htmlString =\n typeof htmlContent === \"string\" ? htmlContent : htmlContent.toString(\"utf-8\");\n } catch {\n // If UTF-8 fails, use the HTTP charset or fall back to latin1 for meta tag detection\n htmlString =\n typeof htmlContent === \"string\"\n ? htmlContent\n : htmlContent.toString((httpCharset || \"latin1\") as BufferEncoding);\n }\n\n // Look for charset in HTML meta tags (usually in first 1024 bytes)\n const headContent = htmlString.substring(0, 1024);\n const metaCharset = detectCharsetFromHtml(headContent);\n\n if (metaCharset) {\n logger.debug(`Detected charset from HTML meta tag: ${metaCharset}`);\n return metaCharset;\n }\n\n if (httpCharset) {\n logger.debug(`Using charset from HTTP header: ${httpCharset}`);\n return httpCharset;\n }\n\n logger.debug(\"No charset detected, defaulting to UTF-8\");\n return \"utf-8\";\n}\n\n/**\n * Common charset aliases and their canonical names.\n * Helps handle cases where servers use non-standard charset names.\n */\nexport const CHARSET_ALIASES: Record<string, string> = {\n \"iso-8859-1\": \"latin1\",\n \"iso_8859-1\": \"latin1\",\n \"latin-1\": \"latin1\",\n \"windows-1252\": \"cp1252\",\n \"cp-1252\": \"cp1252\",\n \"ms-ansi\": \"cp1252\",\n utf8: \"utf-8\",\n unicode: \"utf-8\",\n \"us-ascii\": \"ascii\",\n ascii: \"ascii\",\n};\n\n/**\n * Normalizes charset name to handle common aliases.\n */\nexport function normalizeCharset(charset: string): string {\n const normalized = charset.toLowerCase().trim();\n return CHARSET_ALIASES[normalized] || normalized;\n}\n","import iconv from \"iconv-lite\";\nimport { normalizeCharset } from \"./charset\";\n\n/**\n * Decodes a Buffer or string to a JavaScript string using the specified charset.\n * The charset should be the encoding as reported by the source (e.g., HTTP header).\n * The result is always a valid JS string (Unicode/UTF-16).\n *\n * If the charset is missing or unsupported, falls back to UTF-8.\n *\n * @param content The content to decode (Buffer or string)\n * @param charset The source encoding (e.g., 'utf-8', 'iso-8859-1', 'utf-16le', etc.)\n * @returns The decoded string\n */\nexport function convertToString(content: string | Buffer, charset?: string): string {\n if (typeof content === \"string\") return content;\n\n const normalizedCharset = charset ? normalizeCharset(charset) : \"utf-8\";\n\n try {\n return iconv.decode(content, normalizedCharset);\n } catch {\n // Fallback to utf-8 if decoding fails\n try {\n return iconv.decode(content, \"utf-8\");\n } catch {\n // Last resort: decode as latin1 which can handle any byte sequence\n return iconv.decode(content, \"latin1\");\n }\n }\n}\n","import { GreedySplitter } from \"../../splitter/GreedySplitter\";\nimport { SemanticMarkdownSplitter } from \"../../splitter/SemanticMarkdownSplitter\";\nimport type { AppConfig } from \"../../utils/config\";\nimport { logger } from \"../../utils/logger\";\nimport { MimeTypeUtils } from \"../../utils/mimeTypeUtils\";\nimport type { ManagedBrowser } from \"../fetcher/ManagedBrowser\";\nimport type { ContentFetcher, RawContent } from \"../fetcher/types\";\nimport { HtmlCheerioParserMiddleware } from \"../middleware/HtmlCheerioParserMiddleware\";\nimport { HtmlLinkExtractorMiddleware } from \"../middleware/HtmlLinkExtractorMiddleware\";\nimport { HtmlMetadataExtractorMiddleware } from \"../middleware/HtmlMetadataExtractorMiddleware\";\nimport { HtmlNormalizationMiddleware } from \"../middleware/HtmlNormalizationMiddleware\";\nimport { HtmlPlaywrightMiddleware } from \"../middleware/HtmlPlaywrightMiddleware\";\nimport { HtmlSanitizerMiddleware } from \"../middleware/HtmlSanitizerMiddleware\";\nimport { HtmlToMarkdownMiddleware } from \"../middleware/HtmlToMarkdownMiddleware\";\nimport type { ContentProcessorMiddleware, MiddlewareContext } from \"../middleware/types\";\nimport type { ScraperOptions } from \"../types\";\nimport { convertToString } from \"../utils/buffer\";\nimport { resolveCharset } from \"../utils/charset\";\nimport { BasePipeline } from \"./BasePipeline\";\nimport type { PipelineResult } from \"./types\";\n\n/**\n * HtmlPipeline - Processes HTML content into Markdown chunks.\n * Uses Playwright for rendering if needed and Cheerio for semantic extraction.\n */\nexport class HtmlPipeline extends BasePipeline {\n private readonly playwrightMiddleware: HtmlPlaywrightMiddleware;\n private readonly standardMiddleware: ContentProcessorMiddleware[];\n private readonly greedySplitter: GreedySplitter;\n\n /**\n * @param config - Application configuration.\n * @param managedBrowser - The browser to render with; pass one to share it\n * with the browser fetcher.\n */\n constructor(config: AppConfig, managedBrowser?: ManagedBrowser) {\n super();\n\n const preferredChunkSize = config.splitter.preferredChunkSize;\n const maxChunkSize = config.splitter.maxChunkSize;\n const minChunkSize = config.splitter.minChunkSize;\n\n this.playwrightMiddleware = new HtmlPlaywrightMiddleware(\n config.scraper,\n managedBrowser,\n );\n // Pick the extractor. When the default (`cheerio`) is selected we never\n // touch the Defuddle module — its `defuddle` + `linkedom` dependencies\n // (~2.4 MB combined) stay off the import graph entirely. The Defuddle\n // path lazy-imports on first page, so the cost is paid once when the\n // flag is enabled and never otherwise.\n const extractor: ContentProcessorMiddleware =\n config.scraper.htmlExtractor === \"defuddle\"\n ? createLazyDefuddleMiddleware()\n : new HtmlSanitizerMiddleware();\n logger.debug(`HtmlPipeline using extractor: ${config.scraper.htmlExtractor}`);\n this.standardMiddleware = [\n new HtmlCheerioParserMiddleware(),\n new HtmlMetadataExtractorMiddleware(),\n new HtmlLinkExtractorMiddleware(),\n extractor,\n new HtmlNormalizationMiddleware(),\n new HtmlToMarkdownMiddleware(),\n ];\n\n // Create the two-phase splitting: semantic + size optimization\n const semanticSplitter = new SemanticMarkdownSplitter(\n preferredChunkSize,\n maxChunkSize,\n );\n this.greedySplitter = new GreedySplitter(\n semanticSplitter,\n minChunkSize,\n preferredChunkSize,\n maxChunkSize,\n );\n }\n\n canProcess(mimeType: string): boolean {\n return MimeTypeUtils.isHtml(mimeType);\n }\n\n async process(\n rawContent: RawContent,\n options: ScraperOptions,\n fetcher?: ContentFetcher,\n ): Promise<PipelineResult> {\n // Use enhanced charset detection that considers HTML meta tags\n const resolvedCharset = resolveCharset(\n rawContent.charset,\n rawContent.content,\n rawContent.mimeType,\n );\n const contentString = convertToString(rawContent.content, resolvedCharset);\n\n const context: MiddlewareContext = {\n content: contentString,\n contentType: rawContent.mimeType || \"text/html\",\n source: rawContent.source,\n // metadata: {},\n links: [],\n errors: [],\n options,\n fetcher,\n };\n\n // Build middleware stack dynamically based on scrapeMode\n let middleware: ContentProcessorMiddleware[] = [...this.standardMiddleware];\n if (options.scrapeMode === \"playwright\" || options.scrapeMode === \"auto\") {\n middleware = [this.playwrightMiddleware, ...middleware];\n }\n\n // Execute the middleware stack using the base class method\n await this.executeMiddlewareStack(middleware, context);\n\n // Split the content using SemanticMarkdownSplitter (HTML is converted to markdown by middleware)\n const chunks = await this.greedySplitter.splitText(\n typeof context.content === \"string\" ? context.content : \"\",\n );\n\n return {\n title: context.title,\n contentType: context.contentType,\n textContent: context.content,\n links: context.links,\n errors: context.errors,\n chunks,\n };\n }\n\n /**\n * Cleanup resources used by this pipeline, specifically the Playwright browser instance.\n * Errors during cleanup are logged but not propagated to ensure graceful shutdown.\n */\n public async close(): Promise<void> {\n await super.close(); // Call base class close (no-op by default)\n try {\n await this.playwrightMiddleware.closeBrowser();\n } catch (error) {\n // Log error but don't throw - cleanup should be best-effort\n // The closeBrowser method already handles errors internally, but\n // this provides an additional safety layer for unexpected failures\n logger.warn(`⚠️ Error during browser cleanup: ${error}`);\n }\n }\n}\n\n/**\n * Build a middleware wrapper that defers loading `HtmlDefuddleMiddleware`\n * (and transitively `defuddle/node` + `linkedom`) until the first HTML page\n * is processed with the `defuddle` extractor selected. Keeps the default\n * `cheerio` path free of the extra dependency cost.\n */\nfunction createLazyDefuddleMiddleware(): ContentProcessorMiddleware {\n let real: ContentProcessorMiddleware | null = null;\n return {\n async process(context, next) {\n if (!real) {\n const mod = await import(\"../middleware/HtmlDefuddleMiddleware\");\n real = new mod.HtmlDefuddleMiddleware();\n }\n await real.process(context, next);\n },\n };\n}\n","/**\n * TextDocumentSplitter - Simple text-based document splitter\n *\n * This splitter provides basic text splitting functionality for plain text files.\n * It uses the TextContentSplitter for hierarchical text splitting with no semantic organization.\n * This is a fallback splitter for any text document that cannot be handled by HTML, Markdown,\n * or Source Code document splitters.\n */\n\nimport { MinimumChunkSizeError } from \"./errors\";\nimport { TextContentSplitter } from \"./splitters/TextContentSplitter\";\nimport type { Chunk, DocumentSplitter, SplitterConfig } from \"./types\";\n\n/**\n * Simple document splitter for plain text files.\n * Uses TextContentSplitter for hierarchical text splitting with no semantic organization.\n * This is a fallback splitter for any text document that cannot be handled by HTML,\n * Markdown, or Source Code document splitters.\n */\nexport class TextDocumentSplitter implements DocumentSplitter {\n private config: SplitterConfig;\n private textSplitter: TextContentSplitter;\n\n constructor(config: SplitterConfig) {\n this.config = config;\n\n this.textSplitter = new TextContentSplitter({\n chunkSize: this.config.maxChunkSize,\n });\n }\n\n async splitText(content: string): Promise<Chunk[]> {\n if (!content.trim()) {\n return [];\n }\n\n try {\n // Split the text content into chunks\n const chunks = await this.textSplitter.split(content);\n\n // Convert string chunks to ContentChunk objects\n return chunks.map((chunk) => ({\n types: [\"text\"] as const,\n content: chunk,\n section: {\n level: 0,\n path: [],\n },\n }));\n } catch (error) {\n // If splitting fails due to minimum chunk size error (e.g., a very long word/token),\n // forcefully split the content by character count to ensure we never return chunks\n // that exceed the maximum size. This is a last resort to handle unsplittable content\n // like very long strings without spaces or newlines.\n\n // For MinimumChunkSizeError or other text splitting errors, forcefully split by character count\n if (!(error instanceof MinimumChunkSizeError) && error instanceof Error) {\n // Log unexpected errors but still proceed with forceful splitting to avoid data loss\n console.warn(\n `Unexpected text splitting error: ${error.message}. Forcing character-based split.`,\n );\n }\n\n const chunks: Chunk[] = [];\n let offset = 0;\n while (offset < content.length) {\n const chunkContent = content.substring(offset, offset + this.config.maxChunkSize);\n chunks.push({\n types: [\"text\"] as const,\n content: chunkContent,\n section: {\n level: 0,\n path: [],\n },\n });\n offset += this.config.maxChunkSize;\n }\n return chunks;\n }\n }\n}\n","/**\n * JsonDocumentSplitter - Concatenation-friendly JSON document splitting.\n *\n * Creates minimal, concatenable chunks that form valid JSON when combined.\n * Each chunk is a building block: opening braces, individual properties with proper commas,\n * nested structures, and closing braces. Designed to work with GreedySplitter for optimization.\n *\n * Algorithm:\n * 1. Create opening structure chunks (braces/brackets)\n * 2. Create individual property/element chunks with proper punctuation\n * 3. Process nested structures recursively up to maxDepth\n * 4. Maintain proper indentation and hierarchical paths\n * 5. Let GreedySplitter handle size optimization\n * 6. Fall back to text-based chunking if maxChunks limit is exceeded or maxDepth is reached\n */\n\nimport { defaults } from \"../utils/config\";\nimport { TextDocumentSplitter } from \"./TextDocumentSplitter\";\nimport type { Chunk, DocumentSplitter, SplitterConfig } from \"./types\";\n\ntype JsonValue =\n | string\n | number\n | boolean\n | null\n | JsonValue[]\n | { [key: string]: JsonValue };\n\n/**\n * Options for the JsonDocumentSplitter\n */\nexport interface JsonDocumentSplitterOptions {\n /**\n * Maximum depth to traverse in the JSON object.\n * Defaults to a reasonable limit to prevent stack overflow.\n */\n maxDepth?: number;\n\n /**\n * Maximum number of chunks to generate.\n * If exceeded, falls back to text splitting.\n */\n maxChunks?: number;\n\n preserveFormatting?: boolean;\n\n /** Maximum size for individual chunks */\n maxChunkSize?: number;\n}\n\n/**\n * JsonDocumentSplitter handles splitting of JSON content.\n * It attempts to preserve the structure of the JSON object while splitting it into chunks.\n */\nexport class JsonDocumentSplitter implements DocumentSplitter {\n private preserveFormatting: boolean;\n private maxDepth: number;\n private maxChunks: number;\n private maxChunkSize: number;\n private textFallbackSplitter: TextDocumentSplitter;\n\n constructor(config: SplitterConfig, options: JsonDocumentSplitterOptions = {}) {\n this.preserveFormatting = options.preserveFormatting ?? true;\n this.maxDepth =\n options.maxDepth ??\n config.json?.maxNestingDepth ??\n options.maxDepth ??\n config.json?.maxNestingDepth ??\n defaults.splitter.json.maxNestingDepth;\n this.maxChunks =\n options.maxChunks ?? config.json?.maxChunks ?? defaults.splitter.json.maxChunks;\n this.maxChunkSize = options.maxChunkSize ?? config.maxChunkSize;\n\n const textSplitterConfig = { ...config };\n if (options.maxChunkSize) {\n textSplitterConfig.maxChunkSize = options.maxChunkSize;\n }\n this.textFallbackSplitter = new TextDocumentSplitter(textSplitterConfig);\n }\n\n async splitText(content: string, _contentType?: string): Promise<Chunk[]> {\n try {\n const parsed: JsonValue = JSON.parse(content);\n const chunks: Chunk[] = [];\n\n // Process the JSON structure recursively, starting with root path\n await this.processValue(parsed, [\"root\"], 1, 0, chunks, true);\n\n // Check if we exceeded the maximum number of chunks\n if (chunks.length > this.maxChunks) {\n // Fall back to text-based chunking\n return this.textFallbackSplitter.splitText(content);\n }\n\n return chunks;\n } catch {\n // If JSON parsing fails, create a single chunk with the raw content\n return [\n {\n types: [\"code\"],\n content: content.trim(),\n section: {\n level: 1,\n path: [\"invalid-json\"],\n },\n },\n ];\n }\n }\n\n private async processValue(\n value: JsonValue,\n path: string[],\n level: number,\n indentLevel: number,\n chunks: Chunk[],\n isLastItem: boolean,\n ): Promise<void> {\n // Check if we've exceeded the maximum depth\n if (level > this.maxDepth) {\n // Switch to simple text-based representation for deep nesting\n await this.processValueAsText(value, path, level, indentLevel, chunks, isLastItem);\n return;\n }\n\n if (Array.isArray(value)) {\n await this.processArray(value, path, level, indentLevel, chunks, isLastItem);\n } else if (value !== null && typeof value === \"object\") {\n await this.processObject(value, path, level, indentLevel, chunks, isLastItem);\n } else {\n await this.processPrimitive(value, path, level, indentLevel, chunks, isLastItem);\n }\n }\n\n private async processArray(\n array: JsonValue[],\n path: string[],\n level: number,\n indentLevel: number,\n chunks: Chunk[],\n isLastItem: boolean,\n ): Promise<void> {\n const indent = this.getIndent(indentLevel);\n const comma = isLastItem ? \"\" : \",\";\n\n // Opening bracket chunk\n chunks.push({\n types: [\"code\"],\n content: `${indent}[`,\n section: { level, path: [...path] },\n });\n\n // Process each array element\n for (let index = 0; index < array.length; index++) {\n const item = array[index];\n const isLast = index === array.length - 1;\n const itemPath = [...path, `[${index}]`];\n await this.processValue(item, itemPath, level + 1, indentLevel + 1, chunks, isLast);\n }\n\n // Closing bracket chunk\n chunks.push({\n types: [\"code\"],\n content: `${indent}]${comma}`,\n section: { level, path: [...path] },\n });\n }\n\n private async processObject(\n obj: Record<string, JsonValue>,\n path: string[],\n level: number,\n indentLevel: number,\n chunks: Chunk[],\n isLastItem: boolean,\n ): Promise<void> {\n const indent = this.getIndent(indentLevel);\n const comma = isLastItem ? \"\" : \",\";\n const entries = Object.entries(obj);\n\n // Opening brace chunk\n chunks.push({\n types: [\"code\"],\n content: `${indent}{`,\n section: { level, path: [...path] },\n });\n\n // Process each property\n for (let index = 0; index < entries.length; index++) {\n const [key, value] = entries[index];\n const isLast = index === entries.length - 1;\n const propertyPath = [...path, key];\n await this.processProperty(\n key,\n value,\n propertyPath,\n level + 1,\n indentLevel + 1,\n chunks,\n isLast,\n );\n }\n\n // Closing brace chunk\n chunks.push({\n types: [\"code\"],\n content: `${indent}}${comma}`,\n section: { level, path: [...path] },\n });\n }\n\n private async processProperty(\n key: string,\n value: JsonValue,\n path: string[],\n level: number,\n indentLevel: number,\n chunks: Chunk[],\n isLastProperty: boolean,\n ): Promise<void> {\n const indent = this.getIndent(indentLevel);\n\n if (typeof value === \"object\" && value !== null) {\n // For complex values (objects/arrays), create a property opening chunk\n chunks.push({\n types: [\"code\"],\n content: `${indent}\"${key}\": `,\n section: { level, path },\n });\n\n // Process the complex value (it handles its own comma)\n await this.processValue(value, path, level, indentLevel, chunks, isLastProperty);\n } else {\n // For primitive values, create a complete property chunk and ensure it respects max chunk size\n const comma = isLastProperty ? \"\" : \",\";\n const formattedValue = JSON.stringify(value);\n const fullContent = `${indent}\"${key}\": ${formattedValue}${comma}`;\n\n if (fullContent.length > this.maxChunkSize) {\n // Use text splitter for oversized primitive values while keeping property context\n const textChunks = await this.textFallbackSplitter.splitText(formattedValue);\n\n // Emit property prefix once, then split value across chunks\n chunks.push({\n types: [\"code\"],\n content: `${indent}\"${key}\": `,\n section: { level, path },\n });\n\n textChunks.forEach((textChunk, index) => {\n const isLastChunk = index === textChunks.length - 1;\n const content = `${textChunk.content}${isLastChunk ? comma : \"\"}`;\n chunks.push({\n types: [\"code\"],\n content,\n section: { level, path },\n });\n });\n } else {\n chunks.push({\n types: [\"code\"],\n content: fullContent,\n section: { level, path },\n });\n }\n }\n }\n\n private async processPrimitive(\n value: JsonValue,\n path: string[],\n level: number,\n indentLevel: number,\n chunks: Chunk[],\n isLastItem: boolean,\n ): Promise<void> {\n const indent = this.getIndent(indentLevel);\n const comma = isLastItem ? \"\" : \",\";\n const formattedValue = JSON.stringify(value);\n\n const fullContent = `${indent}${formattedValue}${comma}`;\n\n if (fullContent.length > this.maxChunkSize) {\n // Use text splitter for oversized primitive values in arrays\n const textChunks = await this.textFallbackSplitter.splitText(formattedValue);\n\n textChunks.forEach((textChunk, index) => {\n const isFirstChunk = index === 0;\n const isLastChunk = index === textChunks.length - 1;\n const valueContent = isFirstChunk\n ? `${indent}${textChunk.content}`\n : textChunk.content;\n const content = `${valueContent}${isLastChunk ? comma : \"\"}`;\n chunks.push({\n types: [\"code\"],\n content,\n section: { level, path: [...path] },\n });\n });\n } else {\n chunks.push({\n types: [\"code\"],\n content: fullContent,\n section: { level, path },\n });\n }\n }\n\n private getIndent(level: number): string {\n return this.preserveFormatting ? \" \".repeat(level) : \"\";\n }\n\n /**\n * Process a value that has exceeded the maximum depth limit by serializing it as text.\n * This prevents excessive chunking of deeply nested structures.\n * If the serialized value is too large, splits it using the text fallback splitter.\n */\n private async processValueAsText(\n value: JsonValue,\n path: string[],\n level: number,\n indentLevel: number,\n chunks: Chunk[],\n isLastItem: boolean,\n ): Promise<void> {\n const indent = this.getIndent(indentLevel);\n const comma = isLastItem ? \"\" : \",\";\n\n // Serialize the entire value\n let serialized: string;\n if (this.preserveFormatting) {\n // Use a more efficient approach for indented serialization\n const lines = JSON.stringify(value, null, 2).split(\"\\n\");\n serialized = lines\n .map((line, idx) => (idx === 0 ? line : `${indent}${line}`))\n .join(\"\\n\");\n } else {\n serialized = JSON.stringify(value);\n }\n\n const fullContent = `${indent}${serialized}${comma}`;\n\n // Check if the FINAL formatted content (with indent and comma) exceeds the limit.\n // If so, we split just the serialized content (without structural formatting) because\n // the resulting chunks are treated as searchable text blocks, not structural JSON elements.\n if (fullContent.length > this.maxChunkSize) {\n // Use text splitter to break down the large serialized JSON\n // Note: When content is this large, we prioritize searchability over perfect JSON structure.\n // The chunks contain the actual data that users can search, with proper metadata (level, path)\n // to indicate where in the JSON structure this content originated from.\n const textChunks = await this.textFallbackSplitter.splitText(serialized);\n\n // Add each text chunk with the current path information\n for (const textChunk of textChunks) {\n chunks.push({\n types: [\"code\"],\n content: textChunk.content,\n section: { level, path: [...path] },\n });\n }\n } else {\n // Content is small enough, add as single chunk\n chunks.push({\n types: [\"code\"],\n content: fullContent,\n section: { level, path: [...path] },\n });\n }\n }\n}\n","import { JsonDocumentSplitter } from \"../../splitter/JsonDocumentSplitter\";\nimport type { DocumentSplitter } from \"../../splitter/types\";\nimport type { AppConfig } from \"../../utils/config\";\nimport { MimeTypeUtils } from \"../../utils/mimeTypeUtils\";\nimport type { ContentFetcher, RawContent } from \"../fetcher/types\";\nimport type { ContentProcessorMiddleware, MiddlewareContext } from \"../middleware/types\";\nimport type { ScraperOptions } from \"../types\";\nimport { convertToString } from \"../utils/buffer\";\nimport { BasePipeline } from \"./BasePipeline\";\nimport type { PipelineResult } from \"./types\";\n\n/**\n * Pipeline for processing JSON content with semantic, hierarchical splitting.\n * Uses JsonDocumentSplitter to produce structurally faithful chunks (preserving {level, path})\n * without greedy size-based merging. Greedy merging is intentionally omitted to avoid collapsing\n * distinct structural nodes that are required for precise hierarchical reassembly.\n */\nexport class JsonPipeline extends BasePipeline {\n private readonly middleware: ContentProcessorMiddleware[];\n private readonly splitter: DocumentSplitter;\n\n constructor(config: AppConfig) {\n super();\n this.middleware = [];\n // Structure-preserving splitter only (no greedy size merging)\n this.splitter = new JsonDocumentSplitter(config.splitter, {\n preserveFormatting: true,\n });\n }\n\n canProcess(mimeType: string): boolean {\n if (!mimeType) return false;\n return MimeTypeUtils.isJson(mimeType);\n }\n\n async process(\n rawContent: RawContent,\n options: ScraperOptions,\n fetcher?: ContentFetcher,\n ): Promise<PipelineResult> {\n const contentString = convertToString(rawContent.content, rawContent.charset);\n\n // Validate JSON structure\n let parsedJson: unknown;\n let isValidJson = true;\n try {\n parsedJson = JSON.parse(contentString);\n } catch (_error) {\n isValidJson = false;\n }\n\n // For invalid JSON, return as-is for fallback text processing\n if (!isValidJson) {\n // Still split invalid JSON content for consistency\n const fallbackChunks = await this.splitter.splitText(contentString);\n return {\n textContent: contentString,\n // metadata: {\n // isValidJson: false,\n // },\n links: [],\n errors: [],\n chunks: fallbackChunks,\n };\n }\n\n const metadata = this.extractMetadata(parsedJson);\n const context: MiddlewareContext = {\n content: contentString,\n source: rawContent.source,\n title: metadata.title,\n contentType: rawContent.mimeType || \"application/json\",\n // metadata: {\n // ...this.extractMetadata(parsedJson),\n // isValidJson,\n // jsonStructure: this.analyzeJsonStructure(parsedJson),\n // },\n links: [], // JSON files typically don't contain links\n errors: [],\n options,\n fetcher,\n };\n\n // Execute the middleware stack (minimal for JSON)\n await this.executeMiddlewareStack(this.middleware, context);\n\n // Split the content using JsonContentSplitter\n const chunks = await this.splitter.splitText(context.content);\n\n return {\n title: context.title,\n contentType: context.contentType,\n textContent: context.content,\n links: context.links,\n errors: context.errors,\n chunks,\n };\n }\n\n /**\n * Extracts metadata from JSON content only when meaningful values exist\n */\n private extractMetadata(parsedJson: unknown): { title?: string; description?: string } {\n const metadata: { title?: string; description?: string } = {};\n\n if (typeof parsedJson === \"object\" && parsedJson !== null) {\n const obj = parsedJson as Record<string, unknown>;\n\n // Look for common title fields - only use if they exist and are strings\n const titleFields = [\"title\", \"name\", \"displayName\", \"label\"];\n for (const field of titleFields) {\n if (field in obj && typeof obj[field] === \"string\" && obj[field]) {\n metadata.title = obj[field] as string;\n break;\n }\n }\n\n // Look for common description fields - only use if they exist and are strings\n const descFields = [\"description\", \"summary\", \"about\", \"info\"];\n for (const field of descFields) {\n if (field in obj && typeof obj[field] === \"string\" && obj[field]) {\n metadata.description = obj[field] as string;\n break;\n }\n }\n }\n\n return metadata;\n }\n\n /**\n * Calculates the maximum nesting depth of a JSON structure\n */\n private calculateDepth(obj: unknown, currentDepth = 1): number {\n if (Array.isArray(obj)) {\n let maxDepth = currentDepth;\n for (const item of obj) {\n if (typeof item === \"object\" && item !== null) {\n maxDepth = Math.max(maxDepth, this.calculateDepth(item, currentDepth + 1));\n }\n }\n return maxDepth;\n } else if (typeof obj === \"object\" && obj !== null) {\n let maxDepth = currentDepth;\n for (const value of Object.values(obj)) {\n if (typeof value === \"object\" && value !== null) {\n maxDepth = Math.max(maxDepth, this.calculateDepth(value, currentDepth + 1));\n }\n }\n return maxDepth;\n }\n\n return currentDepth;\n }\n}\n","import type { ContentProcessorMiddleware, MiddlewareContext } from \"./types\";\n\nconst inlineLinkPattern =\n /(^|[^!\\\\])\\[[^\\]\\n]+\\]\\(([^)\\s]+)(?:\\s+\"[^\"]*\"|\\s+'[^']*'|\\s+\\([^)]*\\))?\\)/g;\nconst referenceLinkPattern = /(^|[^!\\\\])\\[[^\\]\\n]+\\]\\[([^\\]\\n]+)\\]/g;\nconst referenceDefinitionPattern = /^\\s{0,3}\\[([^\\]\\n]+)\\]:\\s*(\\S+)(?:\\s+.*)?$/gm;\n\n/**\n * Extracts crawl links from Markdown content.\n */\nexport class MarkdownLinkExtractorMiddleware implements ContentProcessorMiddleware {\n /**\n * Processes the context and appends Markdown link targets to context.links.\n * @param context The current processing context.\n * @param next Function to call the next middleware.\n */\n async process(context: MiddlewareContext, next: () => Promise<void>): Promise<void> {\n if (!Array.isArray(context.links)) {\n context.links = [];\n }\n\n for (const link of extractMarkdownLinks(context.content)) {\n if (!context.links.includes(link)) {\n context.links.push(link);\n }\n }\n\n await next();\n }\n}\n\nfunction extractMarkdownLinks(content: string): string[] {\n const links: string[] = [];\n const referenceDefinitions = new Map<string, string>();\n\n for (const match of content.matchAll(referenceDefinitionPattern)) {\n const label = normalizeReferenceLabel(match[1]);\n const target = cleanReferenceTarget(match[2]);\n if (label && target && !referenceDefinitions.has(label)) {\n referenceDefinitions.set(label, target);\n }\n }\n\n for (const match of content.matchAll(inlineLinkPattern)) {\n addUniqueLink(links, match[2]);\n }\n\n for (const match of content.matchAll(referenceLinkPattern)) {\n const target = referenceDefinitions.get(normalizeReferenceLabel(match[2]));\n if (target) {\n addUniqueLink(links, target);\n }\n }\n\n return links;\n}\n\nfunction addUniqueLink(links: string[], target: string | undefined): void {\n if (!target || links.includes(target)) {\n return;\n }\n links.push(target);\n}\n\nfunction normalizeReferenceLabel(label: string | undefined): string {\n return label?.trim().replace(/\\s+/g, \" \").toLowerCase() ?? \"\";\n}\n\nfunction cleanReferenceTarget(target: string | undefined): string {\n if (!target) {\n return \"\";\n }\n return target.trim().replace(/^<(.+)>$/, \"$1\");\n}\n","import matter from \"gray-matter\";\nimport { logger } from \"../../utils/logger\";\nimport type { ContentProcessorMiddleware, MiddlewareContext } from \"./types\";\n\n/**\n * Middleware to extract the title from Markdown content.\n * Prioritizes YAML frontmatter 'title' field, falls back to first H1 heading.\n */\nexport class MarkdownMetadataExtractorMiddleware implements ContentProcessorMiddleware {\n /**\n * Processes the context to extract the title from Markdown.\n * @param context The current processing context.\n * @param next Function to call the next middleware.\n */\n async process(context: MiddlewareContext, next: () => Promise<void>): Promise<void> {\n try {\n let title = \"Untitled\";\n let frontmatterTitle: string | undefined;\n\n // 1. Try to extract title from YAML frontmatter\n try {\n const file = matter(context.content);\n if (file.data && file.data.title !== undefined && file.data.title !== null) {\n // Convert to string to handle numeric titles (e.g. title: 2024)\n frontmatterTitle = String(file.data.title).trim();\n }\n } catch (err) {\n // Log warning but continue - don't crash the pipeline for bad frontmatter\n logger.warn(\n `Failed to parse markdown frontmatter: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n\n if (frontmatterTitle && frontmatterTitle.length > 0) {\n title = frontmatterTitle;\n } else {\n // 2. Fallback: Extract first H1 heading\n const match = context.content.match(/^#\\s+(.*)$/m);\n if (match?.[1]) {\n title = match[1].trim();\n }\n }\n\n context.title = title;\n } catch (error) {\n context.errors.push(\n new Error(\n `Failed to extract metadata from Markdown: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n }\n\n await next();\n }\n}\n","import { GreedySplitter } from \"../../splitter/GreedySplitter\";\nimport { SemanticMarkdownSplitter } from \"../../splitter/SemanticMarkdownSplitter\";\nimport type { AppConfig } from \"../../utils/config\";\nimport { MimeTypeUtils } from \"../../utils/mimeTypeUtils\";\nimport type { ContentFetcher, RawContent } from \"../fetcher/types\";\nimport { MarkdownLinkExtractorMiddleware } from \"../middleware/MarkdownLinkExtractorMiddleware\";\nimport { MarkdownMetadataExtractorMiddleware } from \"../middleware/MarkdownMetadataExtractorMiddleware\";\nimport type { ContentProcessorMiddleware, MiddlewareContext } from \"../middleware/types\";\nimport type { ScraperOptions } from \"../types\";\nimport { convertToString } from \"../utils/buffer\";\nimport { BasePipeline } from \"./BasePipeline\";\nimport type { PipelineResult } from \"./types\";\n\n/**\n * MarkdownPipeline - Processes Markdown content using middleware and semantic splitting.\n */\nexport class MarkdownPipeline extends BasePipeline {\n private readonly middleware: ContentProcessorMiddleware[];\n private readonly greedySplitter: GreedySplitter;\n\n constructor(config: AppConfig) {\n super();\n\n const preferredChunkSize = config.splitter.preferredChunkSize;\n const maxChunkSize = config.splitter.maxChunkSize;\n const minChunkSize = config.splitter.minChunkSize;\n\n this.middleware = [\n new MarkdownMetadataExtractorMiddleware(),\n new MarkdownLinkExtractorMiddleware(),\n ];\n\n // Create the two-phase splitting: semantic + size optimization\n const semanticSplitter = new SemanticMarkdownSplitter(\n preferredChunkSize,\n maxChunkSize,\n );\n this.greedySplitter = new GreedySplitter(\n semanticSplitter,\n minChunkSize,\n preferredChunkSize,\n maxChunkSize,\n );\n }\n\n canProcess(mimeType: string): boolean {\n if (!mimeType) return false;\n return MimeTypeUtils.isMarkdown(mimeType);\n }\n\n async process(\n rawContent: RawContent,\n options: ScraperOptions,\n fetcher?: ContentFetcher,\n ): Promise<PipelineResult> {\n const contentString = convertToString(rawContent.content, rawContent.charset);\n\n const context: MiddlewareContext = {\n contentType: rawContent.mimeType || \"text/markdown\",\n content: contentString,\n source: rawContent.source,\n links: [],\n errors: [],\n options,\n fetcher,\n };\n\n // Execute the middleware stack using the base class method\n await this.executeMiddlewareStack(this.middleware, context);\n\n // Split the content using SemanticMarkdownSplitter\n const chunks = await this.greedySplitter.splitText(\n typeof context.content === \"string\" ? context.content : \"\",\n rawContent.mimeType,\n );\n\n return {\n title: context.title,\n contentType: context.contentType,\n textContent: typeof context.content === \"string\" ? context.content : \"\",\n links: context.links,\n errors: context.errors,\n chunks,\n };\n }\n}\n","/**\n * Python parser for tree-sitter based source code splitting.\n *\n * Goals:\n * - Semantic parsing of Python source code (.py files)\n * - Direct boundary extraction aligned with canonical ruleset\n * - Handle Python-specific docstrings (inside function/class bodies)\n * - Support for functions, classes, methods, and nested structures\n */\n\nimport Parser, { type SyntaxNode, type Tree } from \"tree-sitter\";\nimport Python from \"tree-sitter-python\";\nimport { defaults } from \"../../../utils/config\";\nimport type { CodeBoundary, LanguageParser, ParseResult } from \"./types\";\n\n/**\n * Sets of node types we care about for Python.\n */\nconst STRUCTURAL_DECL_TYPES = new Set([\n \"class_definition\",\n \"import_statement\",\n \"import_from_statement\",\n]);\n\n// Executable / content declarations we also emit\nconst CONTENT_DECL_TYPES = new Set([\"function_definition\", \"async_function_definition\"]);\n\n/**\n * Decide if node type is boundary-worthy (before suppression rules).\n */\nfunction isCandidateBoundary(node: SyntaxNode): boolean {\n return STRUCTURAL_DECL_TYPES.has(node.type) || CONTENT_DECL_TYPES.has(node.type);\n}\n\n/**\n * Determine if a function-like node is a local helper (nested inside another function body),\n * in which case we suppress emission (canonical ruleset).\n */\nfunction isLocalHelper(node: SyntaxNode): boolean {\n const functionLike = new Set([\"function_definition\", \"async_function_definition\"]);\n\n let ancestor = node.parent;\n while (ancestor) {\n if (functionLike.has(ancestor.type)) {\n // Current node is nested inside a function body -> local helper\n return true;\n }\n // Stop climbing at structural containers where function declarations are allowed as direct members\n if (ancestor.type === \"class_definition\" || ancestor.type === \"module\") {\n break;\n }\n ancestor = ancestor.parent;\n }\n return false;\n}\n\n/**\n * Extract Python docstring from function or class body.\n * Python docstrings are string literals as the first statement in the body.\n */\nfunction findDocumentationStart(\n node: SyntaxNode,\n source: string,\n): { startLine: number; startByte: number } {\n let startByte = node.startIndex;\n let startLine = node.startPosition.row + 1;\n\n // For Python, look for docstring inside the function/class body\n if (\n node.type === \"function_definition\" ||\n node.type === \"async_function_definition\" ||\n node.type === \"class_definition\"\n ) {\n // Find the body (block) of the function/class\n const body = node.childForFieldName(\"body\");\n if (body && body.type === \"block\") {\n const firstChild = body.children.find((child) => child.type !== \"newline\");\n\n // Check if first statement is a string (docstring)\n if (firstChild && firstChild.type === \"expression_statement\") {\n const expr = firstChild.childForFieldName(\"value\") || firstChild.children[0];\n if (expr && expr.type === \"string\") {\n // We keep the function/class signature as the start, but we'll include\n // the docstring in the content by not adjusting the boundaries here.\n // The docstring will be naturally included in the function body.\n }\n }\n }\n }\n\n // Look for preceding comments (Python uses # comments, not JSDoc)\n const parent = node.parent;\n if (!parent) {\n return { startLine, startByte };\n }\n\n const siblings = parent.children;\n const idx = siblings.indexOf(node);\n if (idx === -1) {\n return { startLine, startByte };\n }\n\n // Walk upward collecting contiguous comment block\n let sawComment = false;\n for (let i = idx - 1; i >= 0; i--) {\n const s = siblings[i];\n const text = source.slice(s.startIndex, s.endIndex);\n\n if (s.type === \"comment\") {\n sawComment = true;\n startByte = s.startIndex;\n startLine = s.startPosition.row + 1;\n continue;\n }\n\n if (/^\\s*$/.test(text)) {\n if (sawComment) {\n startByte = s.startIndex;\n startLine = s.startPosition.row + 1;\n }\n continue;\n }\n\n // Hit non-comment code: stop\n break;\n }\n\n return { startLine, startByte };\n}\n\n/**\n * Name extraction for Python nodes.\n */\nfunction extractName(node: SyntaxNode): string {\n switch (node.type) {\n case \"function_definition\":\n case \"async_function_definition\":\n case \"class_definition\": {\n const nameNode = node.childForFieldName(\"name\");\n return nameNode?.text || `<anonymous_${node.type}>`;\n }\n case \"import_statement\": {\n // Extract imported module names\n const names: string[] = [];\n const dotted_names = node.children.filter(\n (c) => c.type === \"dotted_name\" || c.type === \"identifier\",\n );\n for (const name of dotted_names) {\n names.push(name.text);\n }\n return names.length > 0 ? `import ${names.join(\", \")}` : \"import\";\n }\n case \"import_from_statement\": {\n const moduleNode = node.childForFieldName(\"module_name\");\n const moduleName = moduleNode?.text || \"?\";\n return `from ${moduleName}`;\n }\n default:\n return node.type;\n }\n}\n\n/**\n * Boundary classification mapping for Python.\n */\nfunction classifyBoundaryKind(node: SyntaxNode): {\n boundaryType: \"structural\" | \"content\";\n simple: CodeBoundary[\"type\"];\n} {\n if (node.type === \"class_definition\") {\n return { boundaryType: \"structural\", simple: \"class\" };\n }\n if (node.type === \"import_statement\" || node.type === \"import_from_statement\") {\n return { boundaryType: \"structural\", simple: \"module\" };\n }\n if (node.type === \"function_definition\" || node.type === \"async_function_definition\") {\n return { boundaryType: \"content\", simple: \"function\" };\n }\n return { boundaryType: \"content\", simple: \"other\" };\n}\n\nexport class PythonParser implements LanguageParser {\n readonly name = \"python\";\n readonly fileExtensions = [\".py\", \".pyi\", \".pyw\"];\n readonly mimeTypes = [\n \"text/python\",\n \"text/x-python\",\n \"application/python\",\n \"application/x-python\",\n ];\n\n constructor(\n private readonly treeSitterSizeLimit: number = defaults.splitter.treeSitterSizeLimit,\n ) {}\n\n private createParser(): Parser {\n const parser = new Parser();\n parser.setLanguage(Python as unknown);\n return parser;\n }\n\n parse(source: string): ParseResult {\n // Validate input\n if (typeof source !== \"string\") {\n throw new Error(`PythonParser expected string input, got ${typeof source}`);\n }\n\n if (source == null) {\n throw new Error(\"PythonParser received null or undefined source\");\n }\n\n // Handle tree-sitter size limit\n const limit = this.treeSitterSizeLimit;\n if (source.length > limit) {\n // For files exceeding the limit, we truncate at a reasonable boundary and return a limited parse\n // Try to find a good truncation point (end of line)\n let truncatedSource = source.slice(0, limit);\n const lastNewline = truncatedSource.lastIndexOf(\"\\n\");\n if (lastNewline > limit * 0.9) {\n // If we can find a newline in the last 10% of the limit, use that\n truncatedSource = source.slice(0, lastNewline + 1);\n }\n\n try {\n const parser = this.createParser();\n const tree = parser.parse(truncatedSource);\n const errorNodes: SyntaxNode[] = [];\n this.collectErrorNodes(tree.rootNode, errorNodes);\n\n return {\n tree,\n hasErrors: true, // Mark as having errors due to truncation\n errorNodes,\n };\n } catch (error) {\n throw new Error(\n `Failed to parse truncated Python file (${truncatedSource.length} chars): ${(error as Error).message}`,\n );\n }\n }\n\n // Normal parsing for files within the size limit\n try {\n const parser = this.createParser();\n const tree = parser.parse(source);\n const errorNodes: SyntaxNode[] = [];\n this.collectErrorNodes(tree.rootNode, errorNodes);\n\n return {\n tree,\n hasErrors: errorNodes.length > 0,\n errorNodes,\n };\n } catch (error) {\n throw new Error(\n `Failed to parse Python file (${source.length} chars): ${(error as Error).message}`,\n );\n }\n }\n\n private collectErrorNodes(node: SyntaxNode, acc: SyntaxNode[]): void {\n if (node.hasError && node.type === \"ERROR\") {\n acc.push(node);\n }\n for (const c of node.children) {\n this.collectErrorNodes(c, acc);\n }\n }\n\n /**\n * Boundary extraction: produces CodeBoundary[] directly from AST.\n */\n extractBoundaries(tree: Tree, source: string): CodeBoundary[] {\n if (!source.trim()) return [];\n const boundaries: CodeBoundary[] = [];\n\n const walk = (node: SyntaxNode): void => {\n if (isCandidateBoundary(node)) {\n if (this.shouldSkipStructuralNode(node)) {\n for (const c of node.children) walk(c);\n return;\n }\n\n // Local helper suppression\n if (\n (node.type === \"function_definition\" ||\n node.type === \"async_function_definition\") &&\n isLocalHelper(node)\n ) {\n // Do not emit boundary for local helper\n for (const c of node.children) walk(c);\n return;\n }\n\n const name = extractName(node);\n const docInfo = findDocumentationStart(node, source);\n const classification = classifyBoundaryKind(node);\n\n boundaries.push({\n type: classification.simple,\n boundaryType: classification.boundaryType,\n name,\n startLine: docInfo.startLine,\n endLine: node.endPosition.row + 1,\n startByte: docInfo.startByte,\n endByte: node.endIndex,\n });\n\n // Traverse children (we allow nested boundaries where rules permit)\n for (const c of node.children) walk(c);\n return;\n }\n\n for (const c of node.children) walk(c);\n };\n\n walk(tree.rootNode);\n\n // Deduplicate by start/end/name triple\n const seen = new Set<string>();\n return boundaries.filter((b) => {\n const key = `${b.startByte}:${b.endByte}:${b.name}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n }\n\n /**\n * Determine if a structural node should be skipped in favor of children.\n */\n private shouldSkipStructuralNode(_node: SyntaxNode): boolean {\n // Currently no wrapper types to skip in Python\n return false;\n }\n}\n","/**\n * Simplified standalone TypeScript (and JavaScript) parser.\n *\n * Goals:\n * - Single, unified parser for .ts/.tsx/.js/.jsx (+ mjs/cjs/mts/cts)\n * - Direct boundary extraction aligned with canonical ruleset\n * - Minimal, predictable logic (no complex multi-phase traversals)\n *\n * This replaces the previous inheritance-heavy BaseLanguageParser design.\n */\n\nimport Parser, { type SyntaxNode, type Tree } from \"tree-sitter\";\nimport TypeScript from \"tree-sitter-typescript\";\nimport { defaults } from \"../../../utils/config\";\nimport type { CodeBoundary, LanguageParser, ParseResult } from \"./types\";\n\n/**\n * Helper: language selection (TS vs TSX).\n */\nfunction detectTSX(source: string): boolean {\n // Heuristic: JSX-like tags or React usage\n return /<[A-Za-z][A-Za-z0-9]*\\s|<\\/[A-Za-z]|React\\./.test(source);\n}\n\n/**\n * Sets of node types we care about.\n */\nconst STRUCTURAL_DECL_TYPES = new Set([\n \"class_declaration\",\n \"abstract_class_declaration\",\n \"interface_declaration\",\n \"type_alias_declaration\",\n \"enum_declaration\",\n \"module_declaration\",\n \"namespace_declaration\",\n \"internal_module\",\n \"import_statement\",\n \"export_statement\",\n]);\n\n// Executable / content declarations we also emit\nconst CONTENT_DECL_TYPES = new Set([\n \"function_declaration\",\n \"method_definition\",\n \"method_signature\",\n \"abstract_method_signature\",\n \"constructor\",\n \"arrow_function\",\n // Only emit arrow-function variables via their variable_declarator to avoid duplicates\n \"variable_declarator\",\n]);\n\n/**\n * Decide if node type is boundary-worthy (before suppression rules).\n */\nfunction isCandidateBoundary(node: SyntaxNode): boolean {\n return STRUCTURAL_DECL_TYPES.has(node.type) || CONTENT_DECL_TYPES.has(node.type);\n}\n\n/**\n * Determine if a function-like node is a local helper (nested inside another function/method body),\n * in which case we suppress emission (canonical ruleset).\n */\nfunction isLocalHelper(node: SyntaxNode): boolean {\n const functionLike = new Set([\n \"function_declaration\",\n \"arrow_function\",\n \"method_definition\",\n \"method_signature\",\n \"abstract_method_signature\",\n \"constructor\",\n ]);\n\n let ancestor = node.parent;\n while (ancestor) {\n if (functionLike.has(ancestor.type)) {\n // If ancestor is a class method/constructor and current node is method/constructor,\n // we DO allow emission (method inside class) — only suppress deeper nested function-like inside method bodies.\n if (\n ancestor.type === \"method_definition\" ||\n ancestor.type === \"constructor\" ||\n ancestor.type === \"function_declaration\" ||\n ancestor.type === \"arrow_function\"\n ) {\n // Current node is nested inside a function/method body -> local helper\n return true;\n }\n }\n // Stop climbing at structural containers where function declarations are allowed as direct members\n if (\n ancestor.type === \"class_declaration\" ||\n ancestor.type === \"abstract_class_declaration\" ||\n ancestor.type === \"namespace_declaration\" ||\n ancestor.type === \"module_declaration\" ||\n ancestor.type === \"internal_module\" ||\n ancestor.type === \"interface_declaration\" ||\n ancestor.type === \"enum_declaration\"\n ) {\n break;\n }\n ancestor = ancestor.parent;\n }\n return false;\n}\n\n/**\n * Extract contiguous documentation (comments + blank lines) preceding a node,\n * crossing transparent export wrappers.\n */\nfunction findDocumentationStart(\n node: SyntaxNode,\n source: string,\n): { startLine: number; startByte: number } {\n // If wrapped in export_statement, shift focus to wrapper for doc scan\n let target: SyntaxNode = node;\n if (node.parent && node.parent.type === \"export_statement\") {\n target = node.parent;\n }\n\n // Walk backwards among siblings collecting comments/whitespace.\n const parent = target.parent;\n if (!parent) {\n return {\n startLine: target.startPosition.row + 1,\n startByte: target.startIndex,\n };\n }\n\n const siblings = parent.children;\n const idx = siblings.indexOf(target);\n if (idx === -1) {\n return {\n startLine: target.startPosition.row + 1,\n startByte: target.startIndex,\n };\n }\n\n let startByte = target.startIndex;\n let startLine = target.startPosition.row + 1;\n\n // Walk upward collecting contiguous doc comment block.\n // IMPORTANT: Only expand over whitespace that appears AFTER we've seen at least one comment.\n // This prevents pulling in a blank line above the doc block (tests expect the comment line).\n let sawComment = false;\n for (let i = idx - 1; i >= 0; i--) {\n const s = siblings[i];\n const text = source.slice(s.startIndex, s.endIndex);\n\n if (s.type === \"comment\") {\n sawComment = true;\n startByte = s.startIndex;\n startLine = s.startPosition.row + 1;\n continue;\n }\n\n if (/^\\s*$/.test(text)) {\n if (sawComment) {\n startByte = s.startIndex;\n startLine = s.startPosition.row + 1;\n }\n // If we haven't yet seen a comment, ignore leading blank lines (do not shift start)\n continue;\n }\n // Hit non-comment code: stop.\n break;\n }\n\n // Inline doc on same line as declaration (/** ... */ declaration ...)\n // If we didn't already capture a preceding comment node but the same line\n // contains a JSDoc opening before the declaration start, shift start to that line start.\n const lineStartIdx = source.lastIndexOf(\"\\n\", target.startIndex - 1) + 1;\n if (lineStartIdx >= 0) {\n const prefix = source.slice(lineStartIdx, target.startIndex);\n if (prefix.includes(\"/**\")) {\n startLine = target.startPosition.row + 1;\n startByte = lineStartIdx;\n }\n }\n\n return { startLine, startByte };\n}\n\n/**\n * Name extraction similar to previous implementation but reduced.\n */\nfunction extractName(node: SyntaxNode): string {\n switch (node.type) {\n case \"function_declaration\":\n case \"class_declaration\":\n case \"abstract_class_declaration\":\n case \"interface_declaration\":\n case \"type_alias_declaration\":\n case \"enum_declaration\":\n case \"namespace_declaration\":\n case \"module_declaration\":\n case \"internal_module\": {\n const nameNode = node.childForFieldName(\"name\");\n return nameNode?.text || `<anonymous_${node.type}>`;\n }\n case \"method_definition\":\n case \"method_signature\":\n case \"abstract_method_signature\": {\n const nameNode = node.childForFieldName(\"name\");\n const isStatic = node.children.some((c) => c.type === \"static\");\n const base = nameNode?.text || \"method\";\n return isStatic ? `static ${base}` : base;\n }\n case \"constructor\":\n return \"constructor\";\n case \"arrow_function\": {\n let parent = node.parent;\n while (parent) {\n if (parent.type === \"variable_declarator\") {\n const nameNode = parent.childForFieldName(\"name\");\n return nameNode?.text || \"<anonymous_arrow>\";\n }\n parent = parent.parent;\n }\n return \"<anonymous_arrow>\";\n }\n case \"variable_declaration\":\n case \"lexical_declaration\": {\n // If it declares arrow functions, collect their names\n const declarators = node.children.filter((c) => c.type === \"variable_declarator\");\n const names: string[] = [];\n for (const d of declarators) {\n const value = d.childForFieldName(\"value\");\n if (value?.type === \"arrow_function\") {\n const nameNode = d.childForFieldName(\"name\");\n if (nameNode) names.push(nameNode.text);\n }\n }\n if (names.length > 0) return names.join(\", \");\n return \"<variable_declaration>\";\n }\n case \"variable_declarator\": {\n const nameNode = node.childForFieldName(\"name\");\n return nameNode?.text || \"<variable>\";\n }\n case \"import_statement\":\n case \"export_statement\":\n return node.text.split(\"\\n\")[0].trim();\n default:\n return node.type;\n }\n}\n\n/**\n * Boundary classification mapping.\n */\nfunction classifyBoundaryKind(node: SyntaxNode): {\n boundaryType: \"structural\" | \"content\";\n simple: CodeBoundary[\"type\"];\n} {\n if (node.type === \"class_declaration\" || node.type === \"abstract_class_declaration\") {\n return { boundaryType: \"structural\", simple: \"class\" };\n }\n if (node.type === \"interface_declaration\" || node.type === \"type_alias_declaration\") {\n return { boundaryType: \"structural\", simple: \"interface\" };\n }\n if (node.type === \"enum_declaration\") {\n return { boundaryType: \"structural\", simple: \"enum\" };\n }\n if (\n node.type === \"namespace_declaration\" ||\n node.type === \"module_declaration\" ||\n node.type === \"internal_module\" ||\n node.type === \"export_statement\" ||\n node.type === \"import_statement\"\n ) {\n return { boundaryType: \"structural\", simple: \"module\" };\n }\n if (\n node.type === \"function_declaration\" ||\n node.type === \"method_definition\" ||\n node.type === \"method_signature\" ||\n node.type === \"abstract_method_signature\" ||\n node.type === \"constructor\" ||\n node.type === \"arrow_function\" ||\n node.type === \"variable_declaration\" ||\n node.type === \"lexical_declaration\" ||\n node.type === \"variable_declarator\"\n ) {\n return { boundaryType: \"content\", simple: \"function\" };\n }\n return { boundaryType: \"content\", simple: \"other\" };\n}\n\nexport class TypeScriptParser implements LanguageParser {\n // Unified extensions: TS + JS\n readonly fileExtensions = [\n \".ts\",\n \".tsx\",\n \".mts\",\n \".cts\",\n \".js\",\n \".jsx\",\n \".mjs\",\n \".cjs\",\n ];\n\n readonly mimeTypes = [\n // text/x-* variants (output by MimeTypeUtils.detectMimeTypeFromPath)\n \"text/x-typescript\",\n \"text/x-tsx\",\n \"text/x-jsx\",\n // Standard variants\n \"text/typescript\",\n \"application/typescript\",\n \"text/tsx\",\n \"application/tsx\",\n \"text/javascript\",\n \"application/javascript\",\n \"text/jsx\",\n \"application/jsx\",\n ];\n\n readonly name = \"typescript\";\n\n constructor(\n private readonly treeSitterSizeLimit: number = defaults.splitter.treeSitterSizeLimit,\n ) {}\n\n private createParser(source: string): Parser {\n const p = new Parser();\n const lang = detectTSX(source)\n ? (TypeScript.tsx as unknown)\n : (TypeScript.typescript as unknown);\n p.setLanguage(lang);\n return p;\n }\n\n parse(source: string): ParseResult {\n // Handle tree-sitter size limit\n const limit = this.treeSitterSizeLimit;\n if (source.length > limit) {\n // For files exceeding the limit, we truncate at a reasonable boundary and return a limited parse\n // Try to find a good truncation point (end of line)\n let truncatedSource = source.slice(0, limit);\n const lastNewline = truncatedSource.lastIndexOf(\"\\n\");\n if (lastNewline > limit * 0.9) {\n // If we can find a newline in the last 10% of the limit, use that\n truncatedSource = source.slice(0, lastNewline + 1);\n }\n\n try {\n const parser = this.createParser(truncatedSource);\n const tree = parser.parse(truncatedSource);\n const errorNodes: SyntaxNode[] = [];\n this.collectErrorNodes(tree.rootNode, errorNodes);\n\n return {\n tree,\n hasErrors: true, // Mark as having errors due to truncation\n errorNodes,\n };\n } catch (error) {\n throw new Error(\n `Failed to parse truncated TypeScript file (${truncatedSource.length} chars): ${(error as Error).message}`,\n );\n }\n }\n\n // Normal parsing for files within the size limit\n try {\n const parser = this.createParser(source);\n const tree = parser.parse(source);\n const errorNodes: SyntaxNode[] = [];\n this.collectErrorNodes(tree.rootNode, errorNodes);\n\n return {\n tree,\n hasErrors: errorNodes.length > 0,\n errorNodes,\n };\n } catch (error) {\n throw new Error(\n `Failed to parse TypeScript file (${source.length} chars): ${(error as Error).message}`,\n );\n }\n }\n\n private collectErrorNodes(node: SyntaxNode, acc: SyntaxNode[]): void {\n if (node.hasError && node.type === \"ERROR\") {\n acc.push(node);\n }\n for (const c of node.children) {\n this.collectErrorNodes(c, acc);\n }\n }\n\n /**\n * Boundary extraction: produces CodeBoundary[] directly from AST.\n */\n extractBoundaries(tree: Tree, source: string): CodeBoundary[] {\n if (!source.trim()) return [];\n const boundaries: CodeBoundary[] = [];\n\n const walk = (node: SyntaxNode): void => {\n if (isCandidateBoundary(node)) {\n // Skip wrapper export_statement in favor of its meaningful child(ren)\n if (node.type === \"export_statement\") {\n for (const c of node.children) walk(c);\n return;\n }\n\n if (this.shouldSkipStructuralNode(node)) {\n for (const c of node.children) walk(c);\n return;\n }\n\n // Local helper suppression\n if (\n (node.type === \"function_declaration\" ||\n node.type === \"arrow_function\" ||\n node.type === \"method_definition\" ||\n node.type === \"constructor\") &&\n isLocalHelper(node)\n ) {\n // Do not emit boundary for local helper\n for (const c of node.children) walk(c);\n return;\n }\n\n // Suppress arrow_function boundary when parent is variable_declarator (avoid duplicate with variable_declarator)\n if (\n node.type === \"arrow_function\" &&\n node.parent?.type === \"variable_declarator\"\n ) {\n for (const c of node.children) walk(c);\n return;\n }\n\n // Variable declarators: emit if not within function body (local helpers)\n if (node.type === \"variable_declarator\") {\n if (this.isWithinFunctionLikeBody(node)) {\n for (const c of node.children) walk(c);\n return;\n }\n }\n\n const name = extractName(node);\n const docInfo = findDocumentationStart(node, source);\n const classification = classifyBoundaryKind(node);\n\n boundaries.push({\n type: classification.simple,\n boundaryType: classification.boundaryType,\n name,\n startLine: docInfo.startLine,\n endLine: node.endPosition.row + 1,\n startByte: docInfo.startByte,\n endByte: node.endIndex,\n });\n\n // Traverse children (we allow nested boundaries where rules permit)\n for (const c of node.children) walk(c);\n return;\n }\n\n for (const c of node.children) walk(c);\n };\n\n walk(tree.rootNode);\n\n // Deduplicate by start/end/name triple\n const seen = new Set<string>();\n return boundaries.filter((b) => {\n const key = `${b.startByte}:${b.endByte}:${b.name}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n }\n\n /**\n * Determine if a structural node should be skipped in favor of children (transparent wrapper logic).\n * (Reduced compared to previous logic: currently only handles export wrappers already inline.)\n */\n private shouldSkipStructuralNode(_node: SyntaxNode): boolean {\n // Placeholder for future rules (e.g., more wrapper types). Currently we perform\n // explicit export_statement handling inside traversal so always false here.\n return false;\n }\n\n /**\n * Detect whether a node (e.g., variable_declarator with arrow function) is inside\n * a function/method/constructor body (local helper) before hitting a higher-level\n * structural container (class/namespace/module). Used to suppress local helpers.\n */\n private isWithinFunctionLikeBody(node: SyntaxNode): boolean {\n let ancestor = node.parent;\n while (ancestor) {\n if (\n ancestor.type === \"function_declaration\" ||\n ancestor.type === \"arrow_function\" ||\n ancestor.type === \"method_definition\" ||\n ancestor.type === \"constructor\"\n ) {\n return true;\n }\n if (\n ancestor.type === \"class_declaration\" ||\n ancestor.type === \"abstract_class_declaration\" ||\n ancestor.type === \"namespace_declaration\" ||\n ancestor.type === \"module_declaration\" ||\n ancestor.type === \"internal_module\" ||\n ancestor.type === \"interface_declaration\" ||\n ancestor.type === \"enum_declaration\"\n ) {\n return false;\n }\n ancestor = ancestor.parent;\n }\n return false;\n }\n}\n","/**\n * LanguageParserRegistry - Registry for tree-sitter language parsers\n *\n * Manages available language parsers and provides parser selection\n * based on file extensions and MIME types.\n */\n\nimport { defaults } from \"../../utils/config\";\nimport { PythonParser } from \"./parsers/PythonParser\";\nimport { TypeScriptParser } from \"./parsers/TypeScriptParser\";\nimport type { LanguageParser } from \"./parsers/types\";\n\nexport class LanguageParserRegistry {\n private parsers = new Map<string, LanguageParser>();\n private extensionMap = new Map<string, string>();\n private mimeTypeMap = new Map<string, string>();\n private readonly treeSitterSizeLimit: number;\n\n constructor(treeSitterSizeLimit: number = defaults.splitter.treeSitterSizeLimit) {\n this.treeSitterSizeLimit = treeSitterSizeLimit;\n this.initializeParsers();\n }\n\n /**\n * Get a parser by language name\n */\n getParser(language: string): LanguageParser | undefined {\n return this.parsers.get(language);\n }\n\n /**\n * Get a parser by file extension\n */\n getParserByExtension(extension: string): LanguageParser | undefined {\n const language = this.extensionMap.get(extension.toLowerCase());\n return language ? this.parsers.get(language) : undefined;\n }\n\n /**\n * Get a parser by MIME type\n */\n getParserByMimeType(mimeType: string): LanguageParser | undefined {\n const language = this.mimeTypeMap.get(mimeType.toLowerCase());\n return language ? this.parsers.get(language) : undefined;\n }\n\n /**\n * Register a new parser\n */\n registerParser(parser: LanguageParser): void {\n this.parsers.set(parser.name, parser);\n\n // Register file extensions\n for (const extension of parser.fileExtensions) {\n this.extensionMap.set(extension.toLowerCase(), parser.name);\n }\n\n // Register MIME types\n for (const mimeType of parser.mimeTypes) {\n this.mimeTypeMap.set(mimeType.toLowerCase(), parser.name);\n }\n }\n\n private initializeParsers(): void {\n const limit = this.treeSitterSizeLimit;\n\n // Unified TypeScript parser handles the full TS/JS family.\n const unified = new TypeScriptParser(limit);\n this.registerParser(unified); // registers under 'typescript' with all extensions & MIME types\n\n // Register Python parser\n const pythonParser = new PythonParser(limit);\n this.registerParser(pythonParser);\n }\n}\n","import { defaults } from \"../../utils/config\";\nimport { TextContentSplitter } from \"../splitters/TextContentSplitter\";\nimport type { Chunk, DocumentSplitter, SplitterConfig } from \"../types\";\nimport { LanguageParserRegistry } from \"./LanguageParserRegistry\";\nimport type { CodeBoundary, LanguageParser } from \"./parsers/types\";\n\n/**\n * Tree-sitter based source code splitter that provides semantic parsing\n * while maintaining compatibility with existing chunk patterns\n */\nexport class TreesitterSourceCodeSplitter implements DocumentSplitter {\n private readonly textContentSplitter: TextContentSplitter;\n private readonly registry: LanguageParserRegistry;\n private readonly maxChunkSize: number;\n\n constructor(config: SplitterConfig) {\n this.maxChunkSize = config.maxChunkSize;\n const treeSitterSizeLimit =\n config.treeSitterSizeLimit ?? defaults.splitter.treeSitterSizeLimit;\n\n // Initialize registry and text content splitter\n this.registry = new LanguageParserRegistry(treeSitterSizeLimit);\n this.textContentSplitter = new TextContentSplitter({\n chunkSize: this.maxChunkSize,\n });\n }\n\n async splitText(content: string, contentType?: string): Promise<Chunk[]> {\n if (!content.trim()) {\n return [];\n }\n\n // Try to get a parser for this content type\n const parser = this.getParserForContent(contentType);\n if (!parser) {\n // Fall back to TextContentSplitter for unsupported languages\n return this.fallbackToTextSplitter(content);\n }\n\n try {\n // Parse the source code\n const parseResult = parser.parse(content);\n\n if (parseResult.hasErrors) {\n console.warn(\n `Tree-sitter parsing had errors for ${contentType}, but continuing with partial results`,\n );\n }\n\n // Extract simplified boundaries for chunking\n const boundaries = parser.extractBoundaries(parseResult.tree, content);\n\n if (boundaries.length === 0) {\n // No semantic boundaries found, fall back to text splitter\n return this.fallbackToTextSplitter(content);\n }\n\n // Build hierarchical relationships between boundaries\n const hierarchicalBoundaries = this.buildBoundaryHierarchy(boundaries);\n\n // Direct conversion to chunks (parser is responsible for suppressing unwanted nested boundaries)\n return await this.boundariesToChunks(hierarchicalBoundaries, content, contentType);\n } catch (error) {\n // Graceful fallback to TextContentSplitter on any parsing error\n console.warn(\n \"TreesitterSourceCodeSplitter failed, falling back to TextContentSplitter:\",\n error,\n );\n return this.fallbackToTextSplitter(content);\n }\n }\n\n /**\n * Helper method to fall back to TextContentSplitter and convert results to ContentChunk[]\n */\n private async fallbackToTextSplitter(content: string): Promise<Chunk[]> {\n return this.splitContentIntoChunks(content, [], 0);\n }\n\n /**\n * Get the appropriate parser for the given content type\n */\n private getParserForContent(contentType?: string): LanguageParser | undefined {\n if (!contentType) {\n return undefined;\n }\n\n // Try to find parser by MIME type first\n let parser = this.registry.getParserByMimeType(contentType);\n if (parser) {\n return parser;\n }\n\n // Try to extract file extension from content type\n const extensionMatch = contentType.match(/\\.([a-zA-Z]+)$/);\n if (extensionMatch) {\n const extension = `.${extensionMatch[1]}`;\n parser = this.registry.getParserByExtension(extension);\n if (parser) {\n return parser;\n }\n }\n\n // Check for common patterns in content type\n if (contentType.includes(\"javascript\") || contentType.includes(\"typescript\")) {\n return this.registry.getParser(\"typescript\");\n }\n if (contentType.includes(\"jsx\") || contentType.includes(\"tsx\")) {\n // Unified TypeScript parser also handles JSX/TSX\n return this.registry.getParser(\"typescript\");\n }\n\n return undefined;\n }\n\n /**\n * Helper method to split content using TextContentSplitter only if needed\n * and create ContentChunks with the specified hierarchical path and level\n */\n private async splitContentIntoChunks(\n content: string,\n path: string[],\n level: number,\n ): Promise<Chunk[]> {\n // Preserve whitespace-only content if it fits within chunk size (for perfect reconstruction)\n // Only skip if content is completely empty\n if (content.length === 0) {\n return [];\n }\n\n // Only apply TextContentSplitter if content exceeds max chunk size\n if (content.length <= this.maxChunkSize) {\n // Content is small enough, return as single chunk preserving original formatting\n return [\n {\n types: [\"code\"] as const,\n content,\n section: {\n level,\n path,\n },\n },\n ];\n }\n\n // Content is too large, use TextContentSplitter to break it down\n const textChunks = await this.textContentSplitter.split(content);\n\n // Convert text chunks to ContentChunks with semantic context\n return textChunks.map((textChunk) => ({\n types: [\"code\"] as const,\n content: textChunk,\n section: {\n level,\n path,\n // Make sure to preserve parent hierarchy for large content chunks too\n },\n }));\n }\n\n /**\n * Convert boundaries to chunks.\n * Algorithm:\n * - Collect line breakpoints: file start, each boundary start, each boundary end+1, file end+1\n * - Create linear segments between breakpoints (each line appears exactly once)\n * - Determine containing (innermost) boundary for each segment for path/level\n * - First segment belonging to a structural boundary => structural chunk; subsequent segments demoted to content\n * - Universal max size enforcement: any segment > maxChunkSize is further split via TextContentSplitter\n * - No heuristic de-noising or whitespace merging; reconstruction is guaranteed by preserving order + exact text\n */\n private async boundariesToChunks(\n boundaries: CodeBoundary[],\n content: string,\n _contentType?: string,\n ): Promise<Chunk[]> {\n const lines = content.split(\"\\n\");\n const totalLines = lines.length;\n\n if (boundaries.length === 0) {\n // No boundaries found, use TextContentSplitter on entire content\n // Note: splitContentIntoChunks will preserve content if small enough\n return this.splitContentIntoChunks(content, [], 0);\n }\n\n // NOTE: Removed previous adjustment that forcibly shifted the first boundary\n // to line 1 when only whitespace preceded it. That logic rewrote startLine\n // and broke documentation merging tests (expected doc start line).\n // We preserve original boundary start lines now.\n\n // Step 1: Collect all boundary points (start and end+1 for exclusive ranges)\n const boundaryPoints = new Set<number>();\n boundaryPoints.add(1); // Always start from line 1\n boundaryPoints.add(totalLines + 1); // Always end after last line\n\n for (const boundary of boundaries) {\n boundaryPoints.add(boundary.startLine);\n boundaryPoints.add(boundary.endLine + 1); // +1 for exclusive end\n }\n\n // Step 2: Sort points to create segments\n const sortedPoints = Array.from(boundaryPoints).sort((a, b) => a - b);\n\n // Step 3: Create segments between consecutive points (collect first, don't process yet)\n interface TextSegment {\n startLine: number;\n endLine: number;\n content: string;\n containingBoundary?: CodeBoundary;\n }\n\n const segments: TextSegment[] = [];\n\n for (let i = 0; i < sortedPoints.length - 1; i++) {\n const startLine = sortedPoints[i];\n const endLine = sortedPoints[i + 1] - 1; // Convert back to inclusive end\n\n // Skip empty segments\n if (startLine > endLine || startLine > totalLines) {\n continue;\n }\n\n // Extract content for this segment\n const segmentLines = lines.slice(startLine - 1, Math.min(endLine, totalLines)); // Convert to 0-indexed and clamp\n let segmentContent = segmentLines.join(\"\\n\");\n\n // Add trailing newline for all segments except the last one (for perfect reconstruction)\n if (endLine < totalLines) {\n segmentContent += \"\\n\";\n }\n\n if (segmentContent.length === 0) {\n continue; // Skip empty segments\n }\n\n // Determine which boundary this segment belongs to (innermost containing boundary)\n const containingBoundary = this.findContainingBoundary(\n startLine,\n endLine,\n boundaries,\n );\n\n segments.push({\n startLine,\n endLine,\n content: segmentContent,\n containingBoundary,\n });\n }\n\n // Step 4: Convert segments directly to chunks (whitespace retained verbatim)\n const chunks: Chunk[] = [];\n\n // Ensure only ONE structural chunk is emitted per structural boundary.\n const structuralBoundaryFirstChunk = new Set<CodeBoundary>();\n\n // Accumulate whitespace-only segments and prepend to next non-whitespace segment\n // to avoid emitting standalone whitespace chunks (tests assert no empty-trim chunks)\n let pendingWhitespace = \"\";\n\n for (const segment of segments) {\n if (segment.content.trim() === \"\") {\n pendingWhitespace += segment.content;\n continue;\n }\n // Assign path and level based on containing boundary\n let path: string[];\n let level: number;\n\n const boundary = segment.containingBoundary;\n\n if (boundary) {\n // Use the boundary's hierarchical path and level\n path = boundary.path || [boundary.name || \"unnamed\"];\n level = boundary.level || path.length;\n } else {\n // No containing boundary, this is global code\n path = [];\n level = 0;\n }\n\n // Determine initial structural classification\n let isStructural = boundary?.boundaryType === \"structural\";\n\n if (isStructural && boundary) {\n if (structuralBoundaryFirstChunk.has(boundary)) {\n // Demote subsequent segments of the same structural boundary\n isStructural = false;\n } else {\n structuralBoundaryFirstChunk.add(boundary);\n }\n }\n\n // If segment is too large, delegate to TextContentSplitter\n const segmentChunks = await this.splitContentIntoChunks(\n segment.content,\n path,\n level,\n );\n\n // Overwrite types based on structural vs content classification (always include \"code\" for backward compatibility)\n for (const c of segmentChunks) {\n // Prepend any accumulated whitespace to the FIRST chunk emitted for this segment\n if (pendingWhitespace) {\n c.content = pendingWhitespace + c.content;\n pendingWhitespace = \"\";\n }\n c.types = isStructural ? [\"code\", \"structural\"] : [\"code\"];\n }\n\n chunks.push(...segmentChunks);\n }\n\n // If file ended with whitespace-only content, append it to last chunk (preserve reconstructability)\n if (pendingWhitespace && chunks.length > 0) {\n chunks[chunks.length - 1].content += pendingWhitespace;\n }\n\n return chunks;\n }\n\n /**\n * Build hierarchical relationships between boundaries based on containment\n */\n private buildBoundaryHierarchy(boundaries: CodeBoundary[]): CodeBoundary[] {\n // Create a copy of boundaries to avoid mutating the original\n const hierarchicalBoundaries = boundaries.map((b) => ({ ...b }));\n\n // Build parent-child relationships\n for (let i = 0; i < hierarchicalBoundaries.length; i++) {\n const boundary = hierarchicalBoundaries[i];\n let parent: CodeBoundary | undefined;\n let smallestRange = Infinity;\n\n // Find the smallest containing parent\n for (let j = 0; j < hierarchicalBoundaries.length; j++) {\n if (i === j) continue;\n const candidate = hierarchicalBoundaries[j];\n\n // Check if candidate contains boundary\n if (\n candidate.startLine <= boundary.startLine &&\n candidate.endLine >= boundary.endLine &&\n candidate.startByte <= boundary.startByte &&\n candidate.endByte >= boundary.endByte\n ) {\n const range = candidate.endLine - candidate.startLine;\n\n // Keep the smallest containing boundary (innermost parent)\n if (range < smallestRange) {\n smallestRange = range;\n parent = candidate;\n }\n }\n }\n\n if (parent) {\n boundary.parent = parent;\n }\n\n // Build hierarchical path\n boundary.path = this.buildBoundaryPath(boundary);\n boundary.level = boundary.path.length;\n }\n\n return hierarchicalBoundaries;\n }\n\n /**\n * Build hierarchical path for a boundary by walking up the parent chain\n */\n private buildBoundaryPath(boundary: CodeBoundary): string[] {\n const path: string[] = [];\n let current: CodeBoundary | undefined = boundary;\n\n // Walk up the parent chain\n while (current) {\n if (current.name) {\n path.unshift(current.name); // Add to beginning to build path from root\n }\n current = current.parent;\n }\n\n return path;\n }\n\n /**\n * Find the innermost boundary that contains the given line range\n */\n private findContainingBoundary(\n startLine: number,\n endLine: number,\n boundaries: CodeBoundary[],\n ): CodeBoundary | undefined {\n let innermost: CodeBoundary | undefined;\n let smallestRange = Infinity;\n\n for (const boundary of boundaries) {\n // Check if boundary contains the segment\n if (boundary.startLine <= startLine && boundary.endLine >= endLine) {\n const range = boundary.endLine - boundary.startLine;\n\n // Keep the smallest containing boundary (innermost)\n if (range < smallestRange) {\n smallestRange = range;\n innermost = boundary;\n }\n }\n }\n\n return innermost;\n }\n}\n","import { TreesitterSourceCodeSplitter } from \"../../splitter/treesitter/TreesitterSourceCodeSplitter\";\nimport type { AppConfig } from \"../../utils/config\";\nimport { MimeTypeUtils } from \"../../utils/mimeTypeUtils\";\nimport type { ContentFetcher, RawContent } from \"../fetcher/types\";\nimport type { ContentProcessorMiddleware, MiddlewareContext } from \"../middleware/types\";\nimport type { ScraperOptions } from \"../types\";\nimport { convertToString } from \"../utils/buffer\";\nimport { BasePipeline } from \"./BasePipeline\";\nimport type { PipelineResult } from \"./types\";\n\n/**\n * Pipeline for processing source code content with semantic, structure-aware splitting.\n * Uses TreesitterSourceCodeSplitter for language-aware hierarchical chunking that preserves\n * {level, path} integrity for reassembly. No greedy size-based merging is applied because it\n * would blur structural boundaries and degrade hierarchical reconstruction quality.\n */\nexport class SourceCodePipeline extends BasePipeline {\n private readonly middleware: ContentProcessorMiddleware[];\n private readonly splitter: TreesitterSourceCodeSplitter;\n\n constructor(config: AppConfig) {\n super();\n\n // Source code processing uses minimal middleware since we preserve raw structure\n this.middleware = [];\n\n // Semantic, structure-preserving splitter only (no greedy size merging to keep hierarchy intact)\n this.splitter = new TreesitterSourceCodeSplitter(config.splitter);\n }\n\n canProcess(mimeType: string): boolean {\n if (!mimeType) return false;\n return MimeTypeUtils.isSourceCode(mimeType);\n }\n\n async process(\n rawContent: RawContent,\n options: ScraperOptions,\n fetcher?: ContentFetcher,\n ): Promise<PipelineResult> {\n const contentString = convertToString(rawContent.content, rawContent.charset);\n\n const context: MiddlewareContext = {\n contentType: rawContent.mimeType || \"text/plain\",\n content: contentString,\n source: rawContent.source,\n // metadata: {\n // language: rawContent.mimeType\n // ? MimeTypeUtils.extractLanguageFromMimeType(rawContent.mimeType)\n // : \"text\",\n // isSourceCode: true,\n // },\n links: [], // Source code files typically don't contain web links\n errors: [],\n options,\n fetcher,\n };\n\n // Execute the middleware stack (minimal for source code)\n await this.executeMiddlewareStack(this.middleware, context);\n\n // Split the content using CodeContentSplitter\n const chunks = await this.splitter.splitText(context.content, rawContent.mimeType);\n\n return {\n title: context.title,\n contentType: context.contentType,\n textContent: context.content,\n // metadata: context.metadata,\n links: context.links,\n errors: context.errors,\n chunks,\n };\n }\n}\n","import { GreedySplitter } from \"../../splitter/GreedySplitter\";\nimport { TextDocumentSplitter } from \"../../splitter/TextDocumentSplitter\";\nimport type { AppConfig } from \"../../utils/config\";\nimport { MimeTypeUtils } from \"../../utils/mimeTypeUtils\";\nimport type { ContentFetcher, RawContent } from \"../fetcher/types\";\nimport type { ContentProcessorMiddleware, MiddlewareContext } from \"../middleware/types\";\nimport type { ScraperOptions } from \"../types\";\nimport { convertToString } from \"../utils/buffer\";\nimport { BasePipeline } from \"./BasePipeline\";\nimport type { PipelineResult } from \"./types\";\n\n/**\n * TextPipeline - Processes plain text content with size optimization.\n */\nexport class TextPipeline extends BasePipeline {\n private readonly middleware: ContentProcessorMiddleware[];\n private readonly splitter: GreedySplitter;\n\n constructor(config: AppConfig) {\n super();\n\n const preferredChunkSize = config.splitter.preferredChunkSize;\n const maxChunkSize = config.splitter.maxChunkSize;\n const minChunkSize = config.splitter.minChunkSize;\n\n // Text processing uses minimal middleware for maximum compatibility\n this.middleware = [];\n\n // Create the two-phase splitting: basic text splitting + size optimization\n const textSplitter = new TextDocumentSplitter(config.splitter);\n this.splitter = new GreedySplitter(\n textSplitter,\n minChunkSize,\n preferredChunkSize,\n maxChunkSize,\n );\n }\n\n canProcess(mimeType: string, content?: string | Buffer): boolean {\n // This pipeline serves as a fallback for text content, but should not process binary files\n\n // First check: MIME type filtering - use utility method for safe types\n if (!MimeTypeUtils.isSafeForTextProcessing(mimeType)) {\n return false;\n }\n\n // Second check: binary detection via null bytes (if content is provided)\n if (content && MimeTypeUtils.isBinary(content)) {\n return false;\n }\n\n // If we get here, it's a safe MIME type and doesn't appear binary\n return true;\n }\n\n async process(\n rawContent: RawContent,\n options: ScraperOptions,\n fetcher?: ContentFetcher,\n ): Promise<PipelineResult> {\n const contentString = convertToString(rawContent.content, rawContent.charset);\n\n const context: MiddlewareContext = {\n title: \"\", // Title extraction can be added in middleware if needed\n contentType: rawContent.mimeType || \"text/plain\",\n content: contentString,\n source: rawContent.source,\n links: [], // Generic text content typically doesn't contain structured links\n errors: [],\n options,\n fetcher,\n };\n\n // Execute the middleware stack (minimal for generic text)\n await this.executeMiddlewareStack(this.middleware, context);\n\n // Split the content using TextDocumentSplitter with size optimization\n const chunks = await this.splitter.splitText(context.content, rawContent.mimeType);\n\n return {\n title: context.title,\n contentType: context.contentType,\n textContent: context.content,\n links: context.links,\n errors: context.errors,\n chunks,\n };\n }\n}\n","/**\n * PipelineFactory - Centralized factory for creating content processing pipelines.\n *\n * This factory ensures consistency across scraper strategies by providing standardized\n * pipeline configurations. It eliminates code duplication and makes it easy to maintain\n * and extend pipeline configurations globally.\n */\n\nimport type { AppConfig } from \"../../utils/config\";\nimport type { ManagedBrowser } from \"../fetcher/ManagedBrowser\";\nimport { DocumentPipeline } from \"./DocumentPipeline\";\nimport { HtmlPipeline } from \"./HtmlPipeline\";\nimport { JsonPipeline } from \"./JsonPipeline\";\nimport { MarkdownPipeline } from \"./MarkdownPipeline\";\nimport { SourceCodePipeline } from \"./SourceCodePipeline\";\nimport { TextPipeline } from \"./TextPipeline\";\nimport type { ContentPipeline } from \"./types\";\n\n/**\n * Factory class for creating content processing pipelines.\n * Provides standardized pipeline configurations used across different scraper strategies.\n */\n// biome-ignore lint/complexity/noStaticOnlyClass: Factory pattern with static methods is appropriate here\nexport class PipelineFactory {\n /**\n * Creates the standard set of content pipelines used by all scraper strategies.\n * Includes HTML, Markdown, JSON, source code, document, and text processing capabilities.\n * Each pipeline now handles both preprocessing and content-specific splitting.\n * TextPipeline is placed last as the universal fallback for unknown content types.\n *\n * @param appConfig - Application configuration.\n * @param managedBrowser - The browser the HTML pipeline renders with; pass\n * one to share it with the browser fetcher.\n * @returns Array of content pipelines in processing order\n */\n public static createStandardPipelines(\n appConfig: AppConfig,\n managedBrowser?: ManagedBrowser,\n ): ContentPipeline[] {\n return [\n new JsonPipeline(appConfig),\n new SourceCodePipeline(appConfig),\n new DocumentPipeline(appConfig), // PDF, Office docs, OpenDocument, RTF, eBooks, Jupyter notebooks\n new HtmlPipeline(appConfig, managedBrowser),\n new MarkdownPipeline(appConfig),\n new TextPipeline(appConfig), // Universal fallback - must be last\n ];\n }\n}\n","import type { AppConfig } from \"../../utils/config\";\nimport { logger } from \"../../utils/logger\";\nimport { MimeTypeUtils } from \"../../utils/mimeTypeUtils\";\nimport { HttpFetcher } from \"../fetcher\";\nimport { FetchStatus, type RawContent } from \"../fetcher/types\";\nimport { PipelineFactory } from \"../pipelines/PipelineFactory\";\nimport type { ContentPipeline, PipelineResult } from \"../pipelines/types\";\nimport type { QueueItem } from \"../types\";\nimport { ScrapeMode, type ScraperOptions } from \"../types\";\nimport type { ProcessItemResult } from \"./BaseScraperStrategy\";\n\nexport interface GitHubRepoInfo {\n owner: string;\n repo: string;\n branch?: string;\n subPath?: string;\n}\n\nexport interface GitHubTreeItem {\n path: string;\n type: \"blob\" | \"tree\";\n sha: string;\n size?: number;\n url: string;\n}\n\nexport interface GitHubTreeResponse {\n sha: string;\n url: string;\n tree: GitHubTreeItem[];\n truncated: boolean;\n}\n\n/**\n * GitHubRepoProcessor handles processing individual files from GitHub repositories.\n * It processes HTTPS blob URLs (https://github.com/owner/repo/blob/branch/filepath).\n *\n * This processor is stateless and contains the core logic from GitHubRepoScraperStrategy.\n */\nexport class GitHubRepoProcessor {\n private readonly httpFetcher: HttpFetcher;\n private readonly pipelines: ContentPipeline[];\n\n constructor(config: AppConfig) {\n this.httpFetcher = new HttpFetcher(config.scraper);\n this.pipelines = PipelineFactory.createStandardPipelines(config);\n }\n\n /**\n * Parses an HTTPS blob URL to extract repository information.\n * Format: https://github.com/owner/repo/blob/branch/filepath\n */\n parseHttpsBlobUrl(url: string): GitHubRepoInfo & { filePath: string } {\n const parsedUrl = new URL(url);\n const segments = parsedUrl.pathname.split(\"/\").filter(Boolean);\n\n // Expected format: /owner/repo/blob/branch/filepath\n if (segments.length < 5 || segments[2] !== \"blob\") {\n throw new Error(\n `Invalid GitHub blob URL format. Expected: https://github.com/owner/repo/blob/branch/filepath. Got: ${url}`,\n );\n }\n\n const owner = segments[0];\n const repo = segments[1];\n const branch = segments[3];\n const filePath = segments.slice(4).join(\"/\");\n\n return { owner, repo, branch, filePath };\n }\n\n /**\n * Fetches the raw content of a file from GitHub.\n */\n private async fetchFileContent(\n repoInfo: GitHubRepoInfo,\n filePath: string,\n etag?: string | null,\n headers?: Record<string, string>,\n signal?: AbortSignal,\n ): Promise<RawContent> {\n const { owner, repo, branch } = repoInfo;\n const rawUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${branch}/${filePath}`;\n\n const rawContent = await this.httpFetcher.fetch(rawUrl, { signal, etag, headers });\n\n // Override GitHub's generic 'text/plain' or 'application/octet-stream' MIME type with file extension-based detection\n const detectedMimeType = MimeTypeUtils.detectMimeTypeFromPath(filePath);\n if (\n detectedMimeType &&\n (rawContent.mimeType === \"text/plain\" ||\n rawContent.mimeType === \"application/octet-stream\")\n ) {\n return {\n ...rawContent,\n mimeType: detectedMimeType,\n };\n }\n\n return rawContent;\n }\n\n /**\n * Processes a single GitHub repository file from an HTTPS blob URL.\n */\n async process(\n item: QueueItem,\n options: ScraperOptions,\n headers?: Record<string, string>,\n signal?: AbortSignal,\n ): Promise<ProcessItemResult> {\n // Parse the HTTPS blob URL to extract repository info and file path\n const repoInfo = this.parseHttpsBlobUrl(item.url);\n const { owner, repo, branch, filePath } = repoInfo;\n\n // Fetch the file content from raw.githubusercontent.com\n const rawContent = await this.fetchFileContent(\n { owner, repo, branch },\n filePath,\n item.etag,\n headers,\n signal,\n );\n\n // Return the status directly - BaseScraperStrategy handles NOT_MODIFIED and NOT_FOUND\n if (rawContent.status !== FetchStatus.SUCCESS) {\n return { url: item.url, links: [], status: rawContent.status };\n }\n\n // Process content through appropriate pipeline\n let processed: PipelineResult | undefined;\n\n for (const pipeline of this.pipelines) {\n const contentBuffer = Buffer.isBuffer(rawContent.content)\n ? rawContent.content\n : Buffer.from(rawContent.content);\n if (pipeline.canProcess(rawContent.mimeType || \"text/plain\", contentBuffer)) {\n logger.debug(\n `Selected ${pipeline.constructor.name} for content type \"${rawContent.mimeType}\" (${filePath})`,\n );\n\n // Force 'fetch' mode for GitHub to avoid unnecessary Playwright usage on raw content.\n // GitHub raw files (e.g., HTML files) don't have their dependencies available at the\n // raw.githubusercontent.com domain, so rendering them in a browser would be broken\n // and provide no additional value over direct HTML parsing with Cheerio.\n const gitHubOptions = { ...options, scrapeMode: ScrapeMode.Fetch };\n\n processed = await pipeline.process(rawContent, gitHubOptions, this.httpFetcher);\n break;\n }\n }\n\n if (!processed) {\n logger.warn(\n `⚠️ Unsupported content type \"${rawContent.mimeType}\" for file ${filePath}. Skipping processing.`,\n );\n return { url: item.url, links: [], status: FetchStatus.SKIPPED };\n }\n\n for (const err of processed.errors ?? []) {\n logger.warn(`⚠️ Processing error for ${filePath}: ${err.message}`);\n }\n\n // Create document with GitHub-specific metadata\n const githubUrl = `https://github.com/${owner}/${repo}/blob/${branch}/${filePath}`;\n\n // Use filename as fallback if title is empty or not a string\n const filename = filePath.split(\"/\").pop() || \"Untitled\";\n\n return {\n url: githubUrl,\n title: processed.title?.trim() || filename || \"Untitled\",\n etag: rawContent.etag,\n lastModified: rawContent.lastModified,\n sourceContentType: rawContent.mimeType,\n contentType: processed.contentType || rawContent.mimeType,\n content: processed,\n links: [], // Always return empty links array for individual files\n status: FetchStatus.SUCCESS,\n };\n }\n\n /**\n * Cleanup resources used by this processor.\n */\n async cleanup(): Promise<void> {\n await Promise.allSettled(this.pipelines.map((pipeline) => pipeline.close()));\n }\n}\n","import type { AppConfig } from \"../../utils/config\";\nimport { logger } from \"../../utils/logger\";\nimport { HttpFetcher } from \"../fetcher\";\nimport { FetchStatus } from \"../fetcher/types\";\nimport { PipelineFactory } from \"../pipelines/PipelineFactory\";\nimport type { ContentPipeline, PipelineResult } from \"../pipelines/types\";\nimport type { QueueItem } from \"../types\";\nimport { ScrapeMode, type ScraperOptions } from \"../types\";\nimport { shouldIncludeUrl } from \"../utils/patternMatcher\";\nimport type { ProcessItemResult } from \"./BaseScraperStrategy\";\n\ninterface GitHubWikiInfo {\n owner: string;\n repo: string;\n}\n\n/**\n * GitHubWikiProcessor handles scraping GitHub wiki pages using standard web scraping techniques.\n * GitHub wikis are separate from the main repository and are hosted at /wiki/ URLs.\n *\n * Features:\n * - Scrapes all wiki pages by following links within the wiki\n * - Uses web scraping approach since wikis are not available via the Git tree API\n * - Processes wiki content as HTML/Markdown pages\n * - Stays within the wiki scope to avoid crawling the entire repository\n *\n * This processor is stateless and contains the core logic from GitHubWikiScraperStrategy.\n */\nexport class GitHubWikiProcessor {\n private readonly httpFetcher: HttpFetcher;\n private readonly pipelines: ContentPipeline[];\n\n constructor(config: AppConfig) {\n this.httpFetcher = new HttpFetcher(config.scraper);\n this.pipelines = PipelineFactory.createStandardPipelines(config);\n }\n\n /**\n * Parses a GitHub wiki URL to extract repository information.\n */\n parseGitHubWikiUrl(url: string): GitHubWikiInfo {\n const parsedUrl = new URL(url);\n // Extract /<org>/<repo> from github.com/<org>/<repo>/wiki/...\n const match = parsedUrl.pathname.match(/^\\/([^/]+)\\/([^/]+)\\/wiki/);\n if (!match) {\n throw new Error(`Invalid GitHub wiki URL: ${url}`);\n }\n\n const [, owner, repo] = match;\n return { owner, repo };\n }\n\n /**\n * Determines if a URL should be processed within the wiki scope.\n */\n shouldProcessUrl(url: string, options: ScraperOptions): boolean {\n try {\n const parsedUrl = new URL(url);\n\n // Get the expected repository info from the base URL\n const baseWikiInfo = this.parseGitHubWikiUrl(options.url);\n const expectedWikiPath = `/${baseWikiInfo.owner}/${baseWikiInfo.repo}/wiki`;\n\n // Check if the URL is within the same wiki\n if (!parsedUrl.pathname.startsWith(expectedWikiPath)) {\n return false;\n }\n\n // Apply include/exclude patterns to the wiki page path\n const wikiPagePath = parsedUrl.pathname\n .replace(expectedWikiPath, \"\")\n .replace(/^\\//, \"\");\n return shouldIncludeUrl(\n wikiPagePath || \"Home\",\n options.includePatterns,\n options.excludePatterns,\n );\n } catch {\n return false;\n }\n }\n\n /**\n * Processes a single GitHub wiki page.\n */\n async process(\n item: QueueItem,\n options: ScraperOptions,\n headers?: Record<string, string>,\n signal?: AbortSignal,\n ): Promise<ProcessItemResult> {\n const currentUrl = item.url;\n\n try {\n // Fetch the wiki page content with ETag for conditional requests\n const rawContent = await this.httpFetcher.fetch(currentUrl, {\n signal,\n etag: item.etag,\n headers,\n });\n\n // GitHub redirects the wiki of a repository that has none to the\n // repository page. That page is not a wiki page, so the wiki is absent.\n // Checked before the status: a refresh sends the stored ETag through the\n // redirect, and a row that older versions stored for the repository page\n // carries that page's ETag, so the answer can be a 304 from outside the\n // wiki.\n const wikiInfo = this.parseGitHubWikiUrl(currentUrl);\n const wikiPath = `/${wikiInfo.owner}/${wikiInfo.repo}/wiki`;\n if (!new URL(rawContent.source, currentUrl).pathname.startsWith(wikiPath)) {\n logger.debug(`Wiki URL redirected out of the wiki: ${currentUrl}`);\n return { url: currentUrl, links: [], status: FetchStatus.NOT_FOUND };\n }\n\n // Return the status directly - BaseScraperStrategy handles NOT_MODIFIED and NOT_FOUND\n if (rawContent.status !== FetchStatus.SUCCESS) {\n return { url: currentUrl, links: [], status: rawContent.status };\n }\n\n // Process content through appropriate pipeline\n let processed: PipelineResult | undefined;\n\n for (const pipeline of this.pipelines) {\n if (pipeline.canProcess(rawContent.mimeType, rawContent.content)) {\n logger.debug(\n `Selected ${pipeline.constructor.name} for content type \"${rawContent.mimeType}\" (${currentUrl})`,\n );\n\n // Use fetch mode for consistent behavior\n const wikiOptions = { ...options, scrapeMode: ScrapeMode.Fetch };\n\n processed = await pipeline.process(rawContent, wikiOptions, this.httpFetcher);\n break;\n }\n }\n\n if (!processed) {\n logger.warn(\n `⚠️ Unsupported content type \"${rawContent.mimeType}\" for wiki page ${currentUrl}. Skipping processing.`,\n );\n return { url: currentUrl, links: [], status: FetchStatus.SKIPPED };\n }\n\n for (const err of processed.errors ?? []) {\n logger.warn(`⚠️ Processing error for ${currentUrl}: ${err.message}`);\n }\n\n const parsedUrl = new URL(currentUrl);\n\n // Extract links from the processed content\n const links = processed.links || [];\n\n // Filter links to only include other wiki pages and ensure they're absolute URLs\n const wikiLinks = links\n .filter((link) => {\n // Skip obviously invalid links\n if (\n !link ||\n link.trim() === \"\" ||\n link === \"invalid-url\" ||\n link === \"not-a-url-at-all\"\n ) {\n return false;\n }\n return true;\n })\n .map((link) => {\n try {\n // Convert relative links to absolute URLs\n return new URL(link, currentUrl).href;\n } catch {\n return null;\n }\n })\n .filter((link): link is string => link !== null)\n .filter((link) => {\n try {\n const linkUrl = new URL(link);\n // Only include links that are within the same wiki\n return (\n linkUrl.hostname === parsedUrl.hostname &&\n linkUrl.pathname.startsWith(wikiPath)\n );\n } catch {\n return false;\n }\n });\n\n return {\n url: currentUrl,\n // The crawl stores the pipeline's title for a page with text and this\n // one for a page without, so both get the <title> GitHub serves with\n // every wiki page.\n title: processed.title,\n etag: rawContent.etag,\n lastModified: rawContent.lastModified,\n contentType: rawContent.mimeType,\n content: processed,\n links: wikiLinks,\n status: FetchStatus.SUCCESS,\n };\n } catch (error) {\n logger.warn(`⚠️ Failed to process wiki page ${currentUrl}: ${error}`);\n return { url: currentUrl, links: [], status: FetchStatus.SUCCESS };\n }\n }\n\n /**\n * Cleanup resources used by this processor.\n */\n async cleanup(): Promise<void> {\n await Promise.allSettled(this.pipelines.map((pipeline) => pipeline.close()));\n }\n}\n","import { exec } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { logger } from \"../../utils/logger\";\n\nconst execAsync = promisify(exec);\n\n/**\n * Resolves GitHub authentication headers using a cascading fallback mechanism.\n *\n * Resolution order (first match wins):\n * 1. Explicit `Authorization` header in input - user has full control\n * 2. `GITHUB_TOKEN` environment variable - standard GitHub Actions / CI convention\n * 3. `GH_TOKEN` environment variable - alternative used by some CI systems\n * 4. `gh auth token` CLI - local development convenience\n *\n * @param explicitHeaders - Headers provided by the user in scraper options\n * @returns Headers object with Authorization if available, or the original headers\n */\nexport async function resolveGitHubAuth(\n explicitHeaders?: Record<string, string>,\n): Promise<Record<string, string>> {\n // 1. Check for explicit Authorization header (case-insensitive check)\n if (explicitHeaders) {\n const hasAuthHeader = Object.keys(explicitHeaders).some(\n (key) => key.toLowerCase() === \"authorization\",\n );\n if (hasAuthHeader) {\n return explicitHeaders;\n }\n }\n\n // 2. Check GITHUB_TOKEN environment variable\n const githubToken = process.env.GITHUB_TOKEN;\n if (githubToken) {\n logger.debug(\"Using GitHub token from GITHUB_TOKEN environment variable\");\n return {\n ...explicitHeaders,\n Authorization: `Bearer ${githubToken}`,\n };\n }\n\n // 3. Check GH_TOKEN environment variable (fallback)\n const ghToken = process.env.GH_TOKEN;\n if (ghToken) {\n logger.debug(\"Using GitHub token from GH_TOKEN environment variable\");\n return {\n ...explicitHeaders,\n Authorization: `Bearer ${ghToken}`,\n };\n }\n\n // 4. Try gh CLI as last resort\n try {\n const { stdout } = await execAsync(\"gh auth token\", { timeout: 5000 });\n const cliToken = stdout.trim();\n if (cliToken) {\n logger.debug(\"Using GitHub token from local gh CLI\");\n return {\n ...explicitHeaders,\n Authorization: `Bearer ${cliToken}`,\n };\n }\n } catch {\n // gh CLI not installed, not authenticated, or command failed - silently continue\n }\n\n // No authentication available - return original headers (or empty object)\n return explicitHeaders ?? {};\n}\n","import type { ProgressCallback } from \"../../types\";\nimport type { AppConfig } from \"../../utils/config\";\nimport { ChallengeError, HttpStatusError, ScraperError } from \"../../utils/errors\";\nimport { logger } from \"../../utils/logger\";\nimport { MimeTypeUtils } from \"../../utils/mimeTypeUtils\";\nimport { HttpFetcher } from \"../fetcher\";\nimport { FetchStatus } from \"../fetcher/types\";\nimport type { QueueItem, ScraperOptions, ScraperProgressEvent } from \"../types\";\nimport { shouldIncludeUrl } from \"../utils/patternMatcher\";\nimport { BaseScraperStrategy, type ProcessItemResult } from \"./BaseScraperStrategy\";\nimport type {\n GitHubRepoInfo,\n GitHubTreeItem,\n GitHubTreeResponse,\n} from \"./GitHubRepoProcessor\";\nimport { GitHubRepoProcessor } from \"./GitHubRepoProcessor\";\nimport { GitHubWikiProcessor } from \"./GitHubWikiProcessor\";\nimport { resolveGitHubAuth } from \"./github-auth\";\n\n/** Text-based file extensions recognized for GitHub repository scraping. */\nconst TEXT_EXTENSIONS: ReadonlySet<string> = new Set([\n // Markup\n \".md\",\n \".markdown\",\n \".mdx\",\n \".gfm\",\n \".mkd\",\n \".mkdn\",\n \".mkdown\",\n \".mdown\",\n \".mdwn\",\n \".ronn\",\n \".txt\",\n \".rst\",\n \".adoc\",\n \".asciidoc\",\n \".textile\",\n \".org\",\n \".pod\",\n \".rdoc\",\n \".wiki\",\n \".rmd\",\n // Web\n \".html\",\n \".htm\",\n \".xml\",\n \".xsl\",\n \".xslt\",\n \".xsd\",\n \".dtd\",\n \".wsdl\",\n \".xhtml\",\n // Stylesheets\n \".css\",\n \".scss\",\n \".sass\",\n \".less\",\n // JavaScript/TypeScript\n \".js\",\n \".jsx\",\n \".mjs\",\n \".cjs\",\n \".ts\",\n \".tsx\",\n \".mts\",\n \".cts\",\n // Python\n \".py\",\n \".pyw\",\n \".pyi\",\n \".pyx\",\n \".pxd\",\n // JVM\n \".java\",\n \".kt\",\n \".kts\",\n \".scala\",\n \".groovy\",\n \".gradle\",\n // .NET\n \".cs\",\n // Systems\n \".c\",\n \".cpp\",\n \".cc\",\n \".cxx\",\n \".h\",\n \".hpp\",\n \".hxx\",\n \".go\",\n \".rs\",\n \".zig\",\n \".nim\",\n \".v\",\n \".cr\",\n // Apple/Mobile\n \".swift\",\n \".dart\",\n \".m\",\n \".mm\",\n // Scripting\n \".rb\",\n \".rake\",\n \".php\",\n \".lua\",\n \".pl\",\n \".pm\",\n \".r\",\n // Functional\n \".hs\",\n \".lhs\",\n \".elm\",\n \".erl\",\n \".ex\",\n \".exs\",\n \".clj\",\n \".cljs\",\n \".cljc\",\n \".jl\",\n // Web3\n \".sol\",\n \".move\",\n \".cairo\",\n // Web Frameworks\n \".vue\",\n \".svelte\",\n \".astro\",\n // Shell\n \".sh\",\n \".bash\",\n \".zsh\",\n \".fish\",\n \".ps1\",\n \".bat\",\n \".cmd\",\n // Data\n \".json\",\n \".yaml\",\n \".yml\",\n \".csv\",\n \".tsv\",\n \".sql\",\n \".graphql\",\n \".gql\",\n // Config\n \".toml\",\n \".ini\",\n \".cfg\",\n \".conf\",\n \".properties\",\n \".env\",\n \".gitignore\",\n \".dockerignore\",\n \".gitattributes\",\n \".editorconfig\",\n // Build Systems\n \".pom\",\n \".sbt\",\n \".maven\",\n \".cmake\",\n \".make\",\n \".dockerfile\",\n \".containerfile\",\n \".makefile\",\n \".bazel\",\n \".bzl\",\n \".buck\",\n // IaC\n \".tf\",\n \".tfvars\",\n \".hcl\",\n // Package managers\n \".mod\",\n \".sum\",\n // Schema/API\n \".proto\",\n \".prisma\",\n \".thrift\",\n \".avro\",\n // TeX\n \".tex\",\n \".latex\",\n // Other\n \".log\",\n]);\n\n/** Document extensions supported by DocumentPipeline. */\nconst DOCUMENT_EXTENSIONS: ReadonlySet<string> = new Set([\n \".pdf\",\n \".docx\",\n \".xlsx\",\n \".pptx\",\n \".ipynb\",\n \".doc\",\n \".xls\",\n \".ppt\",\n \".odt\",\n \".ods\",\n \".odp\",\n \".rtf\",\n \".epub\",\n \".fb2\",\n]);\n\n/** Well-known filenames (case-insensitive) that are typically text-based. */\nconst COMMON_TEXT_FILES: readonly string[] = [\n \"readme\",\n \"license\",\n \"changelog\",\n \"contributing\",\n \"authors\",\n \"maintainers\",\n \"dockerfile\",\n \"makefile\",\n \"rakefile\",\n \"gemfile\",\n \"podfile\",\n \"cartfile\",\n \"brewfile\",\n \"procfile\",\n \"vagrantfile\",\n \"gulpfile\",\n \"gruntfile\",\n \".prettierrc\",\n \".eslintrc\",\n \".babelrc\",\n \".nvmrc\",\n \".npmrc\",\n];\n\n/**\n * GitHubScraperStrategy is a discovery strategy that orchestrates the scraping of both\n * GitHub repository code and wiki pages. When given a GitHub repository URL, it will:\n *\n * 1. Attempt to scrape the repository's wiki pages using GitHubWikiProcessor (prioritized)\n * 2. Discover all repository files using the GitHub Tree API\n * 3. Create HTTPS blob URLs for each file, which are stored in the database\n * 4. Process blob URLs directly with GitHubRepoProcessor\n *\n * This provides comprehensive documentation coverage by including both wiki documentation\n * and source code in a single scraping job, with wikis prioritized as they typically\n * contain higher-quality curated documentation.\n *\n * Features:\n * - Handles base GitHub repository URLs (e.g., https://github.com/owner/repo)\n * - Handles branch-specific URLs (e.g., https://github.com/owner/repo/tree/branch)\n * - Handles single file URLs (e.g., https://github.com/owner/repo/blob/branch/path)\n * - Discovers all files efficiently using GitHub's Tree API\n * - Generates and processes user-friendly HTTPS blob URLs throughout\n * - Prioritizes wiki content over repository files for better documentation quality\n * - Respects maxPages limit across both scraping phases to prevent exceeding quotas\n * - Automatically discovers and scrapes both wiki and code content\n * - Graceful handling when wikis don't exist or are inaccessible\n */\nexport class GitHubScraperStrategy extends BaseScraperStrategy {\n private readonly httpFetcher: HttpFetcher;\n private readonly wikiProcessor: GitHubWikiProcessor;\n private readonly repoProcessor: GitHubRepoProcessor;\n private resolvedAuthHeaders?: Record<string, string>;\n private resolvedAuthKey?: string;\n\n constructor(config: AppConfig) {\n super(config);\n this.httpFetcher = new HttpFetcher(config.scraper);\n this.wikiProcessor = new GitHubWikiProcessor(config);\n this.repoProcessor = new GitHubRepoProcessor(config);\n }\n\n /**\n * Parses a GitHub URL to extract repository information.\n */\n private parseGitHubUrl(\n url: string,\n ): GitHubRepoInfo & { isBlob?: boolean; filePath?: string } {\n const parsedUrl = new URL(url);\n // Extract /<org>/<repo> from github.com/<org>/<repo>/...\n const match = parsedUrl.pathname.match(/^\\/([^/]+)\\/([^/]+)/);\n if (!match) {\n throw new Error(`Invalid GitHub repository URL: ${url}`);\n }\n\n const [, owner, repo] = match;\n\n // Extract branch and optional subpath from URLs like /tree/<branch>/<subPath>\n const segments = parsedUrl.pathname.split(\"/\").filter(Boolean);\n\n // Handle /blob/ URLs for single file indexing\n if (segments.length >= 4 && segments[2] === \"blob\") {\n const branch = segments[3];\n const filePath = segments.length > 4 ? segments.slice(4).join(\"/\") : undefined;\n return { owner, repo, branch, filePath, isBlob: true };\n }\n\n // Handle /tree/ URLs with branch and optional subpath\n if (segments.length >= 4 && segments[2] === \"tree\") {\n const branch = segments[3];\n const subPath = segments.length > 4 ? segments.slice(4).join(\"/\") : undefined;\n return { owner, repo, branch, subPath };\n }\n\n // Base repository URL\n return { owner, repo };\n }\n\n private buildAuthCacheKey(explicitHeaders?: Record<string, string>): string {\n const normalizedHeaders = explicitHeaders\n ? Object.keys(explicitHeaders)\n .sort()\n .map((key) => [key, explicitHeaders[key]])\n : [];\n const envKey = `${process.env.GITHUB_TOKEN ?? \"\"}|${process.env.GH_TOKEN ?? \"\"}`;\n return JSON.stringify({ headers: normalizedHeaders, env: envKey });\n }\n\n private async getResolvedAuthHeaders(\n explicitHeaders?: Record<string, string>,\n ): Promise<Record<string, string>> {\n const cacheKey = this.buildAuthCacheKey(explicitHeaders);\n if (this.resolvedAuthHeaders && this.resolvedAuthKey === cacheKey) {\n return this.resolvedAuthHeaders;\n }\n\n const resolved = await resolveGitHubAuth(explicitHeaders);\n this.resolvedAuthHeaders = resolved;\n this.resolvedAuthKey = cacheKey;\n return resolved;\n }\n\n /**\n * Fetches the repository tree structure from GitHub API.\n */\n private async fetchRepositoryTree(\n repoInfo: GitHubRepoInfo,\n headers?: Record<string, string>,\n signal?: AbortSignal,\n ): Promise<{ tree: GitHubTreeResponse; resolvedBranch: string }> {\n const { owner, repo, branch } = repoInfo;\n\n // If no branch specified, fetch the default branch first\n let targetBranch = branch;\n if (!targetBranch) {\n const repoUrl = `https://api.github.com/repos/${owner}/${repo}`;\n logger.debug(`Fetching repository info: ${repoUrl}`);\n\n let repoContent: Awaited<ReturnType<typeof this.httpFetcher.fetch>>;\n try {\n repoContent = await this.httpFetcher.fetch(repoUrl, { signal, headers });\n } catch (error) {\n this.rethrowAsGitHubAuthError(error, owner, repo);\n throw error;\n }\n\n // Check for NOT_FOUND status before parsing - repo is inaccessible (private or doesn't exist)\n if (repoContent.status === FetchStatus.NOT_FOUND) {\n throw new ScraperError(\n `Repository \"${owner}/${repo}\" not found or not accessible. For private repositories, set the GITHUB_TOKEN environment variable.`,\n false,\n );\n }\n\n // Try to parse the response to get the default branch\n try {\n const content =\n typeof repoContent.content === \"string\"\n ? repoContent.content\n : repoContent.content.toString(\"utf-8\");\n const repoData = JSON.parse(content) as { default_branch?: string };\n const defaultBranch =\n typeof repoData.default_branch === \"string\"\n ? repoData.default_branch.trim()\n : \"\";\n if (!defaultBranch) {\n logger.warn(\n `⚠️ Repository info missing default_branch for ${owner}/${repo}, using 'main'`,\n );\n targetBranch = \"main\";\n } else {\n targetBranch = defaultBranch;\n logger.debug(`Using default branch: ${targetBranch}`);\n }\n } catch (parseError) {\n // Only fall back to \"main\" for JSON parse errors (e.g., unexpected API response format)\n logger.warn(`⚠️ Could not parse repository info, using 'main': ${parseError}`);\n targetBranch = \"main\";\n }\n }\n\n const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${targetBranch}?recursive=1`;\n logger.debug(`Fetching repository tree: ${treeUrl}`);\n\n let rawContent: Awaited<ReturnType<typeof this.httpFetcher.fetch>>;\n try {\n rawContent = await this.httpFetcher.fetch(treeUrl, { signal, headers });\n } catch (error) {\n this.rethrowAsGitHubAuthError(error, owner, repo);\n throw error;\n }\n\n // Check for NOT_FOUND status before parsing - this indicates repo is inaccessible\n if (rawContent.status === FetchStatus.NOT_FOUND) {\n throw new ScraperError(\n `Repository \"${owner}/${repo}\" not found or not accessible. For private repositories, set the GITHUB_TOKEN environment variable.`,\n false,\n );\n }\n\n const content =\n typeof rawContent.content === \"string\"\n ? rawContent.content\n : rawContent.content.toString(\"utf-8\");\n\n // Parse JSON with proper error handling\n let treeData: GitHubTreeResponse;\n try {\n treeData = JSON.parse(content) as GitHubTreeResponse;\n } catch (parseError) {\n throw new ScraperError(\n `Failed to parse GitHub API response for \"${owner}/${repo}\". The repository may be inaccessible or the API returned an unexpected response.`,\n false,\n parseError instanceof Error ? parseError : undefined,\n );\n }\n\n if (treeData.truncated) {\n logger.warn(\n `⚠️ Repository tree was truncated for ${owner}/${repo}. Some files may be missing.`,\n );\n }\n\n return { tree: treeData, resolvedBranch: targetBranch };\n }\n\n /**\n * Determines if a file should be processed based on its path and type.\n */\n private shouldProcessFile(item: GitHubTreeItem, options: ScraperOptions): boolean {\n if (item.type !== \"blob\") {\n return false;\n }\n\n const filePath = item.path;\n const pathLower = filePath.toLowerCase();\n\n // Extract extension for Set-based lookup\n const lastDot = pathLower.lastIndexOf(\".\");\n const ext = lastDot !== -1 ? pathLower.slice(lastDot) : \"\";\n\n const hasTextExtension = ext !== \"\" && TEXT_EXTENSIONS.has(ext);\n const hasDocumentExtension = ext !== \"\" && DOCUMENT_EXTENSIONS.has(ext);\n const hasCompoundExtension =\n pathLower.includes(\".env.\") ||\n pathLower.endsWith(\".env\") ||\n pathLower.includes(\".config.\") ||\n pathLower.includes(\".lock\");\n\n const fileName = filePath.split(\"/\").pop() || \"\";\n const fileNameLower = fileName.toLowerCase();\n\n const isCommonTextFile = COMMON_TEXT_FILES.some(\n (name) => fileNameLower === name || fileNameLower.startsWith(`${name}.`),\n );\n\n // If file passes known checks, include it\n if (\n hasTextExtension ||\n hasDocumentExtension ||\n hasCompoundExtension ||\n isCommonTextFile\n ) {\n return shouldIncludeUrl(filePath, options.includePatterns, options.excludePatterns);\n }\n\n // Fallback: check if unknown extension has text/* MIME type using MimeTypeUtils\n const mimeType = MimeTypeUtils.detectMimeTypeFromPath(filePath);\n if (mimeType?.startsWith(\"text/\")) {\n logger.debug(`Including file with text MIME type: ${filePath} (${mimeType})`);\n return shouldIncludeUrl(filePath, options.includePatterns, options.excludePatterns);\n }\n\n // Not a text file\n return false;\n }\n\n /**\n * Checks if a path is within the specified subpath.\n */\n private isWithinSubPath(path: string, subPath?: string): boolean {\n if (!subPath) {\n return true;\n }\n\n const trimmedSubPath = subPath.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n if (trimmedSubPath.length === 0) {\n return true;\n }\n\n const normalizedPath = path.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n if (normalizedPath === trimmedSubPath) {\n return true;\n }\n\n return normalizedPath.startsWith(`${trimmedSubPath}/`);\n }\n\n /**\n * Replaces a GitHub API auth failure with a message naming the likely cause.\n *\n * Keyed off the response status rather than the message text, which embeds\n * the API url — a repo named e.g. \"error-403\" would otherwise make every\n * failure for it read as access denied.\n *\n * GitHub answers a rate limit with 403 rather than 429, so 403 deliberately\n * covers both permissions and rate limiting here.\n *\n * @param error The error the fetch threw.\n * @param owner Repository owner, for the message.\n * @param repo Repository name, for the message.\n * @throws A {@link ScraperError} when the status identifies an auth failure.\n */\n private rethrowAsGitHubAuthError(error: unknown, owner: string, repo: string): void {\n // HttpFetcher raises ChallengeError rather than HttpStatusError for a 403\n // carrying Cloudflare challenge markers, and it carries a status too.\n if (!(error instanceof HttpStatusError || error instanceof ChallengeError)) {\n return;\n }\n const { statusCode } = error;\n if (statusCode === 401) {\n throw new ScraperError(\n `GitHub authentication failed for \"${owner}/${repo}\". Your token is invalid or expired. Please check your GITHUB_TOKEN or GH_TOKEN environment variable.`,\n false,\n error,\n );\n }\n if (statusCode === 403) {\n throw new ScraperError(\n `GitHub access denied for \"${owner}/${repo}\". Your token may lack the required permissions, or you may be rate-limited. Please check your GITHUB_TOKEN or GH_TOKEN.`,\n false,\n error,\n );\n }\n }\n\n /**\n * Measures scope from the repository root rather than the URL the scrape\n * started from.\n *\n * A `/tree/<branch>` URL names a branch, but the files discovered under it\n * live at `/blob/<branch>/...` and the wiki at `/wiki`, so measured from the\n * tree URL the default `subpages` scope rejects every one of them.\n *\n * @param options Scraper options naming the GitHub URL the scrape started from.\n * @returns The repository root URL.\n */\n protected override getScopeBaseUrl(options: ScraperOptions): URL {\n const { owner, repo } = this.parseGitHubUrl(options.url);\n return new URL(`/${owner}/${repo}`, options.url);\n }\n\n async processItem(\n item: QueueItem,\n options: ScraperOptions,\n signal?: AbortSignal,\n ): Promise<ProcessItemResult> {\n // Handle legacy github-file:// URLs - treat as deleted/not found\n if (item.url.startsWith(\"github-file://\")) {\n logger.info(\n `🗑️ Legacy github-file:// URL detected, marking as deleted: ${item.url}`,\n );\n return {\n url: item.url,\n links: [],\n status: FetchStatus.NOT_FOUND,\n };\n }\n\n const headers = await this.getResolvedAuthHeaders(options.headers);\n\n // Delegate to wiki processor for wiki URLs\n // Use precise pattern matching: /owner/repo/wiki or /owner/repo/wiki/\n try {\n const parsedUrl = new URL(item.url);\n if (/^\\/[^/]+\\/[^/]+\\/wiki($|\\/)/.test(parsedUrl.pathname)) {\n return await this.wikiProcessor.process(item, options, headers, signal);\n }\n } catch {\n // If URL parsing fails, fall through to other handlers\n }\n\n // For the main repository URL (depth 0), perform discovery\n if (item.depth === 0) {\n const repoInfo = this.parseGitHubUrl(options.url);\n const { owner, repo } = repoInfo;\n\n // A single file (blob) URL is scoped strictly to that file, so the root\n // item is the file itself. Returning its URL as a link instead would\n // index nothing: the crawl has already marked the root URL as visited.\n if (repoInfo.isBlob && repoInfo.filePath) {\n logger.debug(\n `Single file URL detected: ${owner}/${repo}/${repoInfo.filePath} - indexing file only`,\n );\n return await this.repoProcessor.process(item, options, headers, signal);\n }\n\n logger.debug(`Discovering GitHub repository ${owner}/${repo}`);\n\n const discoveredLinks: string[] = [];\n\n // The wiki belongs to the repository, not to a branch, so it is built\n // from the repository root: appended to a tree URL it would name\n // nothing. A scrape narrowed to a directory leaves the wiki out.\n if (!repoInfo.subPath) {\n const wikiUrl = new URL(`/${owner}/${repo}/wiki`, options.url).href;\n discoveredLinks.push(wikiUrl);\n logger.debug(`Discovered wiki URL: ${wikiUrl}`);\n }\n\n // 3. Discover all files in the repository\n const { tree, resolvedBranch } = await this.fetchRepositoryTree(\n repoInfo,\n headers,\n signal,\n );\n\n const fileItems = tree.tree\n .filter((treeItem) => this.isWithinSubPath(treeItem.path, repoInfo.subPath))\n .filter((treeItem) => this.shouldProcessFile(treeItem, options));\n\n logger.debug(\n `Discovered ${fileItems.length} processable files in repository (branch: ${resolvedBranch})`,\n );\n\n // Create HTTPS blob URLs for storage in database\n // These are user-friendly, clickable URLs that work outside the system\n const fileUrls = fileItems.map(\n (treeItem) =>\n `https://github.com/${owner}/${repo}/blob/${resolvedBranch}/${treeItem.path}`,\n );\n\n discoveredLinks.push(...fileUrls);\n\n logger.debug(\n `Discovery complete: ${fileUrls.length} repo file(s), ${discoveredLinks.length} total URLs`,\n );\n\n // The repository or tree URL only lists what to index; it is not a page.\n return {\n url: item.url,\n links: discoveredLinks,\n isContainer: true,\n status: FetchStatus.SUCCESS,\n };\n }\n\n // Handle HTTPS blob URLs at depth > 0 (from database during refresh or discovered files)\n // Process blob URLs directly - fetch content and return empty links\n // Use precise pattern matching: /owner/repo/blob/branch/path\n try {\n const parsedUrl = new URL(item.url);\n if (/^\\/[^/]+\\/[^/]+\\/blob\\//.test(parsedUrl.pathname)) {\n logger.debug(`Processing HTTPS blob URL at depth ${item.depth}: ${item.url}`);\n return await this.repoProcessor.process(item, options, headers, signal);\n }\n } catch (error) {\n logger.warn(`⚠️ Failed to parse blob URL ${item.url}: ${error}`);\n return { url: item.url, links: [], status: FetchStatus.SUCCESS };\n }\n\n // Neither a file nor a wiki page, so nothing this strategy indexes. Older\n // versions stored such URLs, such as a wiki URL appended to a tree URL, and\n // reporting them as gone lets a refresh remove them.\n logger.debug(`Not a GitHub file or wiki page at depth ${item.depth}: ${item.url}`);\n return { url: item.url, links: [], status: FetchStatus.NOT_FOUND };\n }\n\n async scrape(\n options: ScraperOptions,\n progressCallback: ProgressCallback<ScraperProgressEvent>,\n signal?: AbortSignal,\n ): Promise<void> {\n const url = new URL(options.url);\n if (!url.hostname.includes(\"github.com\")) {\n throw new Error(\"URL must be a GitHub URL\");\n }\n\n await this.getResolvedAuthHeaders(options.headers);\n\n // Use the base class implementation which handles initialQueue properly\n // The processItem method will discover all wiki and repo file URLs\n // The base scraper will automatically deduplicate URLs from initialQueue\n try {\n await super.scrape(options, progressCallback, signal);\n } finally {\n this.resolvedAuthHeaders = undefined;\n this.resolvedAuthKey = undefined;\n }\n }\n\n async cleanup(): Promise<void> {\n await Promise.all([this.wikiProcessor.cleanup(), this.repoProcessor.cleanup()]);\n }\n}\n","import fs from \"node:fs\";\nimport { Readable } from \"node:stream\";\nimport * as tar from \"tar\";\nimport type { ArchiveAdapter, ArchiveEntry } from \"./types\";\n\nexport class TarAdapter implements ArchiveAdapter {\n private filePath: string;\n\n constructor(filePath: string) {\n this.filePath = filePath;\n }\n\n async *listEntries(): AsyncGenerator<ArchiveEntry> {\n const fileStream = fs.createReadStream(this.filePath);\n const parseStream = new tar.Parser();\n\n fileStream.pipe(parseStream);\n\n const entryStream = new Readable({ objectMode: true, read() {} });\n\n parseStream.on(\"entry\", (entry: tar.ReadEntry) => {\n const isDir = entry.type === \"Directory\";\n const path = entry.path;\n const size = entry.size;\n\n entryStream.push({\n path,\n type: isDir ? \"directory\" : \"file\",\n size,\n } as ArchiveEntry);\n\n // Important: resume to skip data so we get next entry\n entry.resume();\n });\n\n parseStream.on(\"end\", () => entryStream.push(null));\n parseStream.on(\"error\", (err: Error) => entryStream.destroy(err));\n fileStream.on(\"error\", (err: Error) => entryStream.destroy(err));\n\n try {\n for await (const entry of entryStream) {\n yield entry as ArchiveEntry;\n }\n } finally {\n fileStream.destroy();\n }\n }\n\n async getContent(path: string): Promise<Buffer> {\n const stream = await this.getStream(path);\n const chunks: Buffer[] = [];\n for await (const chunk of stream) {\n chunks.push(Buffer.from(chunk));\n }\n return Buffer.concat(chunks);\n }\n\n async getStream(path: string): Promise<Readable> {\n return new Promise((resolve, reject) => {\n const fileStream = fs.createReadStream(this.filePath);\n const parseStream = new tar.Parser();\n let found = false;\n\n parseStream.on(\"entry\", (entry: tar.ReadEntry) => {\n if (found) {\n entry.resume();\n return;\n }\n\n // Normalize paths? Tar paths often relative.\n // Check for exact match or ./ match\n if (\n entry.path === path ||\n entry.path === `./${path}` ||\n entry.path === path.replace(/^\\//, \"\")\n ) {\n found = true;\n // We return the entry as a Readable stream\n resolve(entry as unknown as Readable);\n } else {\n entry.resume();\n }\n });\n\n parseStream.on(\"end\", () => {\n if (!found) reject(new Error(`File not found in tar: ${path}`));\n });\n\n parseStream.on(\"error\", (err: Error) => {\n fileStream.destroy();\n reject(err);\n });\n fileStream.on(\"error\", (err: Error) => {\n // parseStream.destroy() might not exist on all versions or types,\n // but fileStream is the source.\n // @ts-expect-error\n if (typeof parseStream.destroy === \"function\") parseStream.destroy();\n reject(err);\n });\n\n fileStream.pipe(parseStream);\n });\n }\n\n async close(): Promise<void> {\n return Promise.resolve();\n }\n}\n","import { Readable } from \"node:stream\";\nimport yauzl from \"yauzl\";\nimport type { ArchiveAdapter, ArchiveEntry } from \"./types\";\n\nexport class ZipAdapter implements ArchiveAdapter {\n private zipfile: yauzl.ZipFile | null = null;\n private filePath: string;\n\n constructor(filePath: string) {\n this.filePath = filePath;\n }\n\n private async getZipFile(): Promise<yauzl.ZipFile> {\n if (this.zipfile) return this.zipfile;\n\n return new Promise((resolve, reject) => {\n yauzl.open(\n this.filePath,\n { lazyEntries: true, autoClose: false },\n (err, zipfile) => {\n if (err) return reject(err);\n if (!zipfile) return reject(new Error(\"Failed to open zip file\"));\n this.zipfile = zipfile;\n resolve(zipfile);\n },\n );\n });\n }\n\n async *listEntries(): AsyncGenerator<ArchiveEntry> {\n // Ensure we start fresh\n if (this.zipfile) {\n this.zipfile.close();\n this.zipfile = null;\n }\n const z = await this.getZipFile();\n\n const entryStream = new Readable({\n objectMode: true,\n read() {\n z.readEntry();\n },\n });\n\n z.on(\"entry\", (entry: yauzl.Entry) => {\n const isDir = entry.fileName.endsWith(\"/\");\n entryStream.push({\n path: entry.fileName,\n type: isDir ? \"directory\" : \"file\",\n size: entry.uncompressedSize,\n } as ArchiveEntry);\n });\n\n z.on(\"end\", () => {\n entryStream.push(null);\n });\n\n z.on(\"error\", (err) => {\n entryStream.destroy(err);\n });\n\n for await (const entry of entryStream) {\n yield entry as ArchiveEntry;\n }\n }\n\n async getContent(path: string): Promise<Buffer> {\n const stream = await this.getStream(path);\n const chunks: Buffer[] = [];\n for await (const chunk of stream) {\n chunks.push(Buffer.from(chunk));\n }\n return Buffer.concat(chunks);\n }\n\n async getStream(path: string): Promise<Readable> {\n // Let's implement a cache of entries on first load.\n if (!this.entriesCache) {\n await this.loadEntries();\n }\n\n const entry = this.entriesCache?.get(path);\n if (!entry) {\n throw new Error(`File not found in zip: ${path}`);\n }\n\n const z = await this.getZipFile();\n return new Promise((resolve, reject) => {\n z.openReadStream(entry, (err, readStream) => {\n if (err) return reject(err);\n if (!readStream) return reject(new Error(\"Failed to create read stream\"));\n resolve(readStream);\n });\n });\n }\n\n private entriesCache: Map<string, yauzl.Entry> | null = null;\n\n private async loadEntries(): Promise<void> {\n if (this.entriesCache) return;\n this.entriesCache = new Map();\n\n // Ensure clean state\n if (this.zipfile) {\n this.zipfile.close();\n this.zipfile = null;\n }\n const z = await this.getZipFile();\n\n return new Promise((resolve, reject) => {\n z.on(\"entry\", (entry: yauzl.Entry) => {\n this.entriesCache?.set(entry.fileName, entry);\n z.readEntry();\n });\n z.on(\"end\", () => resolve());\n z.on(\"error\", (err) => reject(err));\n z.readEntry();\n });\n }\n\n async close(): Promise<void> {\n if (this.zipfile) {\n this.zipfile.close();\n this.zipfile = null;\n }\n this.entriesCache = null;\n }\n}\n","import path from \"node:path\";\nimport { TarAdapter } from \"./TarAdapter\";\nimport type { ArchiveAdapter } from \"./types\";\nimport { ZipAdapter } from \"./ZipAdapter\";\n\n/**\n * Returns an appropriate archive adapter for the given file path based on its\n * extension, or `null` if the file is not a recognized archive format.\n *\n * Detection relies exclusively on file extensions (`.zip`, `.tar`, `.gz`,\n * `.tgz`). Magic byte inspection is intentionally omitted because many\n * document formats (DOCX, XLSX, PPTX, EPUB, ODT, ODS, ODP) are internally\n * ZIP archives sharing the same `PK` signature. Treating them as archives\n * would prevent proper document extraction via `DocumentPipeline`.\n */\nexport async function getArchiveAdapter(\n filePath: string,\n): Promise<ArchiveAdapter | null> {\n const ext = path.extname(filePath).toLowerCase();\n\n if (ext === \".zip\") {\n return new ZipAdapter(filePath);\n }\n if (ext === \".tar\" || ext === \".gz\" || ext === \".tgz\") {\n return new TarAdapter(filePath);\n }\n\n return null;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { ScraperAccessPolicy } from \"../../utils/accessPolicy\";\nimport { type ArchiveAdapter, getArchiveAdapter } from \"../../utils/archive\";\nimport type { AppConfig } from \"../../utils/config\";\nimport { logger } from \"../../utils/logger\";\nimport { MimeTypeUtils } from \"../../utils/mimeTypeUtils\";\nimport { FileFetcher } from \"../fetcher\";\nimport { FetchStatus, type RawContent } from \"../fetcher/types\";\nimport { PipelineFactory } from \"../pipelines/PipelineFactory\";\nimport type { ContentPipeline, PipelineResult } from \"../pipelines/types\";\nimport type { QueueItem, ScraperOptions } from \"../types\";\nimport { BaseScraperStrategy, type ProcessItemResult } from \"./BaseScraperStrategy\";\n\n/**\n * Orders two names by Unicode code point, which is the byte order of their\n * UTF-8 encoding, so the result is the same on every platform and locale.\n */\nfunction compareCodePoints(a: string, b: string): number {\n return Buffer.compare(Buffer.from(a), Buffer.from(b));\n}\n\n/**\n * LocalFileStrategy handles crawling and scraping of local files and folders using file:// URLs.\n *\n * Files are routed to the appropriate pipeline based on their detected MIME type:\n * `text/*` content (HTML, Markdown, plain text, source code such as `.js`/`.ts`/`.tsx`/`.css`)\n * is handled by the text/HTML/Markdown/source-code pipelines, while binary documents\n * (PDF, Office, OpenDocument, RTF, eBooks, Jupyter notebooks) are handled by the\n * `DocumentPipeline`. Other binary formats (images, etc.) fall through unprocessed\n * and are logged as unsupported.\n *\n * Supports include/exclude filters and percent-encoded paths.\n */\nexport class LocalFileStrategy extends BaseScraperStrategy {\n private readonly fileFetcher: FileFetcher;\n private readonly pipelines: ContentPipeline[];\n private readonly accessPolicy: ScraperAccessPolicy;\n\n constructor(config: AppConfig) {\n super(config);\n this.fileFetcher = new FileFetcher(config.scraper);\n this.pipelines = PipelineFactory.createStandardPipelines(config);\n this.accessPolicy = new ScraperAccessPolicy(config.scraper.security);\n }\n\n async processItem(\n item: QueueItem,\n options: ScraperOptions,\n _signal?: AbortSignal,\n ): Promise<ProcessItemResult> {\n const resolvedAccess = await this.accessPolicy.resolveFileAccess(\n item.url,\n options.internalAllowedFileRoots,\n );\n const filePath = resolvedAccess.filePath;\n\n let stats: Awaited<ReturnType<typeof fs.stat>> | null = null;\n let archivePath: string | null = null;\n let innerPath: string | null = null;\n let archiveAdapter: ArchiveAdapter | null = null;\n\n try {\n try {\n stats = await fs.stat(filePath);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\" || code === \"ENOTDIR\") {\n // File not found or path component is not a directory (maybe archive traversal)\n // Check if it's a virtual path inside an archive\n const resolved = await this.resolveVirtualPath(filePath);\n if (resolved.archive && resolved.inner && resolved.adapter) {\n archivePath = resolved.archive;\n innerPath = resolved.inner;\n archiveAdapter = resolved.adapter;\n } else {\n logger.info(`✓ File deleted or not available: ${filePath}`);\n return {\n url: item.url,\n links: [],\n status: FetchStatus.NOT_FOUND,\n };\n }\n } else {\n throw error;\n }\n }\n\n // Handle physical directory\n if (stats?.isDirectory()) {\n // Pages get their row ids in crawl order, which search uses to break\n // score ties. fs.readdir happens to return names in byte order on\n // macOS and Linux but in NTFS order (case-insensitive) on Windows, and\n // Node promises neither, so sort explicitly to crawl the same way on\n // every platform.\n const contents = (await fs.readdir(filePath)).sort(compareCodePoints);\n const visibleContents = this.config.scraper.security.fileAccess.includeHidden\n ? contents\n : contents.filter((name) => !name.startsWith(\".\"));\n // Only return links that pass shouldProcessUrl\n const linkEntries = await Promise.all(\n visibleContents.map(async (name) => {\n const entryPath = path.join(filePath, name);\n if (!this.config.scraper.security.fileAccess.followSymlinks) {\n const entryStats = await fs.lstat(entryPath).catch(() => null);\n if (entryStats?.isSymbolicLink()) {\n return null;\n }\n }\n\n // Construct valid file URL using URL class to ensure proper encoding and structure\n const url = new URL(`file://${entryPath.replace(/\\\\/g, \"/\")}`);\n // Ensure we always have file:/// format (empty host)\n if (url.hostname !== \"\") {\n url.pathname = `/${url.hostname}${url.pathname}`;\n url.hostname = \"\";\n }\n\n return url.href;\n }),\n );\n const links = linkEntries\n .filter((url): url is string => Boolean(url))\n .filter((url) => {\n const allowed = this.shouldProcessUrl(url, options);\n if (!allowed) {\n logger.debug(`Skipping out-of-scope link: ${url}`);\n }\n return allowed;\n });\n\n logger.debug(\n `Found ${links.length} files in ${filePath} (from ${visibleContents.length} entries)`,\n );\n return { url: item.url, links, isContainer: true, status: FetchStatus.SUCCESS };\n }\n\n // Check if the file itself is an archive (Root Archive)\n if (stats?.isFile()) {\n const adapter = await getArchiveAdapter(filePath);\n if (adapter) {\n logger.info(`📦 Detected archive file: ${filePath}`);\n try {\n const links: string[] = [];\n for await (const entry of adapter.listEntries()) {\n // Validate entry path to prevent Zip Slip\n if (entry.path.includes(\"..\")) {\n logger.warn(`⚠️ Skipping unsafe archive entry path: ${entry.path}`);\n continue;\n }\n\n // Create virtual URL: file:///path/to/archive.zip/entry/path\n // Ensure entry path doesn't start with / to avoid double slash issues\n const entryPath = entry.path.replace(/^\\//, \"\");\n\n // Normalize windows separators if any in entry path (rare in standard zips but possible in display)\n const fullVirtualPath = path.join(filePath, entryPath).replace(/\\\\/g, \"/\");\n const virtualUrl = new URL(`file://${fullVirtualPath}`);\n if (virtualUrl.hostname !== \"\") {\n virtualUrl.pathname = `/${virtualUrl.hostname}${virtualUrl.pathname}`;\n virtualUrl.hostname = \"\";\n }\n\n if (\n this.shouldProcessUrl(virtualUrl.href, options) &&\n this.isVisibleArchiveEntry(entry.path)\n ) {\n links.push(virtualUrl.href);\n }\n }\n logger.debug(`Found ${links.length} entries in archive ${filePath}`);\n return {\n url: item.url,\n links,\n isContainer: true,\n status: FetchStatus.SUCCESS,\n };\n } catch (err) {\n logger.error(`❌ Failed to list archive ${filePath}: ${err}`);\n // Treat as binary file or fail?\n // If listing fails, maybe just fall through to standard processing (which will likely ignore it)\n } finally {\n await adapter.close();\n }\n }\n }\n\n // Handle Virtual Archive Path (inner file)\n if (archivePath && innerPath && archiveAdapter) {\n // Validate inner path for Zip Slip\n if (innerPath.includes(\"..\")) {\n logger.warn(`⚠️ Detected unsafe virtual path traversal: ${innerPath}`);\n return {\n url: item.url,\n links: [],\n status: FetchStatus.NOT_FOUND,\n };\n }\n return await this.processArchiveEntry(\n item,\n archivePath,\n innerPath,\n archiveAdapter,\n options,\n );\n }\n\n const rawContent: RawContent = await this.fileFetcher.fetch(item.url, {\n etag: item.etag,\n });\n\n // Handle NOT_MODIFIED status (file hasn't changed)\n if (rawContent.status === FetchStatus.NOT_MODIFIED) {\n logger.debug(`✓ File unchanged: ${filePath}`);\n return { url: rawContent.source, links: [], status: FetchStatus.NOT_MODIFIED };\n }\n\n return await this.processContent(item.url, filePath, rawContent, options);\n } finally {\n if (archiveAdapter) {\n await archiveAdapter.close();\n }\n }\n }\n\n /**\n * Resolves a path that might be inside an archive.\n * Returns the archive path and the inner path if found.\n */\n private async resolveVirtualPath(fullPath: string): Promise<{\n archive: string | null;\n inner: string | null;\n adapter: ArchiveAdapter | null;\n }> {\n let currentPath = fullPath;\n while (\n currentPath !== \"/\" &&\n currentPath !== \".\" &&\n path.dirname(currentPath) !== currentPath\n ) {\n const dirname = path.dirname(currentPath);\n\n try {\n const stats = await fs.stat(currentPath);\n if (stats.isFile()) {\n // Found a file part of the path. Check if it is an archive.\n const adapter = await getArchiveAdapter(currentPath);\n if (adapter) {\n // We return the OPEN adapter to avoid reopening it\n const inner = fullPath\n .substring(currentPath.length)\n .replace(/^\\/+/, \"\")\n .replace(/^\\\\+/, \"\");\n return { archive: currentPath, inner, adapter };\n }\n }\n // If it exists and is not an archive (or is a dir), then the path is just wrong/missing\n // because we started from a full path that didn't exist (ENOENT), and walked up.\n // If we hit a real directory or real file that isn't an archive, we stop.\n return { archive: null, inner: null, adapter: null };\n } catch (_e) {\n // Path segment doesn't exist, go up\n currentPath = dirname;\n }\n }\n return { archive: null, inner: null, adapter: null };\n }\n\n private isVisibleArchiveEntry(entryPath: string): boolean {\n if (this.config.scraper.security.fileAccess.includeHidden) {\n return true;\n }\n\n return !entryPath\n .split(/[\\\\/]+/)\n .filter(Boolean)\n .some((segment) => segment.startsWith(\".\"));\n }\n\n private async processArchiveEntry(\n item: QueueItem,\n archivePath: string,\n innerPath: string,\n adapter: ArchiveAdapter,\n options: ScraperOptions,\n ): Promise<ProcessItemResult> {\n logger.debug(`Reading archive entry: ${innerPath} inside ${archivePath}`);\n\n try {\n const contentBuffer = await adapter.getContent(innerPath);\n\n // Detect mime type based on inner filename using MimeTypeUtils for consistent detection\n const mimeType =\n MimeTypeUtils.detectMimeTypeFromPath(innerPath) || \"application/octet-stream\";\n\n const rawContent: RawContent = {\n source: item.url,\n content: contentBuffer,\n mimeType,\n status: FetchStatus.SUCCESS,\n lastModified: new Date().toISOString(), // Archive entries don't easily give mod time in generic way, defaulting\n etag: undefined, // Could hash content?\n };\n\n return this.processContent(\n item.url,\n `${archivePath}/${innerPath}`,\n rawContent,\n options,\n );\n } catch (err) {\n logger.warn(\n `⚠️ Failed to read archive entry \"${innerPath}\" from archive \"${archivePath}\": ${err}`,\n );\n console.error(`DEBUG ERROR: ${err}`); // Force output to console\n return {\n url: item.url,\n links: [],\n status: FetchStatus.NOT_FOUND,\n };\n }\n }\n\n private async processContent(\n _url: string,\n displayPath: string,\n rawContent: RawContent,\n options: ScraperOptions,\n ): Promise<ProcessItemResult> {\n let processed: PipelineResult | undefined;\n\n for (const pipeline of this.pipelines) {\n if (pipeline.canProcess(rawContent.mimeType, rawContent.content)) {\n logger.debug(\n `Selected ${pipeline.constructor.name} for content type \"${rawContent.mimeType}\" (${displayPath})`,\n );\n processed = await pipeline.process(rawContent, options, this.fileFetcher);\n break;\n }\n }\n\n if (!processed) {\n logger.warn(\n `⚠️ Unsupported content type \"${rawContent.mimeType}\" for file ${displayPath}. Skipping processing.`,\n );\n return { url: rawContent.source, links: [], status: FetchStatus.SKIPPED };\n }\n\n for (const err of processed.errors ?? []) {\n logger.warn(`⚠️ Processing error for ${displayPath}: ${err.message}`);\n }\n\n // Use filename as fallback if title is empty or not a string\n const filename = path.basename(displayPath);\n const title = processed.title?.trim() || filename || null;\n\n // For local files, we don't follow links (no crawling within file content)\n // Return empty links array\n return {\n url: rawContent.source,\n title: title,\n etag: rawContent.etag,\n lastModified: rawContent.lastModified,\n sourceContentType: rawContent.mimeType,\n contentType: processed.contentType || rawContent.mimeType,\n content: processed,\n links: [],\n status: FetchStatus.SUCCESS,\n };\n }\n\n /**\n * Cleanup resources used by this strategy, specifically the pipeline browser instances.\n */\n async cleanup(): Promise<void> {\n await Promise.allSettled(this.pipelines.map((pipeline) => pipeline.close()));\n }\n}\n","import type { ContentPipeline } from \"./types\";\n\n/**\n * Answers whether the configured content pipelines can process a given MIME type.\n */\nexport type MimeTypeCapabilityPredicate = (mimeType: string) => boolean;\n\n/**\n * Builds the single predicate used to decide whether content is worth fetching.\n *\n * The answer is derived from the pipelines themselves rather than from a list, so\n * support for a format is declared in exactly one place: the relevant pipeline's\n * `canProcess()`. Adding a pipeline widens every crawl gate automatically, and no\n * gate may hardcode extensions or MIME strings of its own.\n *\n * The predicate is evaluated without content, which makes it at least as permissive\n * as the pipeline-selection loop that later runs with content available. A resource\n * the predicate accepts may still be refused by a pipeline; a resource it rejects\n * would not have been accepted by any.\n *\n * @param pipelines The pipeline set whose capabilities define processability.\n * @returns A predicate that reports whether some pipeline claims the MIME type.\n */\nexport function createMimeTypeCapabilityPredicate(\n pipelines: ContentPipeline[],\n): MimeTypeCapabilityPredicate {\n return (mimeType: string): boolean =>\n pipelines.some((pipeline) => pipeline.canProcess(mimeType));\n}\n","/**\n * Web scraper strategy that normalizes URLs, fetches content with automatic\n * fetcher selection, and routes content through pipelines. Requires resolved\n * configuration from the entrypoint to avoid implicit config loading.\n */\nimport fsPromises from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport type { ProgressCallback } from \"../../types\";\nimport type { AppConfig } from \"../../utils/config\";\nimport { logger } from \"../../utils/logger\";\nimport { MimeTypeUtils } from \"../../utils/mimeTypeUtils\";\nimport {\n normalizeUrl,\n stripMarkdownExtension,\n type UrlNormalizerOptions,\n} from \"../../utils/url\";\nimport { AutoDetectFetcher, ManagedBrowser } from \"../fetcher\";\nimport { FetchStatus, type RawContent } from \"../fetcher/types\";\nimport {\n createMimeTypeCapabilityPredicate,\n type MimeTypeCapabilityPredicate,\n} from \"../pipelines/capability\";\nimport { PipelineFactory } from \"../pipelines/PipelineFactory\";\nimport type { ContentPipeline, PipelineResult } from \"../pipelines/types\";\nimport type { QueueItem, ScraperOptions, ScraperProgressEvent } from \"../types\";\nimport { convertToString } from \"../utils/buffer\";\nimport { isLlmsTxtUrl, type LlmsTxtResult, parseLlmsTxt } from \"../utils/llmsTxtParser\";\nimport { isFileLikePath, isPathDescendant } from \"../utils/scope\";\nimport { BaseScraperStrategy, type ProcessItemResult } from \"./BaseScraperStrategy\";\nimport { LocalFileStrategy } from \"./LocalFileStrategy\";\n\nexport interface WebScraperStrategyOptions {\n urlNormalizerOptions?: UrlNormalizerOptions;\n shouldFollowLink?: (baseUrl: URL, targetUrl: URL) => boolean;\n}\n\n/**\n * Matches paths naming an archive we know how to unpack.\n *\n * This is a policy statement, not a capability one, which is why it is not\n * expressed through the pipeline capability predicate: archives are readable —\n * `processRootArchive` unpacks one when it is the start URL — but following them\n * mid-crawl is deliberately declined. The two call sites act on the same test in\n * opposite directions, so they share this helper rather than the literal.\n *\n * @param pathname The URL pathname to test.\n * @returns True when the path names a supported archive.\n */\nfunction isArchivePath(pathname: string): boolean {\n return /\\.(zip|tar|gz|tgz)$/i.test(pathname);\n}\n\ninterface LlmsTxtProbeResult {\n url: string;\n result: LlmsTxtResult;\n}\n\nexport class WebScraperStrategy extends BaseScraperStrategy {\n private readonly fetcher: AutoDetectFetcher;\n private readonly shouldFollowLinkFn?: (baseUrl: URL, targetUrl: URL) => boolean;\n private readonly pipelines: ContentPipeline[];\n private readonly canProcessMimeType: MimeTypeCapabilityPredicate;\n private readonly localFileStrategy: LocalFileStrategy;\n private tempFiles: string[] = [];\n private siblingwiseRedirectWarned = false;\n private pendingLlmsTxtProbe: LlmsTxtProbeResult | null = null;\n\n constructor(config: AppConfig, options: WebScraperStrategyOptions = {}) {\n super(config, { urlNormalizerOptions: options.urlNormalizerOptions });\n this.shouldFollowLinkFn = options.shouldFollowLink;\n // The browser fallback and the HTML renderer share one Chromium.\n const managedBrowser = new ManagedBrowser(config.scraper);\n this.fetcher = new AutoDetectFetcher(config.scraper, managedBrowser);\n this.pipelines = PipelineFactory.createStandardPipelines(config, managedBrowser);\n this.canProcessMimeType = createMimeTypeCapabilityPredicate(this.pipelines);\n this.localFileStrategy = new LocalFileStrategy(config);\n }\n\n private restorePreservedHash(requestedUrl: string, actualUrl: string): string {\n if (!requestedUrl.includes(\"#\")) {\n return actualUrl;\n }\n\n try {\n const requested = new URL(requestedUrl);\n const actual = new URL(actualUrl);\n const normalizePathname = (pathname: string): string =>\n pathname.length > 1 ? pathname.replace(/\\/+$/, \"\") : pathname;\n if (\n requested.origin === actual.origin &&\n normalizePathname(requested.pathname) === normalizePathname(actual.pathname) &&\n requested.search === actual.search\n ) {\n actual.hash = requested.hash;\n return actual.toString();\n }\n } catch {\n return actualUrl;\n }\n\n return actualUrl;\n }\n\n // Removed custom isInScope logic; using shared scope utility for consistent behavior\n\n private createFetchOptions(\n item: QueueItem,\n options: ScraperOptions,\n signal?: AbortSignal,\n ) {\n return {\n signal,\n followRedirects: options.followRedirects,\n headers: options.headers,\n etag: item.etag,\n // Fetch-time gate. The fetcher stays ignorant of pipelines; it is simply\n // told what this strategy is able to read.\n acceptsMimeType: this.canProcessMimeType,\n ...(item.internalAllowedFileRoots\n ? { internalAllowedFileRoots: item.internalAllowedFileRoots }\n : {}),\n };\n }\n\n private buildMarkdownVariantUrl(url: string): string {\n const variant = new URL(url);\n if (variant.pathname.endsWith(\"/\")) {\n variant.pathname = `${variant.pathname}index.html.md`;\n return variant.toString();\n }\n\n const lastSegment = variant.pathname.split(\"/\").at(-1) ?? \"\";\n if (lastSegment.includes(\".\")) {\n variant.pathname = `${variant.pathname}.md`;\n return variant.toString();\n }\n\n variant.pathname = `${variant.pathname}/index.html.md`;\n return variant.toString();\n }\n\n /**\n * Records a web page under its canonical URL.\n *\n * Web URLs are the case the shared normaliser was written for: a server\n * returns the same bytes for `/config` and `/config/`, and for a directory and\n * its index file, so those spellings name one page.\n */\n protected override canonicalizeStoredUrl(\n url: string,\n scrapeOptions: ScraperOptions,\n ): string {\n return normalizeUrl(url, this.getUrlNormalizerOptions(scrapeOptions));\n }\n\n /**\n * Restates an accepted Markdown variant's content type as Markdown.\n *\n * Sites disagree on how to serve a `.md` file: vite.dev sends `text/markdown`,\n * react.dev sends `text/plain`. Both are Markdown documents, so both are\n * parsed and recorded as Markdown — the extension is the author's statement\n * about the format, and the plain-text pipeline would throw away every\n * heading. Markdown is close enough to a superset of plain text that a file\n * using none of its syntax still comes through intact.\n *\n * `text/plain` is not treated as a weaker signal than HTML. It was, briefly,\n * to stop a plain-text soft error page outranking the page it folds onto —\n * but the hosts that soft-404 a `.md` URL answer `200 text/markdown` with a\n * `# Page Not Found` body (ai-sdk.dev, nextjs.org), so that rule caught none\n * of them, while react.dev — the `text/plain` host — returns a real 404.\n * It cost the published Markdown of every such site and bought nothing.\n * Soft-error detection needs to read the body, and belongs elsewhere.\n */\n private asMarkdownRepresentation(url: string, rawContent: RawContent): RawContent {\n if (!this.isMarkdownUrl(url) || !this.isAcceptableMarkdownVariant(rawContent)) {\n return rawContent;\n }\n return MimeTypeUtils.isMarkdown(rawContent.mimeType)\n ? rawContent\n : { ...rawContent, mimeType: \"text/markdown\" };\n }\n\n private isAcceptableMarkdownVariant(rawContent: RawContent): boolean {\n const mimeType = rawContent.mimeType.toLowerCase();\n return MimeTypeUtils.isMarkdown(mimeType) || mimeType === \"text/plain\";\n }\n\n private isMarkdownUrl(url: string): boolean {\n // Pathname only, for the reason `canProcessDiscoveredLink` documents: given a\n // whole URL the detector reads the host's suffix as an extension, and `.md`\n // is Moldova's ccTLD, so `https://example.md/` would report as Markdown.\n let pathname: string;\n try {\n pathname = new URL(url).pathname;\n } catch {\n return false;\n }\n const mimeType = MimeTypeUtils.detectMimeTypeFromPath(pathname);\n return mimeType ? MimeTypeUtils.isMarkdown(mimeType) : false;\n }\n\n /**\n * Resolves the page identity for a fetched resource.\n *\n * A published Markdown file is a representation of a page rather than a page of\n * its own, so `guide.md` is recorded as `guide`. Both signals are required and\n * they answer different questions: the extension states what the author meant\n * the URL to be, the response states what the server actually returned. The\n * extension alone would fold a soft 404 or an HTML page onto an identity it\n * does not serve; the response alone would rewrite the identity of a document\n * that is legitimately its own resource.\n *\n * Being a property of the response, the rule needs no knowledge of how the URL\n * was discovered or of what else the crawl has seen — which is what lets an\n * `llms.txt` entry and a crawled link converge without ordering guarantees.\n *\n * @param url The URL the content was fetched from, after redirects.\n * @param rawContent The response, consulted for its resolved MIME type.\n * @returns The canonical page URL.\n */\n private resolvePageIdentity(url: string, rawContent: RawContent): string {\n if (!this.isMarkdownUrl(url) || !this.isAcceptableMarkdownVariant(rawContent)) {\n return url;\n }\n const canonical = stripMarkdownExtension(url);\n if (canonical !== url) {\n logger.debug(`Markdown variant ${url} recorded as ${canonical}`);\n }\n return canonical;\n }\n\n /**\n * Queue-time gate: rejects a discovered link whose path extension names binary\n * media that no configured pipeline can process, before any request is made.\n *\n * Two conditions must both hold, and they answer different questions. The binary\n * media check decides how far to trust an extension; the capability predicate\n * decides what can be processed. Keeping them separate means adding an image\n * pipeline still widens this gate automatically, while a `.csh` or `.tcl` file the\n * `mime` package files under `application/*` is never rejected on its name alone.\n *\n * A null detection means \"no opinion\" — the link is admitted so the fetch-time\n * gate can decide against the server's actual `Content-Type`. That covers\n * extensionless URLs, unknown extensions, and paths whose only dots sit in a\n * directory segment.\n *\n * @param targetUrl The resolved absolute URL of the discovered link.\n * @returns True when the link should continue through the remaining filters.\n */\n private canProcessDiscoveredLink(targetUrl: URL): boolean {\n const mimeType = MimeTypeUtils.detectMimeTypeFromPath(targetUrl.pathname);\n const isUnreadableMedia =\n !!mimeType &&\n MimeTypeUtils.isBinaryMediaType(mimeType) &&\n !this.canProcessMimeType(mimeType);\n\n if (!isUnreadableMedia) {\n return true;\n }\n logger.debug(`Skipping ${targetUrl.href}: ${mimeType} is not processable`);\n return false;\n }\n\n private async fetchItemContent(\n item: QueueItem,\n options: ScraperOptions,\n signal?: AbortSignal,\n ): Promise<RawContent> {\n const fetchOptions = this.createFetchOptions(item, options, signal);\n\n if (!item.fromLlmsTxt || this.isMarkdownUrl(item.url)) {\n return await this.fetcher.fetch(item.url, fetchOptions);\n }\n\n const markdownVariantUrl = this.buildMarkdownVariantUrl(item.url);\n try {\n const markdownContent = await this.fetcher.fetch(markdownVariantUrl, fetchOptions);\n if (\n markdownContent.status === FetchStatus.SUCCESS &&\n this.isAcceptableMarkdownVariant(markdownContent)\n ) {\n logger.debug(\n `llms.txt Markdown URL preference succeeded: ${item.url} -> ${markdownVariantUrl}`,\n );\n return markdownContent;\n }\n\n logger.debug(\n `llms.txt Markdown URL preference fell back for ${item.url}: ${markdownVariantUrl} returned status=${markdownContent.status}, contentType=${markdownContent.mimeType}`,\n );\n } catch (error) {\n logger.debug(\n `llms.txt Markdown URL preference fell back for ${item.url}: ${error}`,\n );\n }\n\n return this.fetcher.fetch(item.url, fetchOptions);\n }\n\n private getLlmsTxtCandidates(baseUrl: string, inputUrl: string): string[] {\n const llmsTxtAt = (base: string, pathname: string): string => {\n const url = new URL(base);\n url.pathname = pathname.replace(/\\/+/g, \"/\");\n url.search = \"\";\n url.hash = \"\";\n return url.toString();\n };\n\n const { pathname } = new URL(inputUrl);\n // Direct subpath candidate (e.g. /paymob-docs -> /paymob-docs/llms.txt).\n // Only for directory-like paths: appending to a file name (/docs/page.html)\n // would probe /docs/page.html/llms.txt, which is a guaranteed 404.\n // Appending to a file name (/docs/page.html, /docs/index) would probe a\n // guaranteed 404, so only directory-like paths get the subpath candidate.\n const isDirectoryLike = !isFileLikePath(pathname);\n // Parent path candidate (e.g. /docs/v1/page.html -> /docs/v1/llms.txt)\n const parentPath = pathname.endsWith(\"/\")\n ? pathname\n : pathname.slice(0, pathname.lastIndexOf(\"/\") + 1);\n\n return [\n ...new Set([\n ...(isDirectoryLike\n ? [llmsTxtAt(inputUrl, `${pathname.replace(/\\/+$/, \"\")}/llms.txt`)]\n : []),\n llmsTxtAt(inputUrl, `${parentPath}llms.txt`),\n llmsTxtAt(baseUrl, \"/llms.txt\"),\n ]),\n ];\n }\n\n /**\n * Probes for an llms.txt file using the existing fetcher and access policy.\n * @param baseUrl The site base URL used for the root fallback probe.\n * @param inputUrl The original input URL used for the subpath probe.\n * @param options Scraper options to apply to probe requests.\n * @param signal Optional abort signal.\n * @returns The first valid llms.txt result, or null when none is available.\n */\n async probeLlmsTxt(\n baseUrl: string,\n inputUrl: string,\n options: ScraperOptions,\n signal?: AbortSignal,\n ): Promise<LlmsTxtProbeResult | null> {\n for (const candidate of this.getLlmsTxtCandidates(baseUrl, inputUrl)) {\n try {\n const { acceptsMimeType: _gate, ...probeOptions } = this.createFetchOptions(\n { url: candidate, depth: 0 },\n options,\n signal,\n );\n const rawContent = await this.fetcher.fetch(candidate, probeOptions);\n if (rawContent.status !== FetchStatus.SUCCESS) {\n logger.debug(`llms.txt probe failed for ${candidate}: ${rawContent.status}`);\n continue;\n }\n\n const result = parseLlmsTxt(\n convertToString(rawContent.content, rawContent.charset),\n );\n if (result.links.length === 0) {\n logger.debug(`llms.txt probe failed for ${candidate}: invalid content`);\n continue;\n }\n\n logger.info(\n `📄 Detected llms.txt at ${rawContent.source} (${result.links.length} URLs)`,\n );\n return { url: rawContent.source, result };\n } catch (error) {\n logger.debug(`llms.txt probe failed for ${candidate}: ${error}`);\n }\n }\n\n return null;\n }\n\n private createLlmsTxtQueueItems(\n options: ScraperOptions,\n probe: LlmsTxtProbeResult,\n ): QueueItem[] {\n const items: QueueItem[] = [];\n\n for (const link of probe.result.links) {\n try {\n const targetUrl = new URL(link.url, probe.url);\n if (targetUrl.protocol !== \"http:\" && targetUrl.protocol !== \"https:\") {\n continue;\n }\n // Seeds go through the same admission checks as discovered links: an\n // image or archive listed in llms.txt should be rejected at queue time\n // rather than fetched and then discarded.\n if (isArchivePath(targetUrl.pathname)) {\n continue;\n }\n if (!this.canProcessDiscoveredLink(targetUrl)) {\n continue;\n }\n if (!this.shouldProcessUrl(targetUrl.href, options)) {\n continue;\n }\n if (this.shouldFollowLinkFn) {\n const baseUrl = this.canonicalBaseUrl ?? new URL(options.url);\n if (!this.shouldFollowLinkFn(baseUrl, targetUrl)) {\n continue;\n }\n }\n items.push({ url: targetUrl.href, depth: 0, fromLlmsTxt: true });\n } catch {}\n }\n\n return items;\n }\n\n private consumePendingLlmsTxtQueueItems(\n item: QueueItem,\n options: ScraperOptions,\n ): QueueItem[] {\n if (item.depth !== 0) {\n return [];\n }\n\n const probe = this.pendingLlmsTxtProbe;\n this.pendingLlmsTxtProbe = null;\n\n return probe ? this.createLlmsTxtQueueItems(options, probe) : [];\n }\n\n private updateCanonicalBaseUrl(effectiveSource: string, options: ScraperOptions): void {\n // Protocol and host are always adopted from the redirected URL so cross-origin redirects\n // (http->https, apex<->www, port changes) don't drop every discovered link via the host check.\n // Keep the user-provided path as the scope anchor: callers who start at `/docs` expect the\n // whole docs subtree even when the server redirects that index URL to a concrete page.\n const final = new URL(effectiveSource);\n const userPath = new URL(options.url).pathname;\n if (!isPathDescendant(userPath, final.pathname) && !this.siblingwiseRedirectWarned) {\n logger.warn(\n `⚠️ Depth-0 redirect changed path siblingwise. Scope anchor remains the user-provided path; ` +\n `discovered links under the redirected path will not be in scope. ` +\n `Requested: ${options.url} → Final: ${effectiveSource} → Scope anchor: ${userPath}. ` +\n `If the redirected path is intended, resubmit with that URL.`,\n );\n this.siblingwiseRedirectWarned = true;\n }\n final.pathname = userPath;\n this.canonicalBaseUrl = final;\n }\n\n /**\n * Processes a single queue item by fetching its content and processing it through pipelines.\n * @param item - The queue item to process.\n * @param options - Scraper options including headers for HTTP requests.\n * @param _progressCallback - Optional progress callback (not used here).\n * @param signal - Optional abort signal for request cancellation.\n * @returns An object containing the processed document and extracted links.\n */\n protected override async processItem(\n item: QueueItem,\n options: ScraperOptions,\n signal?: AbortSignal,\n ): Promise<ProcessItemResult> {\n const { url } = item;\n\n try {\n if (isLlmsTxtUrl(url)) {\n logger.debug(`Skipping llms.txt meta-file: ${url}`);\n return { url, links: [], status: FetchStatus.SUCCESS };\n }\n\n // Log when processing with ETag for conditional requests\n if (item.etag) {\n logger.debug(`Processing ${url} with stored ETag: ${item.etag}`);\n }\n\n // Check for Archive Root URL (only the user's actual requested root)\n if (this.isRequestedRoot(item, options)) {\n if (isArchivePath(new URL(url).pathname)) {\n return this.processRootArchive(item, options, signal);\n }\n }\n\n // Use AutoDetectFetcher which handles fallbacks automatically\n const fetched = await this.fetchItemContent(item, options, signal);\n const fetchedSource = options.preserveHashes\n ? this.restorePreservedHash(url, fetched.source)\n : fetched.source;\n // Judged on where the bytes came from, not on where we asked: a redirect\n // from an extensionless URL to a `.md` resource is still a published\n // Markdown representation, and the queued URL would hide that. Applied\n // here rather than per fetch path so every route reaching this point —\n // including the llms.txt variant fallback — is covered by one rule.\n const rawContent = this.asMarkdownRepresentation(fetchedSource, fetched);\n // A Markdown variant is recorded under the page it represents, so a `.md`\n // URL and its canonical form resolve to one identity however each was found.\n const effectiveSource = this.resolvePageIdentity(fetchedSource, rawContent);\n if (this.isRequestedRoot(item, options)) {\n this.updateCanonicalBaseUrl(effectiveSource, options);\n }\n const llmsTxtQueueItems = this.consumePendingLlmsTxtQueueItems(item, options);\n\n logger.debug(\n `Fetch result for ${url}: status=${rawContent.status}, etag=${rawContent.etag || \"none\"}`,\n );\n\n // Return the status directly - BaseScraperStrategy handles NOT_MODIFIED and NOT_FOUND\n // Use the final URL from rawContent.source (which may differ due to redirects)\n if (rawContent.status !== FetchStatus.SUCCESS) {\n logger.debug(`Skipping pipeline for ${url} due to status: ${rawContent.status}`);\n return {\n url: effectiveSource,\n links: [],\n queueItems: llmsTxtQueueItems,\n // Carried so a fatal skip at the requested root can name the type that\n // caused it. Null for 304 and 404, whose MIME type describes nothing.\n sourceContentType: rawContent.mimeType ?? null,\n status: rawContent.status,\n };\n }\n\n if (MimeTypeUtils.isMarkdown(rawContent.mimeType)) {\n logger.debug(\n `Server provided Markdown content for ${url} via content negotiation or Markdown URL (${rawContent.mimeType})`,\n );\n }\n\n // --- Start Pipeline Processing ---\n let processed: PipelineResult | undefined;\n for (const pipeline of this.pipelines) {\n const contentBuffer = Buffer.isBuffer(rawContent.content)\n ? rawContent.content\n : Buffer.from(rawContent.content);\n if (pipeline.canProcess(rawContent.mimeType || \"text/plain\", contentBuffer)) {\n logger.debug(\n `Selected ${pipeline.constructor.name} for content type \"${rawContent.mimeType}\" (${url})`,\n );\n processed = await pipeline.process(\n { ...rawContent, source: effectiveSource },\n options,\n this.fetcher,\n );\n break;\n }\n }\n\n if (!processed) {\n // If content type is unsupported (e.g. binary/archive encountered during crawl), we just skip\n logger.warn(\n `⚠️ Unsupported content type \"${rawContent.mimeType}\" for URL ${url}. Skipping processing.`,\n );\n return {\n url: effectiveSource,\n links: [],\n queueItems: llmsTxtQueueItems,\n sourceContentType: rawContent.mimeType ?? null,\n // Skipped, not empty: nothing read the body, so we cannot claim the\n // page has no content — and a refresh must not erase what is stored.\n status: FetchStatus.SKIPPED,\n };\n }\n\n // Log errors from pipeline\n for (const err of processed.errors ?? []) {\n logger.warn(`⚠️ Processing error for ${url}: ${err.message}`);\n }\n\n // Check if content processing resulted in usable content\n if (!processed.textContent?.trim()) {\n const pipelineFailed = (processed.errors?.length ?? 0) > 0;\n logger.warn(\n `⚠️ No processable content found for ${url} after pipeline execution.`,\n );\n return {\n url: effectiveSource,\n // Recorded here as well as on the non-empty return: an empty page\n // still has a retrieval location, and the base strategy's fallback\n // cannot recover it once the identity has moved — it compares the\n // identity with itself and finds no divergence. Without this the row\n // stores NULL and the next refresh asks the identity while sending\n // the validator the Markdown file issued.\n contentUrl: effectiveSource === fetchedSource ? undefined : fetchedSource,\n title: processed.title ?? null,\n sourceContentType: rawContent.mimeType,\n contentType: processed.contentType || rawContent.mimeType,\n etag: rawContent.etag,\n lastModified: rawContent.lastModified,\n links: processed.links,\n queueItems: llmsTxtQueueItems,\n // A clean run that extracted nothing means the page is empty. An errored\n // run means we learned nothing about it, which is a different fact and\n // gets different handling downstream.\n pipelineFailed,\n status: FetchStatus.SUCCESS,\n };\n }\n\n const filteredLinks =\n processed.links?.flatMap((link) => {\n try {\n const targetUrl = new URL(link, effectiveSource);\n\n // Archives are readable but deliberately not followed mid-crawl.\n // This is policy, so it stays separate from the capability gate below.\n if (isArchivePath(targetUrl.pathname)) {\n return [];\n }\n\n // Reject links whose extension names content no pipeline can read, before\n // any request is issued. Detection is deliberately given the pathname only:\n // passing the href would let a host like `example.zip` or `example.mov`\n // resolve to an archive or video MIME type off its TLD.\n if (!this.canProcessDiscoveredLink(targetUrl)) {\n return [];\n }\n\n // Use the base class's shouldProcessUrl which handles scope + include/exclude patterns\n if (!this.shouldProcessUrl(targetUrl.href, options)) {\n return [];\n }\n // Apply optional custom filter function if provided\n if (this.shouldFollowLinkFn) {\n const baseUrl = this.canonicalBaseUrl ?? new URL(options.url);\n return this.shouldFollowLinkFn(baseUrl, targetUrl) ? [targetUrl.href] : [];\n }\n return [targetUrl.href];\n } catch {\n return [];\n }\n }) ?? [];\n\n return {\n url: effectiveSource,\n // Recorded only when the bytes came from somewhere other than the\n // page's identity, so a later refresh requests that representation and\n // the validator below goes back to the resource that issued it. Equal\n // values would claim a divergence that does not exist.\n contentUrl: effectiveSource === fetchedSource ? undefined : fetchedSource,\n etag: rawContent.etag,\n lastModified: rawContent.lastModified,\n sourceContentType: rawContent.mimeType,\n contentType: processed.contentType || rawContent.mimeType,\n content: processed,\n links: filteredLinks,\n queueItems: llmsTxtQueueItems,\n status: FetchStatus.SUCCESS,\n };\n } catch (error) {\n // Log fetch errors or pipeline execution errors (if run throws)\n logger.error(`❌ Failed processing page ${url}: ${error}`);\n throw error;\n }\n }\n\n async scrape(\n options: ScraperOptions,\n progressCallback: ProgressCallback<ScraperProgressEvent>,\n signal?: AbortSignal,\n ): Promise<void> {\n this.pendingLlmsTxtProbe = null;\n this.pendingLlmsTxtProbe = await this.probeLlmsTxt(\n options.url,\n options.url,\n options,\n signal,\n );\n\n await super.scrape(options, progressCallback, signal);\n }\n\n private async processRootArchive(\n item: QueueItem,\n options: ScraperOptions,\n signal?: AbortSignal,\n ): Promise<ProcessItemResult> {\n logger.info(`📦 Downloading root archive: ${item.url}`);\n\n // We need to stream the download to a temp file\n // Since fetcher.fetch returns a buffer (usually), we might want to bypass it or use it if small enough?\n // But archives can be huge. fetcher.fetch currently loads into memory.\n // For now, let's assume we can use fetcher but warn about memory, OR implement stream download here.\n // Our fetcher abstraction returns RawContent with Buffer.\n // If we want to stream, we might need to access the underlying axios/fetch stream.\n // `AutoDetectFetcher` doesn't expose stream easily.\n // Ideally we refactor fetcher to support streams, but that's out of scope.\n // So we will use fetcher and write buffer to temp file.\n // LIMITATION: Large archives will hit memory limits.\n\n const rawContent = await this.fetcher.fetch(item.url, {\n signal,\n headers: options.headers,\n });\n\n if (rawContent.status !== FetchStatus.SUCCESS) {\n return { url: rawContent.source, links: [], status: rawContent.status };\n }\n\n const buffer = Buffer.isBuffer(rawContent.content)\n ? rawContent.content\n : Buffer.from(rawContent.content);\n\n const tempDir = os.tmpdir();\n const tempFile = path.join(\n tempDir,\n `scraper-${Date.now()}-${path.basename(new URL(item.url).pathname)}`,\n );\n\n // Track file immediately so we can clean it up if write fails or later\n this.tempFiles.push(tempFile);\n\n await fsPromises.writeFile(tempFile, buffer);\n\n // Delegate to LocalFileStrategy\n const localUrl = `file://${tempFile}`;\n const localItem = { ...item, url: localUrl };\n const localOptions = {\n ...options,\n internalAllowedFileRoots: [...(options.internalAllowedFileRoots ?? []), tempFile],\n };\n\n const result = await this.localFileStrategy.processItem(\n localItem,\n localOptions,\n signal,\n );\n\n // We need to fix up the links to point back to something meaningful?\n // If we process a zip, we get file:///tmp/.../file.txt\n // These links are only useful if we continue to treat them as local files for this session.\n // But `WebScraper` expects http links usually?\n // Actually, if we return file:// links, the queue might try to fetch them.\n // `WebScraperStrategy` handles http/https. `LocalFileStrategy` handles file://.\n // If we return file:// links, the scraper will need to route them to `LocalFileStrategy`.\n // The `ScraperService` uses `ScraperRegistry` to pick strategy.\n // So file:// links will work!\n\n return {\n ...result,\n url: item.url, // Keep original URL as the source of this item\n links: result.links,\n internalAllowedFileRoots: [tempFile],\n // links are file://...\n };\n }\n\n /**\n * Cleanup resources used by this strategy, specifically the pipeline browser instances and fetcher.\n */\n async cleanup(): Promise<void> {\n await Promise.allSettled([\n ...this.pipelines.map((pipeline) => pipeline.close()),\n this.localFileStrategy.cleanup(),\n this.fetcher.close(),\n ...this.tempFiles.map((file) => fsPromises.unlink(file).catch(() => {})),\n ]);\n }\n}\n","import type { ProgressCallback } from \"../../types\";\nimport type { AppConfig } from \"../../utils/config\";\nimport type { ScraperOptions, ScraperProgressEvent, ScraperStrategy } from \"../types\";\nimport { WebScraperStrategy } from \"./WebScraperStrategy\";\n\nexport class NpmScraperStrategy implements ScraperStrategy {\n private defaultStrategy: WebScraperStrategy;\n\n constructor(config: AppConfig) {\n this.defaultStrategy = new WebScraperStrategy(config, {\n urlNormalizerOptions: {\n removeHash: true,\n removeTrailingSlash: true,\n removeQuery: true, // Enable removeQuery for NPM packages\n },\n });\n }\n\n async scrape(\n options: ScraperOptions,\n progressCallback: ProgressCallback<ScraperProgressEvent>,\n signal?: AbortSignal,\n ): Promise<void> {\n // Use default strategy with our configuration, passing the signal\n await this.defaultStrategy.scrape(options, progressCallback, signal);\n }\n\n /**\n * Cleanup resources used by this strategy.\n */\n async cleanup(): Promise<void> {\n await this.defaultStrategy.cleanup();\n }\n}\n","import type { ProgressCallback } from \"../../types\";\nimport type { AppConfig } from \"../../utils/config\";\nimport type { ScraperOptions, ScraperProgressEvent, ScraperStrategy } from \"../types\";\nimport { WebScraperStrategy } from \"./WebScraperStrategy\";\n\nexport class PyPiScraperStrategy implements ScraperStrategy {\n private defaultStrategy: WebScraperStrategy;\n\n constructor(config: AppConfig) {\n this.defaultStrategy = new WebScraperStrategy(config, {\n urlNormalizerOptions: {\n removeHash: true,\n removeTrailingSlash: true,\n removeQuery: true, // Enable removeQuery for PyPI packages\n },\n });\n }\n\n async scrape(\n options: ScraperOptions,\n progressCallback: ProgressCallback<ScraperProgressEvent>,\n signal?: AbortSignal,\n ): Promise<void> {\n // Use default strategy with our configuration, passing the signal\n await this.defaultStrategy.scrape(options, progressCallback, signal);\n }\n\n /**\n * Cleanup resources used by this strategy.\n */\n async cleanup(): Promise<void> {\n await this.defaultStrategy.cleanup();\n }\n}\n","import type { AppConfig } from \"../utils/config\";\nimport { ScraperError } from \"../utils/errors\";\nimport { logger } from \"../utils/logger\";\nimport { validateUrl } from \"../utils/url\";\nimport { GitHubScraperStrategy } from \"./strategies/GitHubScraperStrategy\";\nimport { LocalFileStrategy } from \"./strategies/LocalFileStrategy\";\nimport { NpmScraperStrategy } from \"./strategies/NpmScraperStrategy\";\nimport { PyPiScraperStrategy } from \"./strategies/PyPiScraperStrategy\";\nimport { WebScraperStrategy } from \"./strategies/WebScraperStrategy\";\nimport type { ScraperStrategy } from \"./types\";\n\n/**\n * Factory for creating scraper strategy instances.\n * Each call to getStrategy() returns a fresh instance to ensure\n * parallel scrape jobs have completely isolated state.\n */\nexport class ScraperRegistry {\n private config: AppConfig;\n\n constructor(config: AppConfig) {\n this.config = config;\n }\n\n /**\n * Creates and returns a fresh strategy instance for the given URL.\n * Each call returns a new instance to ensure state isolation between parallel scrapes.\n */\n getStrategy(url: string): ScraperStrategy {\n if (!url.startsWith(\"github-file://\")) {\n validateUrl(url);\n }\n\n // Check each strategy type without instantiating heavy objects.\n // Order matters: more specific strategies should come before generic ones.\n\n if (isLocalFileUrl(url)) {\n logger.debug(`Using strategy \"LocalFileStrategy\" for URL: ${url}`);\n return new LocalFileStrategy(this.config);\n }\n\n if (isNpmUrl(url)) {\n logger.debug(`Using strategy \"NpmScraperStrategy\" for URL: ${url}`);\n return new NpmScraperStrategy(this.config);\n }\n\n if (isPyPiUrl(url)) {\n logger.debug(`Using strategy \"PyPiScraperStrategy\" for URL: ${url}`);\n return new PyPiScraperStrategy(this.config);\n }\n\n if (isGitHubUrl(url)) {\n logger.debug(`Using strategy \"GitHubScraperStrategy\" for URL: ${url}`);\n return new GitHubScraperStrategy(this.config);\n }\n\n if (isWebUrl(url)) {\n logger.debug(`Using strategy \"WebScraperStrategy\" for URL: ${url}`);\n return new WebScraperStrategy(this.config, {});\n }\n\n throw new ScraperError(`No strategy found for URL: ${url}`);\n }\n}\n\nfunction isLocalFileUrl(url: string): boolean {\n return url.startsWith(\"file://\");\n}\n\nfunction isNpmUrl(url: string): boolean {\n try {\n const { hostname } = new URL(url);\n return [\"npmjs.org\", \"npmjs.com\", \"www.npmjs.com\"].includes(hostname);\n } catch {\n return false;\n }\n}\n\nfunction isPyPiUrl(url: string): boolean {\n try {\n const { hostname } = new URL(url);\n return [\"pypi.org\", \"www.pypi.org\"].includes(hostname);\n } catch {\n return false;\n }\n}\n\nfunction isGitHubUrl(url: string): boolean {\n if (url.startsWith(\"github-file://\")) {\n return true;\n }\n\n try {\n const parsedUrl = new URL(url);\n const { hostname, pathname } = parsedUrl;\n\n if (![\"github.com\", \"www.github.com\"].includes(hostname)) {\n return false;\n }\n\n if (pathname.match(/^\\/[^/]+\\/[^/]+\\/?$/)) {\n return true;\n }\n\n if (pathname.match(/^\\/[^/]+\\/[^/]+\\/tree\\//)) {\n return true;\n }\n\n if (pathname.match(/^\\/[^/]+\\/[^/]+\\/blob\\//)) {\n return true;\n }\n\n return false;\n } catch {\n return false;\n }\n}\n\nfunction isWebUrl(url: string): boolean {\n try {\n const parsedUrl = new URL(url);\n return parsedUrl.protocol === \"http:\" || parsedUrl.protocol === \"https:\";\n } catch {\n return false;\n }\n}\n","import type { ProgressCallback } from \"../types\";\nimport { ScraperError } from \"../utils/errors\";\nimport { logger } from \"../utils/logger\";\nimport type { ScraperRegistry } from \"./ScraperRegistry\";\nimport type { ScraperOptions, ScraperProgressEvent } from \"./types\";\n\n/**\n * Orchestrates document scraping operations using registered scraping strategies.\n * Automatically selects appropriate strategy based on URL patterns.\n * Each scrape operation uses a fresh strategy instance for state isolation.\n */\nexport class ScraperService {\n private registry: ScraperRegistry;\n\n constructor(registry: ScraperRegistry) {\n this.registry = registry;\n }\n\n /**\n * Scrapes content from the provided URL using the appropriate strategy.\n * Reports progress via callback and handles errors.\n * Cleans up strategy resources after scrape completes (success or failure).\n */\n async scrape(\n options: ScraperOptions,\n progressCallback: ProgressCallback<ScraperProgressEvent>,\n signal?: AbortSignal,\n ): Promise<void> {\n // Get a fresh strategy instance for this scrape (factory pattern)\n const strategy = this.registry.getStrategy(options.url);\n\n let scrapeError: Error | null = null;\n let cleanupErrorToThrow: Error | null = null;\n try {\n // Pass the signal down to the strategy\n await strategy.scrape(options, progressCallback, signal);\n } catch (error) {\n scrapeError =\n error instanceof Error\n ? error\n : new ScraperError(`Scrape failed for URL: ${options.url}`, false);\n } finally {\n // Always cleanup strategy resources after scrape completes\n // This releases browser instances, temp files, etc.\n try {\n await strategy.cleanup?.();\n } catch (cleanupError) {\n logger.error(`❌ Strategy cleanup failed for ${options.url}: ${cleanupError}`);\n if (!scrapeError) {\n cleanupErrorToThrow =\n cleanupError instanceof Error\n ? cleanupError\n : new ScraperError(\n `Strategy cleanup failed for URL: ${options.url}`,\n false,\n );\n }\n }\n }\n\n if (scrapeError) {\n throw scrapeError;\n }\n\n if (cleanupErrorToThrow) {\n throw cleanupErrorToThrow;\n }\n }\n}\n","import type { ScraperService } from \"../scraper\";\nimport {\n PageOutcome,\n type ScrapeResult,\n type ScraperProgressEvent as ScraperProgress,\n type ScraperProgressEvent,\n} from \"../scraper/types\";\nimport type { DocumentManagementService } from \"../store\";\nimport { EmbeddingError } from \"../store/errors\";\nimport { logger } from \"../utils/logger\";\nimport { CancellationError } from \"./errors\";\nimport type { InternalPipelineJob } from \"./types\";\n\n/**\n * Internal callbacks used by PipelineWorker.\n * These work with InternalPipelineJob before conversion to public interface.\n */\ninterface WorkerCallbacks {\n onJobProgress?: (job: InternalPipelineJob, progress: ScraperProgress) => Promise<void>;\n onJobError?: (\n job: InternalPipelineJob,\n error: Error,\n page?: ScrapeResult,\n ) => Promise<void>;\n onJobStatusChange?: (job: InternalPipelineJob) => Promise<void>;\n}\n\n/**\n * Executes a single document processing job.\n * Handles scraping, storing documents, and reporting progress/errors via callbacks.\n */\nexport class PipelineWorker {\n // Dependencies are passed in, making the worker stateless regarding specific jobs\n private readonly store: DocumentManagementService;\n private readonly scraperService: ScraperService;\n\n // Constructor accepts dependencies needed for execution\n constructor(store: DocumentManagementService, scraperService: ScraperService) {\n this.store = store;\n this.scraperService = scraperService;\n }\n\n /**\n * Executes the given pipeline job.\n * @param job - The job to execute.\n * @param callbacks - Internal callbacks provided by the manager for reporting.\n */\n async executeJob(job: InternalPipelineJob, callbacks: WorkerCallbacks): Promise<void> {\n const { id: jobId, library, version, scraperOptions, abortController } = job;\n const signal = abortController.signal;\n\n logger.debug(`[${jobId}] Worker starting job for ${library}@${version}`);\n\n try {\n // Clear existing documents for this library/version before scraping\n // Skip this step for refresh operations or if clean is explicitly false\n if (!scraperOptions.isRefresh && scraperOptions.clean !== false) {\n await this.store.removeAllDocuments(library, version);\n logger.info(\n `💾 Cleared store for ${library}@${version || \"latest\"} before scraping.`,\n );\n } else {\n const message = scraperOptions.isRefresh\n ? `🔄 Refresh operation - preserving existing data for ${library}@${version || \"latest\"}.`\n : `💾 Appending to store for ${library}@${version || \"latest\"} (clean=false).`;\n logger.info(message);\n }\n\n // --- Core Job Logic ---\n await this.scraperService.scrape(\n scraperOptions,\n async (progress: ScraperProgressEvent) => {\n // Check for cancellation signal before processing each document\n if (signal.aborted) {\n throw new CancellationError(\"Job cancelled during scraping progress\");\n }\n\n // Update job object directly (manager holds the reference)\n // Report progress via manager's callback (single source of truth)\n await callbacks.onJobProgress?.(job, progress);\n\n // Branch on the reported outcome rather than inferring one from a null\n // result: `Unchanged` and `Empty` both arrive without content but mean\n // opposite things — one says keep what is stored, the other says the\n // page is now empty. The switch is exhaustive, so adding an outcome\n // becomes a compile error here rather than a silent no-op.\n switch (progress.outcome) {\n case PageOutcome.Empty:\n await this.recordEmptyPage(job, callbacks, library, version, progress);\n break;\n case PageOutcome.Absent:\n await this.removeDeletedPage(job, callbacks, progress);\n break;\n case PageOutcome.Stored:\n await this.storeResult(job, callbacks, library, version, progress);\n break;\n // Nothing to persist: unchanged content stays, a skipped resource was\n // never downloaded, and a failure has already been reported. Listed\n // explicitly so this reads as a decision rather than an omission.\n case PageOutcome.Unchanged:\n case PageOutcome.Skipped:\n case PageOutcome.Failed:\n break;\n default: {\n const unhandled: never = progress.outcome;\n logger.error(`❌ [${job.id}] Unhandled page outcome: ${unhandled}`);\n }\n }\n },\n signal, // Pass signal to scraper service\n );\n // --- End Core Job Logic ---\n\n // Check signal one last time after scrape finishes\n if (signal.aborted) {\n throw new CancellationError(\"Job cancelled\");\n }\n\n // If successful and not cancelled, the manager will handle status update\n logger.debug(`[${jobId}] Worker finished job successfully.`);\n } catch (error) {\n // Re-throw error to be caught by the manager in _runJob\n logger.warn(`⚠️ [${jobId}] Worker encountered error: ${error}`);\n throw error;\n }\n // Note: The manager (_runJob) is responsible for updating final job status (COMPLETED/FAILED/CANCELLED)\n // and resolving/rejecting the completion promise based on the outcome here.\n }\n\n /**\n * Records a page that exists but holds no content, replacing what was stored.\n *\n * When the pipeline failed rather than genuinely finding nothing, the stored\n * content is left alone: we learned nothing about the page, and overwriting it\n * would discard good content on a transient fault.\n */\n private async recordEmptyPage(\n job: InternalPipelineJob,\n callbacks: WorkerCallbacks,\n library: string,\n version: string,\n progress: ScraperProgressEvent,\n ): Promise<void> {\n const { emptyPage } = progress;\n if (!emptyPage) {\n // A container, not a page: nothing to record, and a row stored for it\n // by an older version is deleted.\n await this.removeDeletedPage(job, callbacks, progress);\n return;\n }\n\n if (emptyPage.pipelineFailed) {\n logger.debug(\n `[${job.id}] Extraction failed with no content, leaving stored page untouched: ${progress.currentUrl}`,\n );\n return;\n }\n\n try {\n // A redirect can move a refreshed page to a different URL, in which case\n // `pageId` names the old one and the by-URL cleanup would not reach it.\n // The store retires it as part of the same transaction that decides\n // whether this write lands: deleting it up front would erase a stronger\n // representation before anything could compare the two.\n await this.store.addEmptyPage(\n library,\n version,\n progress.depth,\n {\n url: emptyPage.url,\n contentUrl: emptyPage.contentUrl,\n title: emptyPage.title,\n sourceContentType: emptyPage.sourceContentType,\n contentType: emptyPage.contentType,\n etag: emptyPage.etag,\n lastModified: emptyPage.lastModified,\n isAdditionalRepresentation: emptyPage.isAdditionalRepresentation,\n },\n progress.pageId,\n );\n logger.debug(`[${job.id}] Stored empty page: ${progress.currentUrl}`);\n } catch (docError) {\n logger.error(\n `❌ [${job.id}] Failed to record empty page ${progress.currentUrl}: ${docError}`,\n );\n // Reported like the other persistence paths, so a job cannot complete\n // looking successful while its store write failed.\n await callbacks.onJobError?.(\n job,\n docError instanceof Error ? docError : new Error(String(docError)),\n );\n }\n }\n\n /**\n * Removes a page the source no longer serves.\n *\n * Only refresh items carry a `pageId`; a broken link found mid-crawl has\n * nothing stored to remove.\n */\n private async removeDeletedPage(\n job: InternalPipelineJob,\n callbacks: WorkerCallbacks,\n progress: ScraperProgressEvent,\n ): Promise<void> {\n if (!progress.deleted || !progress.pageId) return;\n\n try {\n await this.store.deletePage(progress.pageId);\n logger.debug(`[${job.id}] Deleted page ${progress.pageId}: ${progress.currentUrl}`);\n } catch (docError) {\n logger.error(\n `❌ [${job.id}] Failed to delete page ${progress.pageId}: ${docError}`,\n );\n const error = docError instanceof Error ? docError : new Error(String(docError));\n await callbacks.onJobError?.(job, error);\n // Deletion failures indicate serious database issues, and leaving orphaned\n // documents would compromise index accuracy.\n throw error;\n }\n }\n\n /**\n * Stores processed content, replacing the page's previous content on refresh.\n */\n private async storeResult(\n job: InternalPipelineJob,\n callbacks: WorkerCallbacks,\n library: string,\n version: string,\n progress: ScraperProgressEvent,\n ): Promise<void> {\n if (!progress.result) return;\n\n try {\n // The old row is retired inside the store's write transaction rather than\n // here. Deleting it first would hide it from the precedence check, so a\n // refresh that re-fetches both representations of one page would keep\n // whichever finished last instead of the better one.\n await this.store.addScrapeResult(\n library,\n version,\n progress.depth,\n progress.result,\n progress.pageId,\n );\n logger.debug(`[${job.id}] Stored processed content: ${progress.currentUrl}`);\n } catch (docError) {\n logger.error(\n `❌ [${job.id}] Failed to process content ${progress.currentUrl}: ${docError}`,\n );\n await callbacks.onJobError?.(\n job,\n docError instanceof Error ? docError : new Error(String(docError)),\n progress.result,\n );\n // A failed embedding usually means the provider is down or misconfigured,\n // so the remaining pages would fail too. The job fails at once instead of\n // completing with nothing stored. Any other error is logged and the job\n // continues.\n if (docError instanceof EmbeddingError) {\n throw docError;\n }\n }\n }\n}\n","/**\n * PipelineManager orchestrates a queue of scraping/indexing jobs.\n * - Controls concurrency, recovery, and job lifecycle\n * - Bridges in-memory job state with the persistent store\n * - Delegates execution to PipelineWorker and emits callbacks\n * Note: completionPromise has an attached no-op catch to avoid unhandled\n * promise rejection warnings when a job fails before a consumer awaits it.\n */\n\nimport { v4 as uuidv4 } from \"uuid\";\nimport type { EventBusService } from \"../events/EventBusService\";\nimport { EventType } from \"../events/types\";\nimport { ScraperRegistry, ScraperService } from \"../scraper\";\nimport type { ScraperOptions, ScraperProgressEvent } from \"../scraper/types\";\nimport { ScrapeMode } from \"../scraper/types\";\nimport type { DocumentManagementService } from \"../store\";\nimport { formatVersionLabel } from \"../store/errors\";\nimport {\n type DbVersionWithLibrary,\n libraryNamesMatch,\n msSinceWritten,\n normalizeLibraryName,\n normalizeVersionLabel,\n UPDATED_AT_RESOLUTION_MS,\n VersionStatus,\n} from \"../store/types\";\nimport type { AppConfig } from \"../utils/config\";\nimport { logger } from \"../utils/logger\";\nimport { CancellationError, PipelineStateError } from \"./errors\";\nimport { PipelineWorker } from \"./PipelineWorker\"; // Import the worker\nimport type { EnqueueScrapeOptions, IPipeline } from \"./trpc/interfaces\";\nimport type { InternalPipelineJob, InterruptedJobs, PipelineJob } from \"./types\";\nimport { PipelineJobStatus } from \"./types\";\n\n/** The states of a job that has ended; in any other, it may still write. */\nconst FINISHED_JOB_STATUSES: ReadonlySet<PipelineJobStatus> = new Set([\n PipelineJobStatus.COMPLETED,\n PipelineJobStatus.CANCELLED,\n PipelineJobStatus.FAILED,\n]);\n\n/**\n * How many heartbeats a job may miss before its version counts as interrupted.\n * Several, so a process whose event loop is busy for a while keeps its jobs.\n */\nconst HEARTBEATS_BEFORE_INTERRUPTED = 4;\n\n/** A version's label for logs, such as `react@18.0` or `react@latest`. */\nfunction labelOf(version: DbVersionWithLibrary): string {\n return formatVersionLabel(version.library_name, version.name ?? \"\");\n}\n\n/**\n * How long a RUNNING or QUEUED version may go unwritten before it counts as\n * interrupted.\n *\n * @param jobHeartbeatMs How often running jobs mark their version alive.\n * @returns The bound in milliseconds.\n */\nexport function interruptedAfterMs(jobHeartbeatMs: number): number {\n return HEARTBEATS_BEFORE_INTERRUPTED * jobHeartbeatMs + UPDATED_AT_RESOLUTION_MS;\n}\n\n/**\n * Manages a queue of document processing jobs, controlling concurrency and tracking progress.\n */\nexport class PipelineManager implements IPipeline {\n private jobMap: Map<string, InternalPipelineJob> = new Map();\n /** The last enqueue or removal per library version; see `withVersionLock`. */\n private readonly versionLocks = new Map<string, Promise<void>>();\n private jobQueue: string[] = [];\n private activeWorkers: Set<string> = new Set();\n private isRunning = false;\n private concurrency: number;\n private store: DocumentManagementService;\n private scraperService: ScraperService;\n private interruptedJobs: InterruptedJobs;\n private eventBus: EventBusService;\n private appConfig: AppConfig;\n /** Marks this manager's unfinished jobs alive while it runs. */\n private heartbeatTimer: NodeJS.Timeout | undefined;\n /** Decides on versions that were alive at start, once they could be silent. */\n private recheckTimer: NodeJS.Timeout | undefined;\n\n constructor(\n store: DocumentManagementService,\n eventBus: EventBusService,\n options: { interruptedJobs: InterruptedJobs; appConfig: AppConfig },\n ) {\n this.store = store;\n this.eventBus = eventBus;\n this.appConfig = options.appConfig;\n this.concurrency = this.appConfig.scraper.maxConcurrency;\n this.interruptedJobs = options.interruptedJobs;\n // ScraperService needs a registry. We create one internally for the manager.\n const registry = new ScraperRegistry(this.appConfig);\n this.scraperService = new ScraperService(registry);\n }\n\n /**\n * Converts internal job representation to public job interface.\n */\n private toPublicJob(job: InternalPipelineJob): PipelineJob {\n return {\n id: job.id,\n library: job.library,\n version: job.version || null, // Convert empty string to null for public API\n status: job.status,\n progress: job.progress,\n error: job.error ? { message: job.error.message } : null,\n createdAt: job.createdAt,\n startedAt: job.startedAt,\n finishedAt: job.finishedAt,\n versionId: job.versionId,\n versionStatus: job.versionStatus,\n progressPages: job.progressPages,\n progressPagesIndexed: job.progressPagesIndexed,\n progressMaxPages: job.progressMaxPages,\n errorMessage: job.errorMessage,\n updatedAt: job.updatedAt,\n sourceUrl: job.sourceUrl,\n scraperOptions: job.scraperOptions,\n };\n }\n\n private normalizeScraperOptions(options: ScraperOptions): ScraperOptions {\n const normalizedOptions: ScraperOptions = {\n ...options,\n scrapeMode: options.scrapeMode ?? ScrapeMode.Auto,\n preserveHashes: options.preserveHashes ?? this.appConfig.scraper.preserveHashes,\n };\n\n if (\n normalizedOptions.preserveHashes &&\n normalizedOptions.scrapeMode === ScrapeMode.Fetch\n ) {\n logger.warn(\n `⚠️ Upgrading scrape mode to '${ScrapeMode.Playwright}' for ${options.url} because preserved hash routes are incompatible with '${ScrapeMode.Fetch}'.`,\n );\n normalizedOptions.scrapeMode = ScrapeMode.Playwright;\n }\n\n return normalizedOptions;\n }\n\n /**\n * Starts the pipeline manager's worker processing.\n */\n async start(): Promise<void> {\n if (this.isRunning) {\n logger.warn(\"⚠️ PipelineManager is already running.\");\n return;\n }\n this.isRunning = true;\n logger.debug(\n `PipelineManager started with concurrency ${this.concurrency}, interrupted jobs: ${this.interruptedJobs}.`,\n );\n\n // Other processes on the store can tell this manager's jobs from interrupted ones\n this.heartbeatTimer = setInterval(\n () => void this.markJobsAlive(),\n this.appConfig.scraper.jobHeartbeatMs,\n ).unref();\n\n if (this.interruptedJobs !== \"leave\") {\n const recentlyWritten = await this.handleInterruptedJobs();\n if (recentlyWritten.length > 0) this.checkAgainLater(recentlyWritten);\n }\n\n this._processQueue().catch((error) => {\n logger.error(`❌ Error in processQueue during start: ${error}`);\n }); // Start processing any existing jobs\n }\n\n /** The jobs that have not ended and may still write to their version. */\n private unfinishedJobs(): InternalPipelineJob[] {\n return Array.from(this.jobMap.values()).filter(\n (job) => !FINISHED_JOB_STATUSES.has(job.status),\n );\n }\n\n /**\n * Marks the versions of this manager's unfinished jobs alive, so a server\n * starting on the same store leaves them alone. Logs a failed write.\n */\n private async markJobsAlive(): Promise<void> {\n const versionIds = this.unfinishedJobs().map((job) => job.versionId);\n if (versionIds.length === 0) return;\n try {\n await this.store.markVersionsAlive(versionIds);\n } catch (error) {\n logger.warn(`⚠️ Failed to mark running jobs alive: ${error}`);\n }\n }\n\n /**\n * Recovers or fails the RUNNING and QUEUED versions that nothing has written\n * within the bound, and returns those written more recently: they may belong\n * to a job another live process runs, which marks its version alive on every\n * heartbeat. The versions of this manager's own unfinished jobs are skipped.\n *\n * @param only Limits the check to these versions.\n * @returns The versions written within the bound; none when the check fails,\n * which it logs.\n */\n private async handleInterruptedJobs(\n only?: ReadonlySet<number>,\n ): Promise<DbVersionWithLibrary[]> {\n try {\n const ownVersionIds = new Set(this.unfinishedJobs().map((job) => job.versionId));\n const versions = (\n await this.store.getVersionsByStatus([\n VersionStatus.RUNNING,\n VersionStatus.QUEUED,\n ])\n ).filter(\n (version) =>\n !ownVersionIds.has(version.id) && (only === undefined || only.has(version.id)),\n );\n const now = Date.now();\n const bound = interruptedAfterMs(this.appConfig.scraper.jobHeartbeatMs);\n const interrupted: DbVersionWithLibrary[] = [];\n const recentlyWritten: DbVersionWithLibrary[] = [];\n for (const version of versions) {\n (msSinceWritten(version, now) >= bound ? interrupted : recentlyWritten).push(\n version,\n );\n }\n\n // An interrupted read is older than a second, so a claim changes updated_at\n // and another process acting on the same read finds nothing to claim\n const claimed: DbVersionWithLibrary[] = [];\n for (const version of interrupted) {\n if (await this.store.claimInterruptedVersion(version.id, version.updated_at)) {\n claimed.push(version);\n } else {\n logger.debug(`Leaving ${labelOf(version)}: another process took it over`);\n }\n }\n\n if (this.interruptedJobs === \"recover\") {\n await this.recoverPendingJobs(claimed);\n } else {\n await this.markInterruptedJobsAsFailed(claimed);\n }\n return recentlyWritten;\n } catch (error) {\n logger.error(`❌ Failed to handle interrupted jobs: ${error}`);\n return [];\n }\n }\n\n /**\n * Checks versions written shortly before start once more, when they could\n * have gone unwritten for the whole bound: a crashed process's versions are\n * handled then, and a live process's are left to it for good.\n */\n private checkAgainLater(versions: DbVersionWithLibrary[]): void {\n const bound = interruptedAfterMs(this.appConfig.scraper.jobHeartbeatMs);\n logger.debug(\n `Checking ${versions.length} recently written job(s) again in ${bound} ms`,\n );\n const ids = new Set(versions.map((version) => version.id));\n this.recheckTimer = setTimeout(async () => {\n for (const version of await this.handleInterruptedJobs(ids)) {\n logger.debug(`Leaving ${labelOf(version)} to the process that runs it`);\n }\n }, bound).unref();\n }\n\n /**\n * Recovers interrupted jobs. Uses enqueueRefreshJob() to properly continue\n * them, leveraging existing pages and ETags when available.\n */\n private async recoverPendingJobs(versions: DbVersionWithLibrary[]): Promise<void> {\n if (versions.length === 0) return;\n\n logger.info(`📥 Recovering ${versions.length} pending job(s) from database`);\n\n for (const version of versions) {\n const versionLabel = labelOf(version);\n try {\n // Use enqueueRefreshJob for recovery - it handles:\n // - Completed versions: incremental refresh with ETags\n // - Incomplete versions: falls back to enqueueJobWithStoredOptions()\n await this.enqueueRefreshJob(version.library_name, version.name);\n logger.info(`🔄 Recovering job: ${versionLabel}`);\n } catch (error) {\n // If recovery fails (e.g., no stored options), mark as failed\n const errorMessage = `Recovery failed: ${error instanceof Error ? error.message : String(error)}`;\n await this.store.updateVersionStatus(\n version.id,\n VersionStatus.FAILED,\n errorMessage,\n );\n logger.warn(`⚠️ Failed to recover job ${versionLabel}: ${error}`);\n }\n }\n }\n\n /** Marks interrupted jobs FAILED, so users can retry them via the UI. */\n private async markInterruptedJobsAsFailed(\n versions: DbVersionWithLibrary[],\n ): Promise<void> {\n for (const version of versions) {\n await this.store.updateVersionStatus(\n version.id,\n VersionStatus.FAILED,\n \"Job interrupted\",\n );\n logger.info(`❌ Marked interrupted job as failed: ${labelOf(version)}`);\n }\n }\n\n /**\n * Stops the pipeline manager and attempts to gracefully shut down workers.\n * Currently, it just stops processing new jobs. Cancellation of active jobs\n * needs explicit `cancelJob` calls.\n */\n async stop(): Promise<void> {\n if (!this.isRunning) {\n logger.warn(\"⚠️ PipelineManager is not running.\");\n return;\n }\n this.isRunning = false;\n clearInterval(this.heartbeatTimer);\n clearTimeout(this.recheckTimer);\n logger.debug(\"PipelineManager stopping. No new jobs will be started.\");\n\n // Note: Strategy cleanup now happens per-scrape in ScraperService.scrape()\n // No cleanup call needed here since strategies are not cached.\n\n // Note: Does not automatically cancel active jobs.\n }\n\n /**\n * Cancels a library version's unfinished jobs and waits until each has ended,\n * including one already being cancelled: it can still be storing its last\n * page, which would create the version again after a removal.\n *\n * The library name and the version are matched the way the store buckets\n * them: comparing names exactly let `Docs` and `docs` run as two jobs against\n * one bucket, where the second one's clean-before-scrape deleted pages the\n * first had already written.\n */\n private async stopJobsFor(library: string, normalizedVersion: string): Promise<void> {\n const jobs = this.unfinishedJobs().filter(\n (job) =>\n libraryNamesMatch(job.library, library) &&\n normalizeVersionLabel(job.version) === normalizedVersion,\n );\n for (const job of jobs) {\n logger.info(\n `🚫 Stopping job ${job.id} for ${formatVersionLabel(job.library, normalizedVersion)}`,\n );\n await this.cancelJob(job.id);\n // How the job ended does not matter, only that it no longer writes\n await this.waitForJobCompletion(job.id).catch(() => {});\n }\n }\n\n /**\n * Runs `work` once any earlier enqueue or removal of the same library version\n * has finished, so the two never interleave.\n */\n private async withVersionLock<T>(\n library: string,\n normalizedVersion: string,\n work: () => Promise<T>,\n ): Promise<T> {\n const key = `${normalizeLibraryName(library)}\\u0000${normalizedVersion}`;\n const previous = this.versionLocks.get(key) ?? Promise.resolve();\n const result = previous.then(work);\n const settled = result.then(\n () => {},\n () => {},\n );\n this.versionLocks.set(key, settled);\n try {\n return await result;\n } finally {\n if (this.versionLocks.get(key) === settled) {\n this.versionLocks.delete(key);\n }\n }\n }\n\n /**\n * Removes a library version once its jobs have stopped (see\n * {@link stopJobsFor}), and the library with its last version. A job enqueued\n * for the same version meanwhile is registered only after the removal is done.\n */\n async removeVersion(\n library: string,\n version: string | undefined | null,\n ): Promise<void> {\n const normalizedVersion = normalizeVersionLabel(version);\n await this.withVersionLock(library, normalizedVersion, async () => {\n await this.stopJobsFor(library, normalizedVersion);\n await this.store.removeVersion(library, version);\n });\n }\n\n /**\n * Enqueues a new document processing job.\n *\n * The target library and version are claimed first: by default an existing\n * version is rejected rather than cleared (`onExisting: \"reject-version\"`).\n * Only a claim that succeeds goes on to stop the version's other jobs (see\n * {@link stopJobsFor}), so none of them writes into it after the new job starts.\n *\n * @throws {LibraryAlreadyExistsError | VersionAlreadyExistsError} When the policy rejects the target.\n * @throws {InvalidLibraryNameError} When a new library's name fails validation.\n */\n async enqueueScrapeJob(\n library: string,\n version: string | undefined | null,\n options: ScraperOptions,\n enqueue: EnqueueScrapeOptions = {},\n ): Promise<string> {\n const normalizedVersion = normalizeVersionLabel(version);\n // A removal of this version cannot run between the claim and the job it\n // registers, so it either sees the job and cancels it, or runs first.\n return this.withVersionLock(library, normalizedVersion, () =>\n this.registerScrapeJob(library, normalizedVersion, options, enqueue),\n );\n }\n\n /**\n * Claims the library version and registers a job for it. Callers hold the\n * version's lock (see {@link withVersionLock}).\n */\n private async registerScrapeJob(\n library: string,\n normalizedVersion: string,\n options: ScraperOptions,\n enqueue: EnqueueScrapeOptions,\n ): Promise<string> {\n // Claim the target before touching any job, so a rejected request cannot\n // cancel the job it conflicts with. Appending clears nothing, so it is not an\n // overwrite and may write into an existing version.\n const requested = enqueue.onExisting ?? \"reject-version\";\n const policy =\n options.clean === false && requested === \"reject-version\" ? \"replace\" : requested;\n const claimed = await this.store.claimVersion(library, normalizedVersion, policy);\n\n await this.stopJobsFor(library, normalizedVersion);\n const label = formatVersionLabel(claimed.library, normalizedVersion);\n\n const normalizedOptions = this.normalizeScraperOptions(options);\n\n const jobId = uuidv4();\n const abortController = new AbortController();\n let resolveCompletion!: () => void;\n let rejectCompletion!: (reason?: unknown) => void;\n\n const completionPromise = new Promise<void>((resolve, reject) => {\n resolveCompletion = resolve;\n rejectCompletion = reject;\n });\n // Prevent unhandled rejection warnings if rejection occurs before consumers attach handlers\n completionPromise.catch(() => {});\n\n const job: InternalPipelineJob = {\n id: jobId,\n // The stored display name, not the caller's casing\n library: claimed.library,\n version: normalizedVersion,\n versionId: claimed.versionId,\n status: PipelineJobStatus.QUEUED,\n progress: null,\n error: null,\n createdAt: new Date(),\n startedAt: null,\n finishedAt: null,\n abortController,\n completionPromise,\n resolveCompletion,\n rejectCompletion,\n // Database fields (single source of truth)\n // Will be populated by updateJobStatus\n progressPages: 0,\n progressPagesIndexed: 0,\n progressMaxPages: 0,\n errorMessage: null,\n updatedAt: new Date(),\n sourceUrl: normalizedOptions.url,\n scraperOptions: normalizedOptions,\n };\n\n this.jobMap.set(jobId, job);\n this.jobQueue.push(jobId);\n logger.info(`📝 Job enqueued: ${jobId} for ${label}`);\n\n // Update database status to QUEUED\n await this.updateJobStatus(job, PipelineJobStatus.QUEUED);\n\n // Trigger processing if manager is running\n if (this.isRunning) {\n this._processQueue().catch((error) => {\n logger.error(`❌ Error in processQueue during enqueue: ${error}`);\n });\n }\n\n return jobId;\n }\n\n /**\n * Enqueues a refresh job for an existing library version by re-scraping all pages\n * and using ETag comparison to skip unchanged content.\n *\n * If the version was never completed (interrupted or failed scrape), performs a\n * full re-scrape from scratch instead of a refresh to ensure completeness.\n */\n async enqueueRefreshJob(\n library: string,\n version: string | undefined | null,\n options?: Pick<ScraperOptions, \"preserveHashes\">,\n ): Promise<string> {\n const normalizedVersion = normalizeVersionLabel(version);\n\n // Held from the first read until the job is registered, so a removal of\n // this version runs before the refresh reads it or after its job exists\n return this.withVersionLock(library, normalizedVersion, async () => {\n try {\n // Look the version up without creating it: refreshing an unknown library\n // or version fails with a not-found error and leaves nothing behind. From\n // here on, the library is named as it is stored.\n const { versionId, library: displayName } = await this.store.requireVersion({\n library,\n version: normalizedVersion,\n });\n const label = formatVersionLabel(displayName, normalizedVersion);\n\n // Check the version's status to detect incomplete scrapes\n const versionInfo = await this.store.getVersionById(versionId);\n if (!versionInfo) {\n throw new Error(`Version ID ${versionId} not found`);\n }\n\n // If the version is not completed, it means the previous scrape was interrupted\n // or failed. In this case, perform a full re-scrape instead of a refresh.\n if (versionInfo && versionInfo.status !== VersionStatus.COMPLETED) {\n logger.info(\n `⚠️ Version ${label} has status \"${versionInfo.status}\". Performing full re-scrape instead of refresh.`,\n );\n return this.reindexWithStoredOptions(displayName, normalizedVersion, options);\n }\n\n // Get all pages for this version with their ETags and depths\n const pages = await this.store.getPagesByVersionId(versionId);\n\n // Debug: Log first page to see what data we're getting\n if (pages.length > 0) {\n logger.debug(\n `Sample page data: url=${pages[0].url}, etag=${pages[0].etag}, depth=${pages[0].depth}`,\n );\n }\n\n if (pages.length === 0) {\n throw new Error(\n `No pages found for ${label}. Use scrape_docs to index it first.`,\n );\n }\n\n logger.info(`🔄 Preparing refresh job for ${label} with ${pages.length} page(s)`);\n\n // Build initialQueue from pages with original depth values.\n //\n // Requests go to where the content actually came from, which differs from\n // the page's URL when a representation lives elsewhere — a published\n // Markdown file recorded under the page it represents. Asking for the URL\n // instead would retrieve a different representation, and would send the\n // stored validator to a resource that never issued it. `content_url` is\n // NULL for pages retrieved from their own address, including every row\n // written before representations were resolved to a shared identity.\n const initialQueue = pages.map((page) => ({\n url: page.content_url ?? page.url,\n depth: page.depth ?? 0, // Use original depth, fallback to 0 for old data\n pageId: page.id,\n etag: page.etag,\n // Carried so a withdrawn representation does not read as a withdrawn\n // page: the scraper asks this address before deleting anything.\n identityUrl: page.content_url ? page.url : undefined,\n }));\n // Get stored scraper options to retrieve the source URL and other options\n const storedOptions = await this.store.getScraperOptions(versionId);\n\n // Build scraper options with initialQueue and isRefresh flag\n const scraperOptions = {\n url: storedOptions?.sourceUrl || pages[0].url, // Required but not used when initialQueue is set\n library: displayName,\n version: normalizedVersion,\n ...(storedOptions?.options || {}), // Include stored options if available (spread first)\n ...(options?.preserveHashes !== undefined\n ? { preserveHashes: options.preserveHashes }\n : {}),\n // Override with refresh-specific options (these must come after the spread)\n initialQueue, // Pre-populated queue with existing pages\n isRefresh: true, // Mark this as a refresh operation\n };\n\n // Enqueue as a standard scrape job with the initialQueue\n logger.info(`📝 Enqueueing refresh job for ${label}`);\n // A refresh acts on an existing version by definition, so it replaces\n // rather than being rejected; isRefresh keeps the worker from clearing it.\n return this.registerScrapeJob(displayName, normalizedVersion, scraperOptions, {\n onExisting: \"replace\",\n });\n } catch (error) {\n logger.error(`❌ Failed to enqueue refresh job: ${error}`);\n throw error;\n }\n });\n }\n\n /**\n * Enqueues a job using stored scraper options from a previous indexing run.\n * If no stored options are found, throws an error.\n */\n async enqueueJobWithStoredOptions(\n library: string,\n version: string | undefined | null,\n options?: Pick<ScraperOptions, \"preserveHashes\">,\n ): Promise<string> {\n const normalizedVersion = normalizeVersionLabel(version);\n return this.withVersionLock(library, normalizedVersion, () =>\n this.reindexWithStoredOptions(library, normalizedVersion, options),\n );\n }\n\n /**\n * Re-indexes a version with its stored options. Callers hold the version's\n * lock (see {@link withVersionLock}).\n */\n private async reindexWithStoredOptions(\n library: string,\n normalizedVersion: string,\n options?: Pick<ScraperOptions, \"preserveHashes\">,\n ): Promise<string> {\n try {\n // Get the version ID to retrieve stored options, without creating it\n const { versionId, library: displayName } = await this.store.requireVersion({\n library,\n version: normalizedVersion,\n });\n const label = formatVersionLabel(displayName, normalizedVersion);\n const stored = await this.store.getScraperOptions(versionId);\n\n if (!stored) {\n throw new Error(`No stored scraper options found for ${label}`);\n }\n\n const storedOptions = stored.options;\n\n // Reconstruct complete scraper options\n const completeOptions: ScraperOptions = {\n url: stored.sourceUrl,\n library: displayName,\n version: normalizedVersion,\n ...storedOptions,\n ...(options?.preserveHashes !== undefined\n ? { preserveHashes: options.preserveHashes }\n : {}),\n };\n\n logger.info(`🔄 Re-indexing ${label} with stored options from ${stored.sourceUrl}`);\n\n // Re-indexes an existing version (refresh fall-back, recovery), so it replaces\n return this.registerScrapeJob(displayName, normalizedVersion, completeOptions, {\n onExisting: \"replace\",\n });\n } catch (error) {\n logger.error(`❌ Failed to enqueue job with stored options: ${error}`);\n throw error;\n }\n }\n\n /**\n * Retrieves the current state of a specific job.\n */\n async getJob(jobId: string): Promise<PipelineJob | undefined> {\n const internalJob = this.jobMap.get(jobId);\n return internalJob ? this.toPublicJob(internalJob) : undefined;\n }\n\n /**\n * Retrieves the current state of all jobs (or a subset based on status).\n */\n async getJobs(status?: PipelineJobStatus): Promise<PipelineJob[]> {\n const allJobs = Array.from(this.jobMap.values());\n const filteredJobs = status\n ? allJobs.filter((job) => job.status === status)\n : allJobs;\n return filteredJobs.map((job) => this.toPublicJob(job));\n }\n\n /**\n * Returns a promise that resolves when the specified job completes, fails, or is cancelled.\n * For cancelled jobs, this resolves successfully rather than rejecting.\n */\n async waitForJobCompletion(jobId: string): Promise<void> {\n const job = this.jobMap.get(jobId);\n if (!job) {\n throw new PipelineStateError(`Job not found: ${jobId}`);\n }\n\n try {\n await job.completionPromise;\n } catch (error) {\n // If the job was cancelled, treat it as successful completion\n if (\n error instanceof CancellationError ||\n job.status === PipelineJobStatus.CANCELLED\n ) {\n return; // Resolve successfully for cancelled jobs\n }\n // Re-throw other errors (failed jobs)\n throw error;\n }\n }\n\n /**\n * Attempts to cancel a queued or running job.\n */\n async cancelJob(jobId: string): Promise<void> {\n const job = this.jobMap.get(jobId);\n if (!job) {\n logger.warn(`❓ Attempted to cancel non-existent job: ${jobId}`);\n return;\n }\n\n switch (job.status) {\n case PipelineJobStatus.QUEUED:\n // Remove from queue and mark as cancelled\n this.jobQueue = this.jobQueue.filter((id) => id !== jobId);\n await this.updateJobStatus(job, PipelineJobStatus.CANCELLED);\n job.finishedAt = new Date();\n logger.info(`🚫 Job cancelled (was queued): ${jobId}`);\n job.rejectCompletion(new PipelineStateError(\"Job cancelled before starting\"));\n break;\n\n case PipelineJobStatus.RUNNING:\n // Signal cancellation via AbortController\n await this.updateJobStatus(job, PipelineJobStatus.CANCELLING);\n job.abortController.abort();\n logger.info(`🚫 Signalling cancellation for running job: ${jobId}`);\n // The worker is responsible for transitioning to CANCELLED and rejecting\n break;\n\n case PipelineJobStatus.CANCELLING:\n logger.debug(`Job ${jobId} is already being cancelled`);\n break;\n\n case PipelineJobStatus.COMPLETED:\n case PipelineJobStatus.FAILED:\n case PipelineJobStatus.CANCELLED:\n logger.warn(\n `⚠️ Job ${jobId} cannot be cancelled in its current state: ${job.status}`,\n );\n break;\n\n default:\n logger.error(`❌ Unhandled job status for cancellation: ${job.status}`);\n break;\n }\n }\n\n /**\n * Removes all jobs that are in a final state (completed, cancelled, or failed).\n * Only removes jobs that are not currently in the queue or actively running.\n * @returns The number of jobs that were cleared.\n */\n async clearCompletedJobs(): Promise<number> {\n let clearedCount = 0;\n const jobsToRemove: string[] = [];\n\n // Find all jobs that can be cleared\n for (const [jobId, job] of this.jobMap.entries()) {\n if (FINISHED_JOB_STATUSES.has(job.status)) {\n jobsToRemove.push(jobId);\n clearedCount++;\n }\n }\n\n // Remove the jobs from the map\n for (const jobId of jobsToRemove) {\n this.jobMap.delete(jobId);\n }\n\n if (clearedCount > 0) {\n logger.info(`🧹 Cleared ${clearedCount} completed job(s) from the queue`);\n // Emit event to notify clients that the job list has changed\n this.eventBus.emit(EventType.JOB_LIST_CHANGE, undefined);\n } else {\n logger.debug(\"No completed jobs to clear\");\n }\n\n return clearedCount;\n }\n\n // --- Private Methods ---\n\n /**\n * Processes the job queue, starting new workers if capacity allows.\n */\n private async _processQueue(): Promise<void> {\n if (!this.isRunning) return;\n\n while (this.activeWorkers.size < this.concurrency && this.jobQueue.length > 0) {\n const jobId = this.jobQueue.shift();\n if (!jobId) continue; // Should not happen, but safety check\n\n const job = this.jobMap.get(jobId);\n if (!job || job.status !== PipelineJobStatus.QUEUED) {\n logger.warn(`⏭️ Skipping job ${jobId} in queue (not found or not queued).`);\n continue;\n }\n\n this.activeWorkers.add(jobId);\n await this.updateJobStatus(job, PipelineJobStatus.RUNNING);\n job.startedAt = new Date();\n\n // Start the actual job execution asynchronously\n this._runJob(job).catch(async (error) => {\n // Catch unexpected errors during job setup/execution not handled by _runJob itself\n logger.error(`❌ Unhandled error during job ${jobId} execution: ${error}`);\n if (\n job.status !== PipelineJobStatus.FAILED &&\n job.status !== PipelineJobStatus.CANCELLED\n ) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n await this.updateJobStatus(job, PipelineJobStatus.FAILED, errorMessage);\n job.error = error instanceof Error ? error : new Error(String(error));\n job.finishedAt = new Date();\n job.rejectCompletion(job.error);\n }\n this.activeWorkers.delete(jobId);\n this._processQueue().catch((error) => {\n logger.error(`❌ Error in processQueue after job completion: ${error}`);\n }); // Check if another job can start\n });\n }\n }\n\n /**\n * Executes a single pipeline job by delegating to a PipelineWorker.\n * Handles final status updates and promise resolution/rejection.\n */\n private async _runJob(job: InternalPipelineJob): Promise<void> {\n const { id: jobId, abortController } = job;\n const signal = abortController.signal; // Get signal for error checking\n\n // Instantiate a worker for this job.\n // Dependencies (store, scraperService) are held by the manager.\n const worker = new PipelineWorker(this.store, this.scraperService);\n\n try {\n // Delegate the actual work to the worker\n // The worker works with InternalPipelineJob, we convert to public when needed\n await worker.executeJob(job, {\n onJobProgress: async (internalJob, progress) => {\n await this.updateJobProgress(internalJob, progress);\n },\n onJobError: async (internalJob, error, document) => {\n // Log job errors\n logger.warn(\n `⚠️ Job ${internalJob.id} error ${document ? `on document ${document.url}` : \"\"}: ${error.message}`,\n );\n },\n });\n\n // If executeJob completes without throwing, and we weren't cancelled meanwhile...\n if (signal.aborted) {\n // Check signal again in case cancellation happened *during* the very last await in executeJob\n throw new CancellationError(\"Job cancelled just before completion\");\n }\n\n // Mark as completed\n await this.updateJobStatus(job, PipelineJobStatus.COMPLETED);\n job.finishedAt = new Date();\n job.resolveCompletion();\n\n logger.info(`✅ Job completed: ${jobId}`);\n } catch (error) {\n // Handle errors thrown by the worker, including CancellationError\n if (error instanceof CancellationError || signal.aborted) {\n // Explicitly check for CancellationError or if the signal was aborted\n await this.updateJobStatus(job, PipelineJobStatus.CANCELLED);\n job.finishedAt = new Date();\n // Don't set job.error for cancellations - cancellation is not an error condition\n const cancellationError =\n error instanceof CancellationError\n ? error\n : new CancellationError(\"Job cancelled by signal\");\n logger.info(`🚫 Job execution cancelled: ${jobId}: ${cancellationError.message}`);\n job.rejectCompletion(cancellationError);\n } else {\n // Handle other errors\n const errorMessage = error instanceof Error ? error.message : String(error);\n await this.updateJobStatus(job, PipelineJobStatus.FAILED, errorMessage);\n job.error = error instanceof Error ? error : new Error(String(error));\n job.finishedAt = new Date();\n logger.error(`❌ Job failed: ${jobId}: ${job.error}`);\n job.rejectCompletion(job.error);\n }\n } finally {\n // Ensure worker slot is freed and queue processing continues\n this.activeWorkers.delete(jobId);\n this._processQueue().catch((error) => {\n logger.error(`❌ Error in processQueue after job cleanup: ${error}`);\n });\n }\n }\n\n /**\n * Maps PipelineJobStatus to VersionStatus for database storage.\n */\n private mapJobStatusToVersionStatus(jobStatus: PipelineJobStatus): VersionStatus {\n switch (jobStatus) {\n case PipelineJobStatus.QUEUED:\n return VersionStatus.QUEUED;\n case PipelineJobStatus.RUNNING:\n return VersionStatus.RUNNING;\n case PipelineJobStatus.COMPLETED:\n return VersionStatus.COMPLETED;\n case PipelineJobStatus.FAILED:\n return VersionStatus.FAILED;\n case PipelineJobStatus.CANCELLED:\n return VersionStatus.CANCELLED;\n case PipelineJobStatus.CANCELLING:\n return VersionStatus.RUNNING; // Keep as running in DB until actually cancelled\n default:\n return VersionStatus.NOT_INDEXED;\n }\n }\n\n /**\n * Updates both in-memory job status and database version status (write-through).\n */\n private async updateJobStatus(\n job: InternalPipelineJob,\n newStatus: PipelineJobStatus,\n errorMessage?: string,\n ): Promise<void> {\n // Update in-memory status\n job.status = newStatus;\n if (errorMessage) {\n job.errorMessage = errorMessage;\n }\n job.updatedAt = new Date();\n\n // Update database status\n try {\n // The version was claimed when the job was enqueued\n const { versionId } = job;\n\n // Update job object with database fields (single source of truth)\n job.versionStatus = this.mapJobStatusToVersionStatus(newStatus);\n\n const dbStatus = this.mapJobStatusToVersionStatus(newStatus);\n await this.store.updateVersionStatus(versionId, dbStatus, errorMessage);\n\n // Store scraper options when job is first queued\n if (newStatus === PipelineJobStatus.QUEUED && job.scraperOptions) {\n try {\n // Pass the complete scraper options (DocumentStore will filter runtime fields)\n await this.store.storeScraperOptions(versionId, job.scraperOptions);\n logger.debug(\n `Stored scraper options for ${job.library}@${job.version}: ${job.sourceUrl}`,\n );\n } catch (optionsError) {\n // Log warning but don't fail the job - options storage is not critical\n logger.warn(\n `⚠️ Failed to store scraper options for job ${job.id}: ${optionsError}`,\n );\n }\n }\n } catch (error) {\n logger.error(`❌ Failed to update database status for job ${job.id}: ${error}`);\n // Don't throw - we don't want to break the pipeline for database issues\n }\n\n // Emit events to EventBusService\n const publicJob = this.toPublicJob(job);\n\n // The store's status write has already emitted LIBRARY_CHANGE\n this.eventBus.emit(EventType.JOB_STATUS_CHANGE, publicJob);\n\n // Logging\n logger.debug(`Job ${job.id} status changed to: ${job.status}`);\n }\n\n /**\n * Updates both in-memory job progress and database progress (write-through).\n * Also emits progress events to the EventBusService.\n */\n async updateJobProgress(\n job: InternalPipelineJob,\n progress: ScraperProgressEvent,\n ): Promise<void> {\n // Update in-memory progress\n job.progress = progress;\n job.progressPages = progress.pagesScraped;\n job.progressMaxPages = progress.totalPages;\n job.progressPagesIndexed = progress.pagesIndexed;\n job.updatedAt = new Date();\n\n // Update database progress if we have a version ID\n if (job.versionId) {\n try {\n await this.store.updateVersionProgress(\n job.versionId,\n progress.pagesScraped,\n progress.totalPages,\n progress.pagesIndexed,\n );\n } catch (error) {\n logger.error(`❌ Failed to update database progress for job ${job.id}: ${error}`);\n // Don't throw - we don't want to break the pipeline for database issues\n }\n }\n\n // Emit progress event to EventBusService\n const publicJob = this.toPublicJob(job);\n\n this.eventBus.emit(EventType.JOB_PROGRESS, { job: publicJob, progress });\n\n // Logging\n logger.debug(\n `Job ${job.id} progress: ${progress.pagesScraped}/${progress.totalPages} processed, ${progress.pagesIndexed} indexed`,\n );\n }\n}\n","/**\n * Document management backed by a remote worker: every operation calls the\n * worker's application API through a shared {@link ApiClient}.\n */\nimport type { ScraperOptions } from \"../scraper/types\";\nimport type { ApiClient } from \"../services/apiClient\";\nimport type { EmbeddingModelConfig } from \"./embeddings/EmbeddingConfig\";\nimport type { IDocumentManagement } from \"./trpc/interfaces\";\nimport type {\n ActivityHistory,\n CompactResult,\n DbVersionWithLibrary,\n EmbeddingConfigInfo,\n FindVersionResult,\n LibrarySummary,\n ListPagesOptions,\n ListPagesResult,\n ListVersionChunksOptions,\n ListVersionChunksResult,\n PageContentOptions,\n PageContentResult,\n StoredScraperOptions,\n StoreSearchResult,\n VersionChunkStats,\n VersionComposition,\n VersionRef,\n VersionStatus,\n} from \"./types\";\n\n/**\n * How long the health report waits for the worker's embedding config before the\n * last known value stands in; a worker that drops traffic would otherwise hold\n * the report open.\n */\nconst EMBEDDING_CONFIG_TIMEOUT_MS = 3000;\n\n/**\n * Implements {@link IDocumentManagement} by delegating every operation to a\n * remote worker.\n */\nexport class DocumentManagementClient implements IDocumentManagement {\n /** The worker's last reported embedding config; `undefined` until it answers once. */\n private lastEmbeddingConfig: EmbeddingConfigInfo | null | undefined;\n\n /** @param client The worker's API client. Whoever created it checks and closes it. */\n constructor(private readonly client: ApiClient) {}\n\n async listLibraries(): Promise<LibrarySummary[]> {\n return this.client.listLibraries.query();\n }\n\n async validateLibraryExists(library: string): Promise<void> {\n await this.client.validateLibraryExists.mutate({ library });\n }\n\n async findBestVersion(\n library: string,\n targetVersion?: string,\n ): Promise<FindVersionResult> {\n return this.client.findBestVersion.query({ library, targetVersion });\n }\n\n async searchStore(\n library: string,\n version: string | null | undefined,\n query: string,\n limit?: number,\n ): Promise<StoreSearchResult[]> {\n return this.client.search.query({ library, version: version ?? null, query, limit });\n }\n\n async getPageContent(\n library: string,\n version: string | null | undefined,\n pathOrUrl: string,\n options?: PageContentOptions,\n ): Promise<PageContentResult> {\n return this.client.getPageContent.query({\n library,\n version: version ?? null,\n pathOrUrl,\n options,\n });\n }\n\n async listPages(\n library: string,\n version: string | null | undefined,\n options?: ListPagesOptions,\n ): Promise<ListPagesResult> {\n return this.client.listPages.query({\n library,\n version: version ?? null,\n options,\n });\n }\n\n /**\n * Removes the version on the worker the way every entry point removes one:\n * the worker first cancels a queued or running job of its own for it.\n */\n async removeVersion(library: string, version?: string | null): Promise<void> {\n await this.client.removeDocs.mutate({ library, version });\n }\n\n async compact(options?: { force?: boolean; vacuum?: boolean }): Promise<CompactResult> {\n return this.client.compact.mutate(options ?? {});\n }\n\n async getVersionsByStatus(statuses: VersionStatus[]): Promise<DbVersionWithLibrary[]> {\n return this.client.getVersionsByStatus.query({\n statuses: statuses as unknown as string[],\n });\n }\n\n async findVersionsBySourceUrl(url: string): Promise<DbVersionWithLibrary[]> {\n return this.client.findVersionsBySourceUrl.query({ url });\n }\n\n async getScraperOptions(versionId: number): Promise<StoredScraperOptions | null> {\n return this.client.getScraperOptions.query({ versionId });\n }\n\n async updateVersionStatus(\n versionId: number,\n status: VersionStatus,\n errorMessage?: string,\n ): Promise<void> {\n await this.client.updateVersionStatus.mutate({ versionId, status, errorMessage });\n }\n\n async updateVersionProgress(\n versionId: number,\n pages: number,\n maxPages: number,\n ): Promise<void> {\n await this.client.updateVersionProgress.mutate({ versionId, pages, maxPages });\n }\n\n async storeScraperOptions(versionId: number, options: ScraperOptions): Promise<void> {\n await this.client.storeScraperOptions.mutate({ versionId, options });\n }\n\n getActiveEmbeddingConfig(): EmbeddingModelConfig | null {\n // For remote client, embedding config is not available locally.\n // The remote server's embedding status cannot be synchronously queried.\n // Return null to indicate embeddings status is unknown/unavailable.\n return null;\n }\n\n /**\n * The worker's embedding config, fetched over the wire because that is where\n * embeddings live; the local `getActiveEmbeddingConfig` (null) would misreport\n * \"FTS only\". The config is fixed for the worker's lifetime, so while the\n * worker does not answer in time, the last value it reported stands in.\n *\n * @throws Error when the worker does not answer in time and never has.\n */\n async getEmbeddingConfigInfo(): Promise<EmbeddingConfigInfo | null> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), EMBEDDING_CONFIG_TIMEOUT_MS);\n try {\n this.lastEmbeddingConfig = await this.client.getEmbeddingConfig.query(undefined, {\n signal: controller.signal,\n });\n } catch (error) {\n if (this.lastEmbeddingConfig === undefined) {\n throw error;\n }\n } finally {\n clearTimeout(timer);\n }\n return this.lastEmbeddingConfig;\n }\n\n async listVersionChunks(\n ref: VersionRef,\n options?: Partial<ListVersionChunksOptions>,\n ): Promise<ListVersionChunksResult> {\n return this.client.listVersionChunks.query({\n library: ref.library,\n version: ref.version,\n limit: options?.limit,\n offset: options?.offset,\n filter: options?.filter,\n });\n }\n\n async getVersionStats(ref: VersionRef): Promise<VersionChunkStats> {\n return this.client.getVersionStats.query({\n library: ref.library,\n version: ref.version,\n });\n }\n\n async getActivityHistory(days?: number): Promise<ActivityHistory> {\n return this.client.getActivityHistory.query({ days });\n }\n\n async getVersionComposition(ref: VersionRef): Promise<VersionComposition> {\n return this.client.getVersionComposition.query({\n library: ref.library,\n version: ref.version,\n });\n }\n}\n","/**\n * Version label classification and comparison utilities.\n *\n * A stored version label is whatever an operator indexed documentation under.\n * It is classified into one of two tiers: a *semantic version*, which takes part\n * in ordering and range matching, or an *opaque tag*, which is only ever matched\n * literally. Nothing is discarded — classification is a routing decision, not a\n * judgement about whether a label is valid.\n */\n\nimport semver from \"semver\";\n\n/**\n * Partial versions accepted as stored labels: `major` or `major.minor`, with an\n * optional `v` prefix (e.g. `\"5\"`, `\"1.20\"`, `\"v1.20\"`).\n *\n * Coercion is gated on this shape because `semver.coerce()` pulls the first\n * number out of arbitrary text — it turns `\"stable-2024\"` into `2024.0.0` and\n * `\"node18\"` into `18.0.0`, which would make non-version labels sort and match\n * as if they were releases.\n */\nconst PARTIAL_VERSION_PATTERN = /^v?\\d+(?:\\.\\d+)?$/;\n\n/**\n * Version shapes accepted in a *request*: `major`, `major.minor`, `major.minor.patch`,\n * and their X-range forms (`1.x`, `1.2.x`, `1.x.x`).\n *\n * Wider than {@link PARTIAL_VERSION_PATTERN} because a request may be a range,\n * which a stored label never is. Full semver requests are recognized by\n * `semver.valid` before this pattern is consulted.\n */\nexport const VERSION_REQUEST_PATTERN = /^\\d+(?:\\.(?:x(?:\\.x)?|\\d+(?:\\.(?:x|\\d+))?))?$/;\n\n/** A stored label that is a semantic version, usable for ordering and ranges. */\nexport interface SemanticVersionCandidate {\n kind: \"version\";\n /** The version string exactly as stored in the database. */\n stored: string;\n /** Strict `X.Y.Z[-prerelease]` semver used for range matching and sorting. */\n normalized: string;\n /** True when `stored` was already valid semver and needed no coercion. */\n strict: boolean;\n}\n\n/** A stored label that is not a version and can only be matched literally. */\ninterface TagCandidate {\n kind: \"tag\";\n /** The label exactly as stored in the database. */\n stored: string;\n}\n\n/**\n * A stored version label paired with how it may be matched.\n *\n * Labels in the store are whatever a project publishes — `\"1.20\"`, `\"5\"`,\n * `\"v2.0.0\"`, `\"2.0.0-beta\"`, but also `\"stable\"` or `\"main\"`. Semver range\n * matching only accepts full `X.Y.Z` strings, so a candidate keeps the stored\n * label beside the form used for matching, and records which tier it is in.\n */\nexport type VersionCandidate = SemanticVersionCandidate | TagCandidate;\n\n/**\n * Classifies a stored version label.\n *\n * Strict semver is matched first and preserved verbatim, so prerelease and build\n * metadata survive and a label like `\"2.0.0-beta\"` never collapses into\n * `\"2.0.0\"` and outranks the real release. Only the partial shapes in\n * {@link PARTIAL_VERSION_PATTERN} fall back to coercion. Everything else is an\n * opaque tag.\n *\n * @param stored Version label as stored in the database.\n * @returns The candidate, or `null` for an empty label, which represents\n * unversioned documentation rather than a tag.\n */\nexport function toVersionCandidate(stored: string): VersionCandidate | null {\n if (stored === \"\") {\n return null;\n }\n\n const strict = semver.valid(stored);\n if (strict) {\n return { kind: \"version\", stored, normalized: strict, strict: true };\n }\n\n if (PARTIAL_VERSION_PATTERN.test(stored)) {\n const coerced = semver.coerce(stored);\n if (coerced) {\n return { kind: \"version\", stored, normalized: coerced.version, strict: false };\n }\n }\n\n return { kind: \"tag\", stored };\n}\n\n/**\n * Classifies stored version labels, dropping empty ones.\n *\n * @param versions Version labels as stored in the database.\n * @returns One candidate per non-empty label, in input order.\n */\nexport function toVersionCandidates(versions: string[]): VersionCandidate[] {\n return versions\n .map(toVersionCandidate)\n .filter((candidate): candidate is VersionCandidate => candidate !== null);\n}\n\n/** Narrows a candidate to the semantic version tier. */\nexport function isSemanticVersion(\n candidate: VersionCandidate,\n): candidate is SemanticVersionCandidate {\n return candidate.kind === \"version\";\n}\n\n/**\n * Compares two version labels for sorting in the canonical display order.\n *\n * Rules:\n * - Unversioned entries (empty string, null, undefined) sort first.\n * - Semantic versions follow, newest first, compared by semver rules. Labels\n * that normalize to the same version are ordered strict spelling first.\n * - Opaque tags sort last, in alphabetical order.\n *\n * @param a First version label (may be empty, null, or undefined for unversioned)\n * @param b Second version label (may be empty, null, or undefined for unversioned)\n * @returns Negative if a should come before b, positive if b should come before a, 0 if equal\n */\nexport function compareVersionsDescending(\n a: string | null | undefined,\n b: string | null | undefined,\n): number {\n const aIsUnversioned = a === \"\" || a === null || a === undefined;\n const bIsUnversioned = b === \"\" || b === null || b === undefined;\n\n // Unversioned entries come first (are \"latest\")\n if (aIsUnversioned && bIsUnversioned) return 0;\n if (aIsUnversioned) return -1;\n if (bIsUnversioned) return 1;\n\n // Classify via the same rules used for range matching, so sort order and\n // version resolution never disagree.\n const aCandidate = toVersionCandidate(a);\n const bCandidate = toVersionCandidate(b);\n const aIsVersion = aCandidate?.kind === \"version\";\n const bIsVersion = bCandidate?.kind === \"version\";\n\n if (aIsVersion && bIsVersion) {\n // Both are semantic versions - compare descending (higher version first)\n const byVersion = semver.rcompare(aCandidate.normalized, bCandidate.normalized);\n if (byVersion !== 0) return byVersion;\n\n // Distinct labels can normalize to the same version (\"1.20\" and \"1.20.0\").\n // Order is still required to be deterministic, so prefer the strict\n // spelling — the same one semantic matching resolves to — and fall back to\n // the label itself rather than leaving it to store insertion order.\n if (aCandidate.strict !== bCandidate.strict) return aCandidate.strict ? -1 : 1;\n return aCandidate.stored.localeCompare(bCandidate.stored);\n }\n\n // Semantic versions outrank opaque tags, which have no defensible position\n // among them.\n if (aIsVersion) return -1;\n if (bIsVersion) return 1;\n\n // Both are tags - alphabetical, so the order is at least deterministic.\n return a.toLowerCase().localeCompare(b.toLowerCase());\n}\n\n/**\n * Sorts version labels into the canonical display order: unversioned first,\n * then semantic versions newest-first, then opaque tags alphabetically.\n *\n * @param versions Array of version labels\n * @returns New array sorted in canonical order\n */\nexport function sortVersionsDescending(versions: string[]): string[] {\n return [...versions].sort(compareVersionsDescending);\n}\n","import type { AppConfig } from \"../../../utils/config\";\nimport { logger } from \"../../../utils/logger\";\nimport { MimeTypeUtils } from \"../../../utils/mimeTypeUtils\";\nimport type { DocumentStore } from \"../../DocumentStore\";\nimport type { DbPageChunk } from \"../../types\";\nimport type { ContentAssemblyStrategy } from \"../types\";\n\n/** Positions of a run of chunks in a page, from `start` up to but not including `end`. */\ninterface ChunkRange {\n start: number;\n end: number;\n}\n\n/** Returns a chunk's path, or the root path when it has none. */\nfunction pathOf(chunk: DbPageChunk): string[] {\n return chunk.metadata.path ?? [];\n}\n\n/** Returns whether `path` begins with every segment of `prefix`. */\nfunction startsWithPath(path: string[], prefix: string[]): boolean {\n return (\n path.length >= prefix.length &&\n prefix.every((segment, index) => segment === path[index])\n );\n}\n\n/** Returns whether two paths have the same segments. */\nfunction isSamePath(a: string[], b: string[]): boolean {\n return a.length === b.length && startsWithPath(a, b);\n}\n\n/** Returns the longest path that every given path starts with. */\nfunction commonPrefix(paths: string[][]): string[] {\n const [first = [], ...rest] = paths;\n let length = 0;\n while (length < first.length && rest.every((path) => path[length] === first[length])) {\n length++;\n }\n return first.slice(0, length);\n}\n\n/** Returns whether a chunk opens a declaration such as a class or namespace. */\nfunction isStructural(chunk: DbPageChunk): boolean {\n return chunk.metadata.types?.includes(\"structural\") ?? false;\n}\n\n/**\n * Assembly strategy for structured content (source code, JSON, config files).\n *\n * Uses selective subtree reassembly: a single match brings the structure that contains\n * it, such as its class or JSON object, with the opening and closing chunks of the scopes\n * around it. Multiple matches within the same document bring only their own subtrees,\n * inside the opening and closing chunks of their scopes, avoiding inclusion of excessive\n * unrelated content. Simple concatenation leverages splitter concatenation guarantees.\n */\nexport class HierarchicalAssemblyStrategy implements ContentAssemblyStrategy {\n constructor(private config: AppConfig) {}\n\n /**\n * Determines if this strategy can handle the given content type.\n * Handles structured content like source code, JSON, configuration files.\n */\n canHandle(mimeType?: string): boolean {\n if (!mimeType) {\n return false;\n }\n // Source code content\n if (MimeTypeUtils.isSourceCode(mimeType)) {\n return true;\n }\n\n // JSON content\n if (MimeTypeUtils.isJson(mimeType)) {\n return true;\n }\n\n // Could add more structured content detection here if needed\n // (e.g., YAML, TOML, XML configuration files)\n\n return false;\n }\n /**\n * Selects the chunks to reassemble around the matches of each document.\n * For a single match: the subtree of its container plus the boundaries of the enclosing scopes.\n * For multiple matches in same document: each match's subtree plus the boundaries of its scopes.\n */\n async selectChunks(\n library: string,\n version: string,\n initialChunks: DbPageChunk[],\n documentStore: DocumentStore,\n ): Promise<DbPageChunk[]> {\n if (initialChunks.length === 0) {\n return [];\n }\n\n try {\n // Group chunks by document URL\n const chunksByDocument = new Map<string, DbPageChunk[]>();\n for (const chunk of initialChunks) {\n const url = chunk.url;\n if (!chunksByDocument.has(url)) {\n chunksByDocument.set(url, []);\n }\n chunksByDocument.get(url)?.push(chunk);\n }\n\n const allChunkIds = new Set<string>();\n\n // Process each document group\n for (const [url, documentChunks] of Array.from(chunksByDocument.entries())) {\n // IMPORTANT: Always include the original matched chunks first\n for (const matched of documentChunks) {\n allChunkIds.add(matched.id);\n }\n\n const pageChunks = await documentStore.findChunksByUrl(library, version, url);\n const matchedIds = new Set(documentChunks.map((matched) => matched.id));\n const matchIndices = pageChunks.flatMap((chunk, index) =>\n matchedIds.has(chunk.id) ? [index] : [],\n );\n if (matchIndices.length === 0) continue;\n\n const selected =\n documentChunks.length === 1\n ? this.selectAroundMatch(\n pageChunks,\n matchIndices[0],\n MimeTypeUtils.isJson(documentChunks[0].content_type ?? \"\"),\n )\n : this.selectAroundMatches(pageChunks, matchIndices);\n for (const chunk of selected) {\n allChunkIds.add(chunk.id);\n }\n }\n\n // Fetch all chunks in proper sort order\n const chunkIds = Array.from(allChunkIds);\n const chunks = await documentStore.findChunksByIds(library, version, chunkIds);\n\n return chunks;\n } catch (error) {\n // Fallback to simpler selection if loading the page fails\n logger.warn(\n `Hierarchical chunk selection failed, falling back to basic selection: ${error}`,\n );\n return this.fallbackSelection(library, version, initialChunks, documentStore);\n }\n }\n\n /**\n * Assembles chunks using simple concatenation.\n * Relies on splitter concatenation guarantees - chunks are designed to join seamlessly.\n */\n assembleContent(chunks: DbPageChunk[]): string {\n return chunks.map((chunk) => chunk.content).join(\"\");\n }\n\n /**\n * Selects the chunks around a single match: the subtree of its container (for code\n * its structural ancestor, such as its class; for JSON the object or array holding\n * it) and the opening and closing chunks of the scopes that enclose that container.\n *\n * @param pageChunks All chunks of one page, in document order.\n * @param matchIndex Position of the match.\n * @param isJson Whether the page is JSON.\n */\n private selectAroundMatch(\n pageChunks: DbPageChunk[],\n matchIndex: number,\n isJson: boolean,\n ): DbPageChunk[] {\n const containerIndex = isJson\n ? this.findJsonContainer(pageChunks, matchIndex)\n : this.findCodeContainer(pageChunks, matchIndex);\n return this.selectSubtree(pageChunks, containerIndex);\n }\n\n /**\n * Selects the chunks around several matches in one page: each match's subtree with\n * the opening and closing chunks of the scopes that enclose it, but none of their\n * other members. Within the scope that holds all matches, the chunks at that scope's\n * own path, such as fields or statements, are included as well.\n *\n * @param pageChunks All chunks of one page, in document order.\n * @param matchIndices Positions of the matches, in document order.\n */\n private selectAroundMatches(\n pageChunks: DbPageChunk[],\n matchIndices: number[],\n ): DbPageChunk[] {\n const selected = matchIndices.flatMap((index) =>\n this.selectSubtree(pageChunks, index),\n );\n\n const commonPath = commonPrefix(\n matchIndices.map((index) => pathOf(pageChunks[index])),\n );\n const commonScope =\n commonPath.length > 0\n ? this.findScopeStart(pageChunks, matchIndices[0], commonPath)\n : undefined;\n if (commonScope !== undefined) {\n const scope = this.containerRange(pageChunks, commonScope);\n for (const chunk of pageChunks.slice(scope.start, scope.end)) {\n if (isSamePath(pathOf(chunk), commonPath)) selected.push(chunk);\n }\n }\n return selected;\n }\n\n /**\n * Selects the subtree that the chunk at `index` opens, through its closing chunk, and\n * the opening and closing chunks of the scopes that enclose it. A chunk that opens\n * nothing, such as a field or statement that follows other members of its scope, comes\n * back on its own inside its scope's opening and closing chunks.\n */\n private selectSubtree(pageChunks: DbPageChunk[], index: number): DbPageChunk[] {\n if (!this.opensContainer(pageChunks, index)) {\n const scopeStart = this.findScopeStart(\n pageChunks,\n index,\n pathOf(pageChunks[index]),\n );\n const scope =\n scopeStart === undefined\n ? []\n : this.scopeBoundaries(pageChunks, this.containerRange(pageChunks, scopeStart));\n return [\n pageChunks[index],\n ...scope,\n ...this.findEnclosingScopeBoundaries(pageChunks, scopeStart ?? index),\n ];\n }\n\n const subtree = this.containerRange(pageChunks, index);\n return [\n ...pageChunks.slice(subtree.start, subtree.end),\n ...this.findEnclosingScopeBoundaries(pageChunks, subtree.start),\n ];\n }\n\n /**\n * Returns whether the chunk at `index` opens a container: no chunk nested deeper in its\n * path comes before it in the run of chunks inside that path. A field between two\n * methods carries its class's path but follows the first method, so it opens nothing.\n */\n private opensContainer(pageChunks: DbPageChunk[], index: number): boolean {\n const path = pathOf(pageChunks[index]);\n if (path.length === 0) {\n return true;\n }\n for (let previous = index - 1; previous >= 0; previous--) {\n const previousPath = pathOf(pageChunks[previous]);\n if (!startsWithPath(previousPath, path)) return true;\n if (previousPath.length > path.length) return false;\n }\n return true;\n }\n\n /**\n * Finds the code container to reconstruct for a single match: the innermost scope\n * around the match, the match's own included, whose opening chunk is structural (a\n * class, interface, enum or namespace). Without one, as for a match in a top-level\n * function, it is the top-level element named by the first path segment, otherwise\n * the match itself.\n *\n * @param pageChunks All chunks of one page, in document order.\n * @param matchIndex Position of the match.\n * @returns The position of the container's opening chunk.\n */\n private findCodeContainer(pageChunks: DbPageChunk[], matchIndex: number): number {\n const path = pathOf(pageChunks[matchIndex]);\n // Example: path ['applyMigrations','overallTransaction','<anonymous_arrow>'] has no\n // structural scope, so the whole top-level function 'applyMigrations' is reconstructed.\n let topLevel: number | undefined;\n for (let length = path.length; length > 0; length--) {\n const start = this.findScopeStart(pageChunks, matchIndex, path.slice(0, length));\n if (start === undefined) continue;\n if (isStructural(pageChunks[start])) return start;\n if (length === 1) topLevel = start;\n }\n return topLevel ?? matchIndex;\n }\n\n /**\n * Finds the JSON object or array to reconstruct for a single match: the one the match\n * opens, otherwise the one that contains it. Unlike code, a match is not promoted to\n * the top level, which in JSON is the whole document.\n *\n * The JSON splitter puts a key whose value is an object or array at the key's path,\n * followed by a chunk at the same path that begins with the opening bracket: the\n * bracket alone, or, past `splitter.json.maxNestingDepth`, the whole value serialized\n * as text. That chunk marks an object or array even when it is empty. A primitive\n * value never begins with a bracket.\n *\n * @param pageChunks All chunks of one page, in document order.\n * @param matchIndex Position of the match.\n * @returns The position of a chunk that opens the container.\n */\n private findJsonContainer(pageChunks: DbPageChunk[], matchIndex: number): number {\n const path = pathOf(pageChunks[matchIndex]);\n const own = this.containerRange(pageChunks, matchIndex);\n const opensContainer = pageChunks\n .slice(own.start, own.end)\n .some(\n (chunk) => isSamePath(pathOf(chunk), path) && /^[[{]/.test(chunk.content.trim()),\n );\n if (opensContainer || path.length <= 1) {\n return matchIndex;\n }\n return this.findScopeStart(pageChunks, own.start, path.slice(0, -1)) ?? matchIndex;\n }\n\n /**\n * Finds the chunks that open and close each scope enclosing a container, innermost\n * first and up to `assembly.maxParentChainDepth` scopes. A scope opens where the run\n * of chunks inside its path begins, so the members and statements between its\n * declaration and the container are left out. A scope with no chunk at its own path,\n * such as a level the splitter skipped, adds nothing.\n *\n * @param pageChunks All chunks of one page, in document order.\n * @param containerStart Position of the container's first chunk.\n * @returns The scopes' opening and closing chunks.\n */\n private findEnclosingScopeBoundaries(\n pageChunks: DbPageChunk[],\n containerStart: number,\n ): DbPageChunk[] {\n const path = pathOf(pageChunks[containerStart]);\n const { maxParentChainDepth } = this.config.assembly;\n const boundaries: DbPageChunk[] = [];\n let index = containerStart;\n for (\n let length = path.length - 1;\n length > 0 && path.length - length < maxParentChainDepth;\n length--\n ) {\n const start = this.findScopeStart(pageChunks, index, path.slice(0, length));\n if (start === undefined) continue;\n index = start;\n boundaries.push(\n ...this.scopeBoundaries(pageChunks, this.containerRange(pageChunks, start)),\n );\n }\n return boundaries;\n }\n\n /**\n * Finds where the scope with the given path opens, looking back from the chunk at\n * `index`: the first chunk of the run of chunks inside that path.\n *\n * @param pageChunks All chunks of one page, in document order.\n * @param index Position of a chunk inside the scope.\n * @param scopePath Path of the scope.\n * @returns The position of the scope's opening chunk, or undefined when the run does\n * not begin with a chunk at the scope's own path.\n */\n private findScopeStart(\n pageChunks: DbPageChunk[],\n index: number,\n scopePath: string[],\n ): number | undefined {\n let start = index;\n while (start > 0 && startsWithPath(pathOf(pageChunks[start - 1]), scopePath)) {\n start--;\n }\n return isSamePath(pathOf(pageChunks[start]), scopePath) ? start : undefined;\n }\n\n /**\n * Returns the chunks that open and close a scope: those at the scope's own path before\n * its first nested member (a class declaration, or a JSON key and its bracket) and\n * after its last one (a closing brace). A scope without nested members has none.\n *\n * @param pageChunks All chunks of one page, in document order.\n * @param scope Range of the scope, as found by `containerRange`.\n */\n private scopeBoundaries(pageChunks: DbPageChunk[], scope: ChunkRange): DbPageChunk[] {\n // Every chunk in the range starts with the scope's path, so a longer path is nested\n const depth = pathOf(pageChunks[scope.start]).length;\n const isOwn = (index: number) => pathOf(pageChunks[index]).length === depth;\n let firstNested = scope.start;\n while (firstNested < scope.end && isOwn(firstNested)) {\n firstNested++;\n }\n if (firstNested === scope.end) {\n return [];\n }\n let lastNested = scope.end - 1;\n while (isOwn(lastNested)) {\n lastNested--;\n }\n return [\n ...pageChunks.slice(scope.start, firstNested),\n ...pageChunks.slice(lastNested + 1, scope.end),\n ];\n }\n\n /**\n * Finds the container that the chunk at `index` belongs to. The container opens with\n * the chunk and the chunks right before it that carry the same path (such as a JSON\n * key and its bracket), and holds the chunks right after it whose path starts with\n * that path. The run ends at the first chunk outside the container, so it holds the\n * nested members and the closing chunk, which repeats the container's path, but no\n * unrelated code. A chunk with an empty path is global code and contains nothing else.\n *\n * @param pageChunks All chunks of one page, in document order.\n * @param index Position of a chunk that opens the container.\n * @returns The container's range in `pageChunks`.\n */\n private containerRange(pageChunks: DbPageChunk[], index: number): ChunkRange {\n const rootPath = pathOf(pageChunks[index]);\n if (rootPath.length === 0) {\n return { start: index, end: index + 1 };\n }\n\n let start = index;\n while (start > 0 && isSamePath(pathOf(pageChunks[start - 1]), rootPath)) {\n start--;\n }\n let end = index + 1;\n while (end < pageChunks.length && startsWithPath(pathOf(pageChunks[end]), rootPath)) {\n end++;\n }\n return { start, end };\n }\n\n /**\n * Fallback selection method when parent chain walking fails.\n * Uses a simplified approach similar to MarkdownAssemblyStrategy but more conservative.\n */\n private async fallbackSelection(\n library: string,\n version: string,\n initialChunks: DbPageChunk[],\n documentStore: DocumentStore,\n ): Promise<DbPageChunk[]> {\n const chunkIds = new Set<string>();\n\n // Just include the initial chunks and their immediate parents/children\n for (const chunk of initialChunks) {\n const id = chunk.id;\n chunkIds.add(id);\n\n // Add parent for context\n const parent = await documentStore.findParentChunk(library, version, id);\n if (parent) {\n chunkIds.add(parent.id);\n }\n\n // Add direct children (limited)\n try {\n const children = await documentStore.findChildChunks(library, version, id, 3);\n for (const child of children) {\n chunkIds.add(child.id as string);\n }\n } catch (error) {\n logger.warn(`Failed to find children for chunk ${id}: ${error}`);\n }\n }\n\n const chunks = await documentStore.findChunksByIds(\n library,\n version,\n Array.from(chunkIds),\n );\n\n return chunks;\n }\n}\n","import type { AppConfig } from \"../../../utils/config\";\nimport { MimeTypeUtils } from \"../../../utils/mimeTypeUtils\";\nimport type { DocumentStore } from \"../../DocumentStore\";\nimport type { DbPageChunk } from \"../../types\";\nimport type { ContentAssemblyStrategy } from \"../types\";\n\n/**\n * Assembly strategy that preserves the current behavior for markdown and text content.\n *\n * Uses broad context expansion (parents, siblings, children) and simple \"\\n\\n\" joining.\n * This strategy is optimized for prose content where broader context enhances understanding.\n */\nexport class MarkdownAssemblyStrategy implements ContentAssemblyStrategy {\n constructor(private config: AppConfig) {}\n\n /**\n * Determines if this strategy can handle the given content type.\n * Handles markdown, HTML, plain text, and serves as fallback for unknown types.\n */\n canHandle(mimeType?: string): boolean {\n // Handle undefined/unknown MIME types as fallback\n if (!mimeType) {\n return true;\n }\n\n // First, check if it's a structured type that should be handled by HierarchicalAssemblyStrategy\n if (MimeTypeUtils.isSourceCode(mimeType) || MimeTypeUtils.isJson(mimeType)) {\n return false;\n }\n\n // Handle markdown content\n if (MimeTypeUtils.isMarkdown(mimeType)) {\n return true;\n }\n\n // Handle HTML content\n if (MimeTypeUtils.isHtml(mimeType)) {\n return true;\n }\n\n // Handle plain text content\n if (MimeTypeUtils.isText(mimeType)) {\n return true;\n }\n\n // Accept as fallback for truly unknown types\n return true;\n }\n\n /**\n * Selects chunks using the current context expansion logic.\n * This replicates the existing behavior from DocumentRetrieverService.getRelatedChunkIds().\n */\n async selectChunks(\n library: string,\n version: string,\n initialChunks: DbPageChunk[],\n documentStore: DocumentStore,\n ): Promise<DbPageChunk[]> {\n const allChunkIds = new Set<string>();\n\n // Process all initial chunks in parallel to gather related chunk IDs\n const relatedIdsPromises = initialChunks.map((doc) =>\n this.getRelatedChunkIds(library, version, doc, documentStore),\n );\n\n const relatedIdsResults = await Promise.all(relatedIdsPromises);\n\n // Add all related IDs to the set (automatically deduplicates)\n for (const relatedIds of relatedIdsResults) {\n for (const id of relatedIds) {\n allChunkIds.add(id);\n }\n }\n\n // Fetch all chunks and return them in sort_order\n const chunkIds = Array.from(allChunkIds);\n const chunks = await documentStore.findChunksByIds(library, version, chunkIds);\n\n return chunks; // Already sorted by sort_order in findChunksByIds\n }\n\n /**\n * Assembles chunks using simple \"\\n\\n\" joining (current behavior).\n */\n assembleContent(chunks: DbPageChunk[]): string {\n return chunks.map((chunk) => chunk.content).join(\"\\n\\n\");\n }\n\n /**\n * Collects related chunk IDs for a single chunk using current context expansion logic.\n * This is a direct port of the logic from DocumentRetrieverService.getRelatedChunkIds().\n */\n private async getRelatedChunkIds(\n library: string,\n version: string,\n doc: DbPageChunk,\n documentStore: DocumentStore,\n ): Promise<Set<string>> {\n const id = doc.id;\n const relatedIds = new Set<string>();\n const { childLimit, precedingSiblingsLimit, subsequentSiblingsLimit } =\n this.config.assembly;\n\n // Add the original chunk\n relatedIds.add(id);\n\n // Parent\n const parent = await documentStore.findParentChunk(library, version, id);\n if (parent) {\n relatedIds.add(parent.id);\n }\n\n // Preceding Siblings\n const precedingSiblings = await documentStore.findPrecedingSiblingChunks(\n library,\n version,\n id,\n precedingSiblingsLimit,\n );\n for (const sib of precedingSiblings) {\n relatedIds.add(sib.id);\n }\n\n // Child Chunks\n const childChunks = await documentStore.findChildChunks(\n library,\n version,\n id,\n childLimit,\n );\n for (const child of childChunks) {\n relatedIds.add(child.id);\n }\n\n // Subsequent Siblings\n const subsequentSiblings = await documentStore.findSubsequentSiblingChunks(\n library,\n version,\n id,\n subsequentSiblingsLimit,\n );\n for (const sib of subsequentSiblings) {\n relatedIds.add(sib.id);\n }\n\n return relatedIds;\n }\n}\n","import type { AppConfig } from \"../../utils/config\";\nimport { HierarchicalAssemblyStrategy } from \"./strategies/HierarchicalAssemblyStrategy\";\nimport { MarkdownAssemblyStrategy } from \"./strategies/MarkdownAssemblyStrategy\";\nimport type { ContentAssemblyStrategy } from \"./types\";\n\n/**\n * Creates the appropriate assembly strategy based on content MIME type.\n *\n * @param mimeType The MIME type of the content (optional)\n * @param config Application configuration\n * @returns The appropriate strategy instance\n */\nexport function createContentAssemblyStrategy(\n mimeType: string | null | undefined,\n config: AppConfig,\n): ContentAssemblyStrategy {\n // Default to MarkdownAssemblyStrategy for unknown or missing MIME types\n if (!mimeType) {\n return new MarkdownAssemblyStrategy(config); // Markdown strategy doesn't need config currently\n }\n\n // Try each strategy to see which one can handle the content type\n const strategies = [\n new HierarchicalAssemblyStrategy(config),\n new MarkdownAssemblyStrategy(config),\n ];\n\n for (const strategy of strategies) {\n if (strategy.canHandle(mimeType)) {\n return strategy;\n }\n }\n\n // Default fallback to MarkdownAssemblyStrategy\n return new MarkdownAssemblyStrategy(config);\n}\n","import type { AppConfig } from \"../utils/config\";\nimport { createContentAssemblyStrategy } from \"./assembly/ContentAssemblyStrategyFactory\";\nimport type { DocumentStore } from \"./DocumentStore\";\nimport {\n type DbChunkRank,\n type DbPageChunk,\n normalizeVersionLabel,\n type StoreSearchResult,\n} from \"./types\";\n\nexport class DocumentRetrieverService {\n private documentStore: DocumentStore;\n private config: AppConfig;\n\n constructor(documentStore: DocumentStore, config: AppConfig) {\n this.documentStore = documentStore;\n this.config = config;\n }\n\n /**\n * Searches for documents and expands the context around the matches using content-type-aware strategies.\n * @param library The library name.\n * @param version The library version.\n * @param query The search query.\n * @param limit The optional limit for the initial search results.\n * @returns An array of search results with content assembled according to content type.\n */\n async search(\n library: string,\n version: string | null | undefined,\n query: string,\n limit?: number,\n ): Promise<StoreSearchResult[]> {\n const normalizedVersion = normalizeVersionLabel(version);\n\n const initialResults = await this.documentStore.findByContent(\n library,\n normalizedVersion,\n query,\n limit ?? 10,\n );\n\n if (initialResults.length === 0) {\n return [];\n }\n\n // Group initial results by URL\n const resultsByUrl = this.groupResultsByUrl(initialResults);\n\n // Process each URL group with appropriate strategy\n const results: StoreSearchResult[] = [];\n for (const [url, urlResults] of resultsByUrl.entries()) {\n // Cluster chunks based on distance\n const clusters = this.clusterChunksByDistance(urlResults);\n\n // Process each cluster as a separate result\n for (const cluster of clusters) {\n const result = await this.processUrlGroup(\n library,\n normalizedVersion,\n url,\n cluster,\n );\n results.push(result);\n }\n }\n\n // Sort all results by score descending\n // This ensures that if a highly relevant chunk was split from a less relevant one,\n // the highly relevant one appears first in the final list.\n results.sort((a, b) => (b.score ?? 0) - (a.score ?? 0));\n\n return results;\n }\n\n /**\n * Groups search results by URL.\n */\n private groupResultsByUrl(\n results: (DbPageChunk & DbChunkRank)[],\n ): Map<string, (DbPageChunk & DbChunkRank)[]> {\n const resultsByUrl = new Map<string, (DbPageChunk & DbChunkRank)[]>();\n\n for (const result of results) {\n const url = result.url;\n if (!resultsByUrl.has(url)) {\n resultsByUrl.set(url, []);\n }\n const urlResults = resultsByUrl.get(url);\n if (urlResults) {\n urlResults.push(result);\n }\n }\n\n return resultsByUrl;\n }\n\n /**\n * Processes a group of search results from the same URL using appropriate strategy.\n */\n private async processUrlGroup(\n library: string,\n version: string,\n url: string,\n initialChunks: (DbPageChunk & DbChunkRank)[],\n ): Promise<StoreSearchResult> {\n // Extract processed and source MIME types from page-level fields.\n // Convert null to undefined for consistency.\n const mimeType =\n initialChunks.length > 0 ? (initialChunks[0].content_type ?? undefined) : undefined;\n const sourceMimeType =\n initialChunks.length > 0\n ? (initialChunks[0].source_content_type ?? undefined)\n : undefined;\n // The identity can be one this crawl derived rather than one the site\n // serves, so a caller linking to the source needs the location that\n // actually answered. Undefined when the two coincide.\n const contentUrl =\n initialChunks.length > 0 ? (initialChunks[0].content_url ?? undefined) : undefined;\n\n // Find the maximum score from the initial results\n const maxScore = Math.max(...initialChunks.map((chunk) => chunk.score));\n\n // Create appropriate assembly strategy based on content type\n const strategy = createContentAssemblyStrategy(mimeType, this.config);\n\n // Use strategy to select and assemble chunks\n const selectedChunks = await strategy.selectChunks(\n library,\n version,\n initialChunks,\n this.documentStore,\n );\n\n const content = strategy.assembleContent(selectedChunks);\n\n return {\n url,\n contentUrl,\n content,\n score: maxScore,\n mimeType,\n sourceMimeType,\n };\n }\n\n /**\n * Clusters chunks based on their sort_order distance.\n * Chunks within maxChunkDistance of each other are grouped together.\n *\n * @param chunks The list of chunks to cluster (must be from the same URL).\n * @returns An array of chunk clusters, where each cluster is an array of chunks.\n */\n private clusterChunksByDistance(\n chunks: (DbPageChunk & DbChunkRank)[],\n ): (DbPageChunk & DbChunkRank)[][] {\n if (chunks.length === 0) return [];\n if (chunks.length === 1) return [chunks];\n\n // Sort chunks by sort_order, then by id for deterministic stability\n const sortedChunks = [...chunks].sort((a, b) => {\n const diff = a.sort_order - b.sort_order;\n if (diff !== 0) return diff;\n return a.id.localeCompare(b.id);\n });\n\n const clusters: (DbPageChunk & DbChunkRank)[][] = [];\n let currentCluster: (DbPageChunk & DbChunkRank)[] = [sortedChunks[0]];\n // Ensure maxChunkDistance is non-negative\n const maxChunkDistance = Math.max(0, this.config.assembly.maxChunkDistance);\n\n for (let i = 1; i < sortedChunks.length; i++) {\n const currentChunk = sortedChunks[i];\n const previousChunk = sortedChunks[i - 1];\n\n // Check distance between current and previous chunk\n const distance = currentChunk.sort_order - previousChunk.sort_order;\n\n if (distance <= maxChunkDistance) {\n // Close enough - add to current cluster\n currentCluster.push(currentChunk);\n } else {\n // Too far - start new cluster\n clusters.push(currentCluster);\n currentCluster = [currentChunk];\n }\n }\n\n // Add the last cluster\n clusters.push(currentCluster);\n\n return clusters;\n }\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { Database } from \"better-sqlite3\";\nimport { logger } from \"../utils/logger\";\nimport { getProjectRoot } from \"../utils/paths\";\nimport { StoreError } from \"./errors\";\n\n// Construct the absolute path to the migrations directory using the project root\nconst MIGRATIONS_DIR = path.join(getProjectRoot(), \"db\", \"migrations\");\nconst MIGRATIONS_TABLE = \"_schema_migrations\";\nconst MIGRATION_STEP_MARKER = /^\\s*--\\s*@migration-step\\s+(.+?)\\s*$/;\nconst VECTOR_PARTITION_MIGRATION = \"014-rebuild-vector-partition-keys.sql\";\nconst DEFAULT_VECTOR_DIMENSION = 1536;\nconst VECTOR_DIMENSION_TOKEN = \"__DOCUMENTS_VEC_DIMENSION__\";\nconst WAL_SIZE_LIMIT_BYTES = 64 * 1024 * 1024;\n\ninterface MigrationStep {\n label: string;\n sql: string;\n}\n\n/**\n * Splits migration SQL into executable blocks using full-line migration markers.\n * SQL before the first marker is treated as an implicit prepare block, and SQL\n * without markers is treated as a single migration block.\n *\n * @param sql The migration SQL file contents.\n * @returns Executable migration steps in source order.\n */\nexport function parseMigrationSteps(sql: string): MigrationStep[] {\n const lines = sql.split(/\\r?\\n/);\n const steps: MigrationStep[] = [];\n let currentLabel = \"prepare\";\n let currentLines: string[] = [];\n let hasMarkers = false;\n\n const pushCurrentStep = () => {\n const currentSql = currentLines.join(\"\\n\").trim();\n if (hasExecutableSql(currentSql)) {\n steps.push({\n label: hasMarkers ? currentLabel : \"migration\",\n sql: currentSql,\n });\n }\n currentLines = [];\n };\n\n for (const line of lines) {\n const marker = line.match(MIGRATION_STEP_MARKER);\n if (marker) {\n hasMarkers = true;\n pushCurrentStep();\n currentLabel = marker[1].trim();\n continue;\n }\n\n currentLines.push(line);\n }\n\n pushCurrentStep();\n\n return steps;\n}\n\nfunction hasExecutableSql(sql: string): boolean {\n return sql\n .split(/\\r?\\n/)\n .some((line) => line.trim() !== \"\" && !line.trim().startsWith(\"--\"));\n}\n\nfunction formatDuration(ms: number): string {\n if (ms < 60_000) {\n return `${(ms / 1000).toFixed(1)}s`;\n }\n\n const minutes = Math.floor(ms / 60_000);\n const seconds = ((ms % 60_000) / 1000).toFixed(1).padStart(4, \"0\");\n return `${minutes}m ${seconds}s`;\n}\n\n/**\n * Ensures the migration tracking table exists in the database.\n * @param db The database instance.\n */\nfunction ensureMigrationsTable(db: Database): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS ${MIGRATIONS_TABLE} (\n id TEXT PRIMARY KEY,\n applied_at DATETIME DEFAULT CURRENT_TIMESTAMP\n );\n `);\n}\n\n/**\n * Retrieves the set of already applied migration IDs (filenames) from the tracking table.\n * @param db The database instance.\n * @returns A Set containing the IDs of applied migrations.\n */\nfunction getAppliedMigrations(db: Database): Set<string> {\n const stmt = db.prepare(`SELECT id FROM ${MIGRATIONS_TABLE}`);\n const rows = stmt.all() as Array<{ id: string }>;\n return new Set(rows.map((row) => row.id));\n}\n\nfunction executeMigrationSql(\n db: Database,\n filename: string,\n sql: string,\n migrationIndex: number,\n migrationTotal: number,\n): void {\n const steps = parseMigrationSteps(sql);\n const migrationStartedAt = Date.now();\n\n logger.info(`🔄 Applying migration ${migrationIndex}/${migrationTotal} ${filename}`);\n\n try {\n if (steps.length === 0) {\n logger.info(\" . no executable SQL (0.0s)\");\n }\n\n for (const step of steps) {\n const stepStartedAt = Date.now();\n db.exec(step.sql);\n logger.info(` . ${step.label} (${formatDuration(Date.now() - stepStartedAt)})`);\n }\n\n logger.info(\n `✅ Completed migration ${migrationIndex}/${migrationTotal} ${filename} in ${formatDuration(\n Date.now() - migrationStartedAt,\n )}`,\n );\n } catch (error) {\n logger.error(\n `❌ Failed migration ${migrationIndex}/${migrationTotal} ${filename} after ${formatDuration(\n Date.now() - migrationStartedAt,\n )}`,\n );\n throw error;\n }\n}\n\nfunction getCurrentVectorDimension(db: Database): number {\n const row = db\n .prepare(\n \"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'documents_vec';\",\n )\n .get() as { sql: string } | undefined;\n const match = row?.sql.match(/embedding\\s+FLOAT\\s*\\[\\s*(\\d+)\\s*]/i);\n const dimension = match ? Number(match[1]) : DEFAULT_VECTOR_DIMENSION;\n\n if (!Number.isInteger(dimension) || dimension < 1) {\n throw new StoreError(\n `Invalid documents_vec embedding dimension in schema: ${row?.sql ?? \"missing\"}`,\n );\n }\n\n return dimension;\n}\n\nfunction prepareMigrationSql(db: Database, filename: string, sql: string): string {\n if (filename !== VECTOR_PARTITION_MIGRATION) {\n return sql;\n }\n\n return sql.replaceAll(VECTOR_DIMENSION_TOKEN, String(getCurrentVectorDimension(db)));\n}\n\n/**\n * Applies pending database migrations found in the migrations directory.\n * Migrations are expected to be .sql files with sequential prefixes (e.g., 001-, 002-).\n * It tracks applied migrations in the _schema_migrations table.\n *\n * @param db The better-sqlite3 database instance.\n * @param options Optional runtime configuration.\n * @throws {StoreError} If any migration fails.\n */\nexport async function applyMigrations(\n db: Database,\n options?: {\n maxRetries?: number;\n retryDelayMs?: number;\n },\n): Promise<void> {\n const maxRetries = options?.maxRetries ?? 5;\n const retryDelayMs = options?.retryDelayMs ?? 300;\n // Keep journaling enabled so schema migrations can roll back if any DDL step fails.\n try {\n db.pragma(\"synchronous = NORMAL\");\n db.pragma(\"mmap_size = 268435456\"); // 256MB memory mapping\n db.pragma(\"cache_size = -64000\"); // 64MB cache (default is ~2MB)\n db.pragma(\"temp_store = MEMORY\"); // Store temporary data in memory\n logger.debug(\"Applied safe migration pragmas\");\n } catch (_error) {\n logger.warn(\"⚠️ Could not apply all migration pragmas\");\n }\n\n const overallTransaction = db.transaction(() => {\n logger.debug(\"Checking database migrations...\");\n ensureMigrationsTable(db);\n const appliedMigrations = getAppliedMigrations(db);\n\n if (!fs.existsSync(MIGRATIONS_DIR)) {\n throw new StoreError(\"Migrations directory not found\");\n }\n\n const migrationFiles = fs\n .readdirSync(MIGRATIONS_DIR)\n .filter((file) => file.endsWith(\".sql\"))\n .sort(); // Sort alphabetically, relying on naming convention (001-, 002-)\n\n const pendingMigrations = migrationFiles.filter(\n (filename) => !appliedMigrations.has(filename),\n );\n\n if (pendingMigrations.length > 0) {\n logger.info(`🔄 Applying ${pendingMigrations.length} database migration(s)...`);\n }\n\n let appliedCount = 0;\n for (const [index, filename] of pendingMigrations.entries()) {\n const filePath = path.join(MIGRATIONS_DIR, filename);\n const sql = prepareMigrationSql(db, filename, fs.readFileSync(filePath, \"utf8\"));\n\n // Execute migration and record it directly within the overall transaction.\n // executeMigrationSql() already logs progress and failure with timing info,\n // so avoid re-logging the same event here.\n try {\n executeMigrationSql(db, filename, sql, index + 1, pendingMigrations.length);\n const insertStmt = db.prepare(`INSERT INTO ${MIGRATIONS_TABLE} (id) VALUES (?)`);\n insertStmt.run(filename);\n appliedCount++;\n } catch (error) {\n // Re-throw to ensure the overall transaction rolls back\n throw new StoreError(`Migration failed: ${filename}`, error);\n }\n }\n\n if (appliedCount > 0) {\n logger.info(`✅ Successfully applied ${appliedCount} migration(s)`);\n } else {\n logger.debug(\"Database schema is up to date\");\n }\n\n // Return the count of applied migrations so we know if VACUUM is needed\n return appliedCount;\n });\n\n let retries = 0;\n let appliedMigrationsCount = 0;\n\n while (true) {\n try {\n // Start a single IMMEDIATE transaction for the entire migration process\n appliedMigrationsCount = overallTransaction.immediate(); // Execute the encompassing transaction\n logger.debug(\"Database migrations completed successfully\");\n\n // Only run VACUUM if migrations were actually applied\n if (appliedMigrationsCount > 0) {\n try {\n logger.debug(\n `Running VACUUM after applying ${appliedMigrationsCount} migration(s)...`,\n );\n db.exec(\"VACUUM\");\n logger.debug(\"Database vacuum completed successfully\");\n } catch (error) {\n logger.warn(`⚠️ Could not vacuum database after migrations: ${error}`);\n // Don't fail the migration process if vacuum fails\n }\n } else {\n logger.debug(\"Skipping VACUUM - no migrations were applied\");\n }\n\n break; // Success\n } catch (error) {\n // biome-ignore lint/suspicious/noExplicitAny: error can be any\n if ((error as any)?.code === \"SQLITE_BUSY\" && retries < maxRetries) {\n retries++;\n logger.warn(\n `⚠️ Migrations busy (SQLITE_BUSY), retrying attempt ${retries}/${maxRetries} in ${retryDelayMs}ms...`,\n );\n await new Promise((resolve) => setTimeout(resolve, retryDelayMs));\n } else {\n // biome-ignore lint/suspicious/noExplicitAny: error can be any\n if ((error as any)?.code === \"SQLITE_BUSY\") {\n logger.error(\n `❌ Migrations still busy after ${maxRetries} retries. Giving up: ${error}`,\n );\n }\n // Ensure StoreError is thrown for consistent handling\n if (error instanceof StoreError) {\n throw error;\n }\n throw new StoreError(\"Failed during migration process\", error);\n }\n }\n }\n\n // Configure production-ready settings after migrations\n try {\n // Enable WAL mode for better concurrency (allows readers while writing)\n db.pragma(\"journal_mode = WAL\");\n\n // Configure WAL autocheckpoint to prevent unbounded growth\n db.pragma(\"wal_autocheckpoint = 1000\"); // Checkpoint every 1000 pages (~4MB)\n\n // SQLite reuses the WAL file after a checkpoint but never shrinks it, so one\n // large write (a bulk scrape, a migration, VACUUM) would leave it at its peak\n // size until the last connection closes. Trim it back once the WAL resets.\n db.pragma(`journal_size_limit = ${WAL_SIZE_LIMIT_BYTES}`);\n\n // Set busy timeout for better handling of concurrent access\n db.pragma(\"busy_timeout = 30000\"); // 30 seconds\n\n // Enable foreign key constraints for data integrity\n db.pragma(\"foreign_keys = ON\");\n\n // Set synchronous to NORMAL for good balance of safety and performance\n db.pragma(\"synchronous = NORMAL\");\n\n logger.debug(\n \"Applied production database configuration (WAL mode, autocheckpoint, WAL size limit, foreign keys, busy timeout)\",\n );\n } catch (_error) {\n logger.warn(\"⚠️ Could not apply all production database settings\");\n }\n}\n","import { statSync } from \"node:fs\";\nimport type { Embeddings } from \"@langchain/core/embeddings\";\nimport Database, { type Database as DatabaseType } from \"better-sqlite3\";\nimport * as sqliteVec from \"sqlite-vec\";\nimport type { ScrapeResult, ScraperOptions } from \"../scraper/types\";\nimport { withoutRunOnlyOptions } from \"../scraper/types\";\nimport { type AppConfig, isVectorDimensionExplicit } from \"../utils/config\";\nimport { logger } from \"../utils/logger\";\nimport { MimeTypeUtils } from \"../utils/mimeTypeUtils\";\nimport { compareVersionsDescending } from \"../utils/version\";\nimport { applyMigrations } from \"./applyMigrations\";\nimport { EmbeddingConfig, type EmbeddingModelConfig } from \"./embeddings/EmbeddingConfig\";\nimport {\n areCredentialsAvailable,\n createEmbeddingModel,\n ModelConfigurationError,\n UnsupportedProviderError,\n} from \"./embeddings/EmbeddingFactory\";\nimport { FixedDimensionEmbeddings } from \"./embeddings/FixedDimensionEmbeddings\";\nimport {\n ConnectionError,\n DimensionError,\n EmbeddingError,\n EmbeddingModelChangedError,\n InvalidLibraryNameError,\n LibraryAlreadyExistsError,\n quoteName,\n StoreError,\n VersionAlreadyExistsError,\n} from \"./errors\";\nimport type {\n ActivityHistory,\n CompactResult,\n DbChunkMetadata,\n DbChunkRank,\n LibraryVersionSummary,\n ListVersionChunksOptions,\n ListVersionChunksResult,\n PageListItem,\n ResolvedVersion,\n StoredScraperOptions,\n VersionChunkListItem,\n VersionChunkStats,\n VersionComposition,\n} from \"./types\";\nimport {\n type DbChunk,\n type DbLibraryVersion,\n type DbPage,\n type DbPageChunk,\n type DbQueryResult,\n type DbVersion,\n type DbVersionWithLibrary,\n denormalizeVersionName,\n describeLibraryNameProblem,\n type ExistingTargetPolicy,\n normalizeLibraryDisplayName,\n normalizeLibraryName,\n normalizeVersionLabel,\n normalizeVersionName,\n type VersionScraperOptions,\n type VersionStatus,\n} from \"./types\";\n\n/**\n * How many full-text candidates are sorted by score alone before the\n * deterministic tie-break, as a multiple of the candidates kept. Sorting every\n * match by URL would read each match's page; sorting a window this size reads\n * a few dozen, and only a tie spanning more rows than the window at the\n * cut-off could still fall back to storage order.\n */\nconst FTS_TIE_WINDOW_FACTOR = 2;\n\n/**\n * Orders search results that score the same: by page URL, then by position on\n * the page. Without it, ties fall to storage order, which depends on when and\n * how fast each page was indexed.\n */\nfunction compareTies(\n a: { url?: string; sort_order?: number },\n b: { url?: string; sort_order?: number },\n): number {\n // Code-point order, as SQLite's default BINARY collation sorts them\n const urlA = a.url ?? \"\";\n const urlB = b.url ?? \"\";\n if (urlA !== urlB) return urlA < urlB ? -1 : 1;\n return (a.sort_order ?? 0) - (b.sort_order ?? 0);\n}\n\ninterface RawSearchResult extends DbChunk {\n // Page fields joined from pages table\n url?: string;\n title?: string | null;\n source_content_type?: string | null;\n content_type?: string | null;\n content_url?: string | null;\n // Search scoring fields, null when that search method did not return the chunk\n vec_score?: number | null;\n fts_score?: number | null;\n}\n\ninterface RankedResult extends RawSearchResult {\n vec_rank?: number;\n fts_rank?: number;\n rrf_score: number;\n}\n\n/**\n * Limits a `documents_fts f` scan to one version's chunks. Binds the version id.\n *\n * The id list comes from the covering indexes on `pages(version_id, url)` and\n * `documents(page_id, sort_order)`, so a full-text hit in another library is\n * dropped without reading its row. Joining documents and pages per hit\n * instead costs a lookup for every match in the store (#550).\n *\n * The unary `+` keeps SQLite from handing the `IN` list to FTS5 as a rowid\n * constraint, which would rerun the whole match once per id (the plan shows\n * `INDEX 0:=M4` instead of `0:M4`).\n */\nconst VERSION_FTS_FILTER = `+f.rowid IN (\n SELECT vd.id FROM pages vp JOIN documents vd ON vd.page_id = vp.id\n WHERE vp.version_id = ?\n)`;\n\ninterface EmbeddingBatchContext {\n url: string;\n batchIndex: number;\n batchTextCount: number;\n batchChars: number;\n totalChunks: number;\n}\n\n/**\n * English stop words that full-text search does not look up on their own.\n *\n * FTS5 has no stop words, so a word like \"the\" or \"to\" matches most chunks of\n * every library. Looking it up as its own OR term reads its whole doclist across\n * the store twice (once to match, once for bm25's row counts), yet it barely\n * moves the ranking: bm25 gives a term found in more than half the rows a weight\n * of 1e-6. These words still count inside the exact full-query phrase and inside\n * phrases the user put in quotes.\n *\n * This is the default English stop word list of Apache Lucene\n * (`EnglishAnalyzer.ENGLISH_STOP_WORDS_SET`, also Elasticsearch's `_english_`).\n * Longer lists such as Snowball's also drop \"how\", \"what\", \"I\" and \"do\". Those\n * are in far fewer chunks, so they still carry real bm25 weight and dropping\n * them reorders results. Entries are compared after lower-casing the query word\n * and trimming punctuation from it.\n */\nconst FTS_STOP_WORDS: ReadonlySet<string> = new Set(\n (\n \"a an and are as at be but by for if in into is it no not of on or such \" +\n \"that the their then there these they this to was will with\"\n ).split(\" \"),\n);\n\n/** Whether a word from an unquoted part of a search query is in `FTS_STOP_WORDS`. */\nfunction isFtsStopWord(word: string): boolean {\n return FTS_STOP_WORDS.has(\n word.toLowerCase().replace(/^[^\\p{L}\\p{N}]+|[^\\p{L}\\p{N}]+$/gu, \"\"),\n );\n}\n\n/**\n * Whether a competing representation should be turned away.\n *\n * A page reachable as both a published Markdown file and an HTML page produces\n * two writes under one identity, and which arrives last is an accident of crawl\n * order. Markdown the site publishes is what its authors wrote for machine\n * consumption, so it wins; converting HTML ourselves is the fallback for sites\n * offering nothing better. A `.md` URL answered as `text/plain` counts as\n * Markdown — see `WebScraperStrategy.asMarkdownRepresentation`.\n *\n * Only applies between representations seen in the same crawl. A first write\n * for an identity always lands, so a later crawl's answer supersedes an earlier\n * crawl's rather than being blocked by it.\n */\nfunction losesToStoredRepresentation(\n stored: PageIdRow | undefined,\n incomingSourceContentType: string | null | undefined,\n isAdditionalRepresentation: boolean | undefined,\n): boolean {\n if (!stored || !isAdditionalRepresentation) return false;\n return (\n MimeTypeUtils.isMarkdown(stored.source_content_type ?? \"\") &&\n !MimeTypeUtils.isMarkdown(incomingSourceContentType ?? \"\")\n );\n}\n\n/** The row `getPageId` returns. Declared once so its two readers agree. */\ninterface PageIdRow {\n id: number;\n source_content_type: string | null;\n}\n\n/**\n * Manages document storage and retrieval using SQLite with vector and full-text search capabilities.\n * Provides direct access to SQLite with prepared statements to store and query document\n * embeddings along with their metadata. Supports versioned storage of documents for different\n * libraries, enabling version-specific document retrieval and searches.\n */\nexport class DocumentStore {\n private readonly config: AppConfig;\n private readonly dbPath: string;\n\n private readonly db: DatabaseType;\n private embeddings: Embeddings | null = null;\n private dbDimension: number;\n private readonly searchWeightVec: number;\n private readonly searchWeightFts: number;\n private readonly searchOverfetchFactor: number;\n private readonly vectorSearchMultiplier: number;\n private readonly splitterMaxChunkSize: number;\n private readonly embeddingBatchSize: number;\n private readonly embeddingBatchChars: number;\n private readonly embeddingInitTimeoutMs: number;\n private modelDimension: number | null = null;\n private readonly embeddingConfig?: EmbeddingModelConfig | null;\n private isVectorSearchEnabled: boolean = false;\n\n /**\n * Returns the active embedding configuration if vector search is enabled,\n * or null if embeddings are disabled (no config provided or credentials unavailable).\n */\n getActiveEmbeddingConfig(): EmbeddingModelConfig | null {\n if (!this.isVectorSearchEnabled || !this.embeddingConfig) {\n return null;\n }\n return this.embeddingConfig;\n }\n\n private statements!: {\n getById: Database.Statement<[bigint]>;\n // Updated for new schema - documents table now uses page_id\n insertDocument: Database.Statement<[number, string, string, number]>;\n // Updated for new schema - embeddings stored directly in documents table\n insertEmbedding: Database.Statement<[Buffer, bigint]>;\n // New statement for pages table\n insertPage: Database.Statement<\n [\n number,\n string,\n string,\n string | null,\n string | null,\n string | null,\n string | null,\n number | null,\n string | null,\n ]\n >;\n getPageId: Database.Statement<[number, string]>;\n deleteDocuments: Database.Statement<[string, string]>;\n deleteDocumentsByPageId: Database.Statement<[number]>;\n deletePage: Database.Statement<[number]>;\n deletePages: Database.Statement<[string, string]>;\n queryVersions: Database.Statement<[string]>;\n checkExists: Database.Statement<[string, string]>;\n queryLibraryVersions: Database.Statement<[]>;\n getChildChunks: Database.Statement<\n [string, string, string, number, string, bigint, number]\n >;\n getPrecedingSiblings: Database.Statement<\n [string, string, string, bigint, string, number]\n >;\n getSubsequentSiblings: Database.Statement<\n [string, string, string, bigint, string, number]\n >;\n getParentChunk: Database.Statement<[string, string, string, string, bigint]>;\n insertLibrary: Database.Statement<[string, string]>;\n getLibraryIdByName: Database.Statement<[string]>;\n getLibraryById: Database.Statement<[number]>;\n // New version-related statements\n insertVersion: Database.Statement<[number, string | null]>;\n resolveVersionId: Database.Statement<[number, string | null]>;\n getVersionById: Database.Statement<[number]>;\n queryVersionsByLibraryId: Database.Statement<[number]>;\n // Status tracking statements\n updateVersionStatus: Database.Statement<[string, string | null, number]>;\n updateVersionProgress: Database.Statement<[number, number, number | null, number]>;\n getVersionsByStatus: Database.Statement<string[]>;\n markVersionsAlive: Database.Statement<[string]>;\n claimInterruptedVersion: Database.Statement<[number, string | null]>;\n // Scraper options statements\n updateVersionScraperOptions: Database.Statement<[string, string, number]>;\n getVersionWithOptions: Database.Statement<[number]>;\n getVersionsBySourceUrl: Database.Statement<[string]>;\n // Version and library deletion statements\n deleteVersionById: Database.Statement<[number]>;\n deleteLibraryById: Database.Statement<[number]>;\n countVersionsByLibraryId: Database.Statement<[number]>;\n getVersionId: Database.Statement<[string, string]>;\n getPagesByVersionId: Database.Statement<[number]>;\n };\n\n /**\n * Calculates Reciprocal Rank Fusion score for a result with configurable weights\n */\n private calculateRRF(vecRank?: number, ftsRank?: number, k = 60): number {\n let rrf = 0;\n if (vecRank !== undefined) {\n rrf += this.searchWeightVec / (k + vecRank);\n }\n if (ftsRank !== undefined) {\n rrf += this.searchWeightFts / (k + ftsRank);\n }\n return rrf;\n }\n\n /**\n * Assigns ranks to search results based on their scores. A result gets a\n * rank only from the search methods that returned it, so a chunk found by\n * one method scores that method's RRF term alone.\n */\n private assignRanks(results: RawSearchResult[]): RankedResult[] {\n // Create maps to store ranks\n const vecRanks = new Map<number, number>();\n const ftsRanks = new Map<number, number>();\n\n // Sort by vector scores and assign ranks\n results\n .filter((r) => r.vec_score != null)\n .sort((a, b) => (b.vec_score ?? 0) - (a.vec_score ?? 0) || compareTies(a, b))\n .forEach((result, index) => {\n vecRanks.set(Number(result.id), index + 1);\n });\n\n // Sort by BM25 scores and assign ranks\n results\n .filter((r) => r.fts_score != null)\n .sort((a, b) => (b.fts_score ?? 0) - (a.fts_score ?? 0) || compareTies(a, b))\n .forEach((result, index) => {\n ftsRanks.set(Number(result.id), index + 1);\n });\n\n // Combine results with ranks and calculate RRF\n return results.map((result) => ({\n ...result,\n vec_rank: vecRanks.get(Number(result.id)),\n fts_rank: ftsRanks.get(Number(result.id)),\n rrf_score: this.calculateRRF(\n vecRanks.get(Number(result.id)),\n ftsRanks.get(Number(result.id)),\n ),\n }));\n }\n\n constructor(dbPath: string, appConfig: AppConfig) {\n if (!dbPath) {\n throw new StoreError(\"Missing required database path\");\n }\n this.dbPath = dbPath;\n this.config = appConfig;\n this.dbDimension = this.config.embeddings.vectorDimension;\n this.searchWeightVec = this.config.search.weightVec;\n this.searchWeightFts = this.config.search.weightFts;\n this.searchOverfetchFactor = this.config.search.overfetchFactor;\n this.vectorSearchMultiplier = this.config.search.vectorMultiplier;\n this.splitterMaxChunkSize = this.config.splitter.maxChunkSize;\n this.embeddingBatchSize = this.config.embeddings.batchSize;\n this.embeddingBatchChars = this.config.embeddings.batchChars;\n this.embeddingInitTimeoutMs = this.config.embeddings.initTimeoutMs;\n\n // Only establish database connection in constructor\n this.db = new Database(dbPath);\n\n // Store embedding config for later initialization\n this.embeddingConfig = this.resolveEmbeddingConfig(appConfig.app.embeddingModel);\n }\n\n private resolveEmbeddingConfig(modelSpec: string): EmbeddingModelConfig | null {\n const resolvedSpec = modelSpec;\n if (!resolvedSpec) {\n logger.debug(\"No embedding model specified. Embeddings are disabled.\");\n return null;\n }\n\n try {\n logger.debug(`Resolving embedding configuration for model: ${resolvedSpec}`);\n return EmbeddingConfig.parseEmbeddingConfig(resolvedSpec);\n } catch (error) {\n logger.debug(`Failed to resolve embedding configuration: ${error}`);\n return null;\n }\n }\n\n /**\n * Sets up prepared statements for database queries\n */\n private prepareStatements(): void {\n const statements = {\n getById: this.db.prepare<[bigint]>(\n `SELECT d.id, d.page_id, d.content, json(d.metadata) as metadata, d.sort_order, d.created_at, p.url, p.title, p.source_content_type, p.content_type, p.content_url \n FROM documents d\n JOIN pages p ON d.page_id = p.id\n WHERE d.id = ?`,\n ),\n // Updated for new schema\n insertDocument: this.db.prepare<[number, string, string, number]>(\n \"INSERT INTO documents (page_id, content, metadata, sort_order) VALUES (?, ?, ?, ?)\",\n ),\n insertEmbedding: this.db.prepare<[Buffer, bigint]>(\n \"UPDATE documents SET embedding = ? WHERE id = ?\",\n ),\n insertPage: this.db.prepare<\n [\n number,\n string,\n string,\n string | null,\n string | null,\n string | null,\n string | null,\n number | null,\n string | null,\n ]\n >(\n \"INSERT INTO pages (version_id, url, title, etag, last_modified, source_content_type, content_type, depth, content_url) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(version_id, url) DO UPDATE SET title = excluded.title, source_content_type = excluded.source_content_type, content_type = excluded.content_type, etag = excluded.etag, last_modified = excluded.last_modified, depth = excluded.depth, content_url = excluded.content_url\",\n ),\n // Returns the row shape described by `PageIdRow`.\n getPageId: this.db.prepare<[number, string]>(\n \"SELECT id, source_content_type FROM pages WHERE version_id = ? AND url = ?\",\n ),\n // Plain insert: callers look the library up first, inside the same transaction.\n insertLibrary: this.db.prepare<[string, string]>(\n \"INSERT INTO libraries (name, display_name) VALUES (?, ?)\",\n ),\n getLibraryIdByName: this.db.prepare<[string]>(\n \"SELECT id, display_name FROM libraries WHERE name = ?\",\n ),\n getLibraryById: this.db.prepare<[number]>(\"SELECT * FROM libraries WHERE id = ?\"),\n // New version-related statements\n insertVersion: this.db.prepare<[number, string]>(\n \"INSERT INTO versions (library_id, name, status) VALUES (?, ?, 'not_indexed') ON CONFLICT(library_id, name) DO NOTHING\",\n ),\n resolveVersionId: this.db.prepare<[number, string]>(\n \"SELECT id FROM versions WHERE library_id = ? AND name = ?\",\n ),\n getVersionById: this.db.prepare<[number]>(\"SELECT * FROM versions WHERE id = ?\"),\n queryVersionsByLibraryId: this.db.prepare<[number]>(\n \"SELECT * FROM versions WHERE library_id = ? ORDER BY name\",\n ),\n deleteDocuments: this.db.prepare<[string, string]>(\n `DELETE FROM documents \n WHERE page_id IN (\n SELECT p.id FROM pages p\n JOIN versions v ON p.version_id = v.id\n JOIN libraries l ON v.library_id = l.id\n WHERE l.name = ? AND COALESCE(v.name, '') = COALESCE(?, '')\n )`,\n ),\n deleteDocumentsByPageId: this.db.prepare<[number]>(\n \"DELETE FROM documents WHERE page_id = ?\",\n ),\n deletePage: this.db.prepare<[number]>(\"DELETE FROM pages WHERE id = ?\"),\n deletePages: this.db.prepare<[string, string]>(\n `DELETE FROM pages \n WHERE version_id IN (\n SELECT v.id FROM versions v\n JOIN libraries l ON v.library_id = l.id\n WHERE l.name = ? AND COALESCE(v.name, '') = COALESCE(?, '')\n )`,\n ),\n getDocumentBySort: this.db.prepare<[string, string]>(\n `SELECT d.id\n FROM documents d\n JOIN pages p ON d.page_id = p.id\n JOIN versions v ON p.version_id = v.id\n JOIN libraries l ON v.library_id = l.id\n WHERE l.name = ?\n AND COALESCE(v.name, '') = COALESCE(?, '')\n LIMIT 1`,\n ),\n queryVersions: this.db.prepare<[string]>(\n `SELECT DISTINCT v.name\n FROM versions v\n JOIN libraries l ON v.library_id = l.id\n WHERE l.name = ?\n ORDER BY v.name`,\n ),\n checkExists: this.db.prepare<[string, string]>(\n `SELECT d.id FROM documents d\n JOIN pages p ON d.page_id = p.id\n JOIN versions v ON p.version_id = v.id\n JOIN libraries l ON v.library_id = l.id\n WHERE l.name = ?\n AND COALESCE(v.name, '') = COALESCE(?, '')\n LIMIT 1`,\n ),\n // Library/version aggregation including versions without documents and status/progress fields\n queryLibraryVersions: this.db.prepare<[]>(\n `SELECT\n l.display_name as library,\n COALESCE(v.name, '') as version,\n v.id as versionId,\n v.status as status,\n v.error_message as errorMessage,\n v.progress_pages as progressPages,\n v.progress_max_pages as progressMaxPages,\n v.progress_pages_indexed as progressPagesIndexed,\n v.source_url as sourceUrl,\n -- \"Last indexed\" = when the version was last (re)indexed. Use the\n -- version's updated_at (bumped on every status/progress change during\n -- a run, including refreshes) rather than MIN(p.created_at), which is\n -- the *first*-index time and never moves on refresh. Fall back to the\n -- oldest page for versions that predate status tracking.\n COALESCE(v.updated_at, MIN(p.created_at)) as indexedAt,\n COUNT(d.id) as documentCount,\n COUNT(DISTINCT p.url) as uniqueUrlCount\n FROM versions v\n JOIN libraries l ON v.library_id = l.id\n LEFT JOIN pages p ON p.version_id = v.id\n LEFT JOIN documents d ON d.page_id = p.id\n GROUP BY v.id\n ORDER BY l.name, version`,\n ),\n getChildChunks: this.db.prepare<\n [string, string, string, number, string, bigint, number]\n >(`\n SELECT d.id, d.page_id, d.content, json(d.metadata) as metadata, d.sort_order, d.created_at, p.url, p.title, p.source_content_type, p.content_type, p.content_url FROM documents d\n JOIN pages p ON d.page_id = p.id\n JOIN versions v ON p.version_id = v.id\n JOIN libraries l ON v.library_id = l.id\n WHERE l.name = ?\n AND COALESCE(v.name, '') = COALESCE(?, '')\n AND p.url = ?\n -- A child's path is the parent's path plus one element. Compare the path\n -- without its last element as JSON instead of using LIKE, so [\"AB\",\"X\"]\n -- is never a child of [\"A\"] and % or _ in a segment stay literal.\n -- The length check keeps an empty-path chunk from matching an empty parent.\n AND json_array_length(json_extract(d.metadata, '$.path')) = ?\n AND json_remove(json_extract(d.metadata, '$.path'), '$[#-1]') = json(?)\n AND d.sort_order > (SELECT sort_order FROM documents WHERE id = ?)\n ORDER BY d.sort_order\n LIMIT ?\n `),\n getPrecedingSiblings: this.db.prepare<\n [string, string, string, bigint, string, number]\n >(`\n SELECT d.id, d.page_id, d.content, json(d.metadata) as metadata, d.sort_order, d.created_at, p.url, p.title, p.source_content_type, p.content_type, p.content_url FROM documents d\n JOIN pages p ON d.page_id = p.id\n JOIN versions v ON p.version_id = v.id\n JOIN libraries l ON v.library_id = l.id\n WHERE l.name = ?\n AND COALESCE(v.name, '') = COALESCE(?, '')\n AND p.url = ?\n AND d.sort_order < (SELECT sort_order FROM documents WHERE id = ?)\n AND json_extract(d.metadata, '$.path') = ?\n ORDER BY d.sort_order DESC\n LIMIT ?\n `),\n getSubsequentSiblings: this.db.prepare<\n [string, string, string, bigint, string, number]\n >(`\n SELECT d.id, d.page_id, d.content, json(d.metadata) as metadata, d.sort_order, d.created_at, p.url, p.title, p.source_content_type, p.content_type, p.content_url FROM documents d\n JOIN pages p ON d.page_id = p.id\n JOIN versions v ON p.version_id = v.id\n JOIN libraries l ON v.library_id = l.id\n WHERE l.name = ?\n AND COALESCE(v.name, '') = COALESCE(?, '')\n AND p.url = ?\n AND d.sort_order > (SELECT sort_order FROM documents WHERE id = ?)\n AND json_extract(d.metadata, '$.path') = ?\n ORDER BY d.sort_order\n LIMIT ?\n `),\n getParentChunk: this.db.prepare<[string, string, string, string, bigint]>(`\n SELECT d.id, d.page_id, d.content, json(d.metadata) as metadata, d.sort_order, d.created_at, p.url, p.title, p.source_content_type, p.content_type, p.content_url FROM documents d\n JOIN pages p ON d.page_id = p.id\n JOIN versions v ON p.version_id = v.id\n JOIN libraries l ON v.library_id = l.id\n WHERE l.name = ?\n AND COALESCE(v.name, '') = COALESCE(?, '')\n AND p.url = ?\n AND json_extract(d.metadata, '$.path') = ?\n AND d.sort_order < (SELECT sort_order FROM documents WHERE id = ?)\n ORDER BY d.sort_order DESC\n LIMIT 1\n `),\n // Status tracking statements\n updateVersionStatus: this.db.prepare<[string, string | null, number]>(\n \"UPDATE versions SET status = ?, error_message = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?\",\n ),\n updateVersionProgress: this.db.prepare<[number, number, number | null, number]>(\n \"UPDATE versions SET progress_pages = ?, progress_max_pages = ?, progress_pages_indexed = COALESCE(?, progress_pages_indexed), updated_at = CURRENT_TIMESTAMP WHERE id = ?\",\n ),\n getVersionsByStatus: this.db.prepare<[string]>(\n \"SELECT v.*, l.display_name as library_name FROM versions v JOIN libraries l ON v.library_id = l.id WHERE v.status IN (SELECT value FROM json_each(?))\",\n ),\n markVersionsAlive: this.db.prepare<[string]>(\n `UPDATE versions SET updated_at = CURRENT_TIMESTAMP\n WHERE id IN (SELECT value FROM json_each(?)) AND status IN ('queued', 'running')`,\n ),\n claimInterruptedVersion: this.db.prepare<[number, string | null]>(\n `UPDATE versions SET updated_at = CURRENT_TIMESTAMP\n WHERE id = ? AND status IN ('queued', 'running') AND updated_at IS ?`,\n ),\n // Scraper options statements\n updateVersionScraperOptions: this.db.prepare<[string, string, number]>(\n \"UPDATE versions SET source_url = ?, scraper_options = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?\",\n ),\n getVersionWithOptions: this.db.prepare<[number]>(\n \"SELECT * FROM versions WHERE id = ?\",\n ),\n getVersionsBySourceUrl: this.db.prepare<[string]>(\n \"SELECT v.*, l.display_name as library_name FROM versions v JOIN libraries l ON v.library_id = l.id WHERE v.source_url = ? ORDER BY v.created_at DESC\",\n ),\n // Version and library deletion statements\n deleteVersionById: this.db.prepare<[number]>(\"DELETE FROM versions WHERE id = ?\"),\n deleteLibraryById: this.db.prepare<[number]>(\"DELETE FROM libraries WHERE id = ?\"),\n countVersionsByLibraryId: this.db.prepare<[number]>(\n \"SELECT COUNT(*) as count FROM versions WHERE library_id = ?\",\n ),\n getVersionId: this.db.prepare<[string, string]>(\n `SELECT v.id, v.library_id, l.display_name FROM versions v\n JOIN libraries l ON v.library_id = l.id\n WHERE l.name = ? AND COALESCE(v.name, '') = COALESCE(?, '')`,\n ),\n getPagesByVersionId: this.db.prepare<[number]>(\n \"SELECT * FROM pages WHERE version_id = ?\",\n ),\n };\n this.statements = statements;\n }\n\n /**\n * Pads a vector to the fixed database dimension by appending zeros.\n * Throws an error if the input vector is longer than the database dimension.\n */\n private padVector(vector: number[]): number[] {\n if (vector.length > this.dbDimension) {\n throw new Error(\n `Vector dimension ${vector.length} exceeds database dimension ${this.dbDimension}`,\n );\n }\n if (vector.length === this.dbDimension) {\n return vector;\n }\n return [...vector, ...new Array(this.dbDimension - vector.length).fill(0)];\n }\n\n /**\n * Reads the stored embedding model and dimension from the metadata table.\n * Returns null for each value that doesn't exist (e.g., first run or pre-metadata database).\n */\n getEmbeddingMetadata(): { model: string | null; dimension: string | null } {\n // Uses inline db.prepare() so this method works before prepareStatements() is called.\n // This is necessary because checkEmbeddingModelChange() runs before ensureVectorTable(),\n // and prepareStatements() cannot run until documents_vec exists (triggers reference it).\n const modelRow = this.db\n .prepare<[string]>(\"SELECT value FROM metadata WHERE key = ?\")\n .get(\"embedding_model\") as { value: string } | undefined;\n const dimensionRow = this.db\n .prepare<[string]>(\"SELECT value FROM metadata WHERE key = ?\")\n .get(\"embedding_dimension\") as { value: string } | undefined;\n return {\n model: modelRow?.value ?? null,\n dimension: dimensionRow?.value ?? null,\n };\n }\n\n /**\n * Persists the active embedding model and dimension to the metadata table.\n * Uses upsert (INSERT ON CONFLICT UPDATE) so it works for both first-run and subsequent updates.\n * Uses inline db.prepare() so this method works before prepareStatements() is called.\n */\n setEmbeddingMetadata(model: string, dimension: number): void {\n const stmt = this.db.prepare<[string, string]>(\n \"INSERT INTO metadata (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value\",\n );\n const persist = this.db.transaction(() => {\n stmt.run(\"embedding_model\", model);\n stmt.run(\"embedding_dimension\", String(dimension));\n });\n persist();\n }\n\n private getStoredDimensionForCurrentModel(): number | null {\n const config = this.embeddingConfig;\n if (!config) {\n return null;\n }\n\n const stored = this.getEmbeddingMetadata();\n if (stored.model !== config.modelSpec || stored.dimension === null) {\n return null;\n }\n\n const dimension = Number(stored.dimension);\n return Number.isInteger(dimension) && dimension >= 1 ? dimension : null;\n }\n\n /**\n * Compares the configured embedding model and dimension against stored metadata.\n * Throws EmbeddingModelChangedError if either has changed since the last run.\n *\n * Skipped when:\n * - No metadata exists (first run / upgrade from pre-metadata DB → silent initialization)\n * - No embedding model is configured (FTS-only mode)\n * - Credentials are unavailable for the configured provider (will fall back to FTS-only)\n */\n checkEmbeddingModelChange(): void {\n // Skip if no embedding config (FTS-only mode)\n if (!this.embeddingConfig) {\n return;\n }\n\n // Skip if credentials are unavailable (will fall back to FTS-only in initializeEmbeddings)\n if (!areCredentialsAvailable(this.embeddingConfig.provider)) {\n return;\n }\n\n const stored = this.getEmbeddingMetadata();\n\n // First run: no stored metadata → skip check (silent initialization)\n if (stored.model === null) {\n return;\n }\n\n const currentModel = this.embeddingConfig.modelSpec;\n const currentDimension = String(this.dbDimension);\n\n const modelChanged = stored.model !== currentModel;\n const dimensionChanged =\n stored.dimension !== null && stored.dimension !== currentDimension;\n\n if (modelChanged || dimensionChanged) {\n // A changed model is not probed before confirmation, so the dimension of\n // one that is neither a known model nor configured is not known yet\n const currentDimensionKnown =\n !modelChanged ||\n this.embeddingConfig.dimensions !== null ||\n isVectorDimensionExplicit(this.config);\n throw new EmbeddingModelChangedError(\n stored.model,\n stored.dimension,\n currentModel,\n currentDimensionKnown ? currentDimension : null,\n );\n }\n }\n\n /**\n * Invalidates all existing embedding vectors after a confirmed model/dimension change.\n * Sets all document embeddings to NULL, drops and recreates the vec table as empty,\n * and updates the metadata with the new model and dimension.\n *\n * After invalidation, FTS search continues working; vector search returns no results\n * until libraries are re-scraped.\n */\n invalidateAllVectors(newModel: string, newDimension: number): void {\n logger.warn(\n `⚠️ Invalidating all embedding vectors due to model/dimension change.\\n` +\n ` All libraries must be re-scraped to restore vector search.\\n` +\n ` Full-text search remains available for all existing documents.`,\n );\n\n // Clear all stored embedding blobs\n this.db.exec(\"UPDATE documents SET embedding = NULL\");\n\n // Drop and recreate vec table as empty with the new dimension\n this.db.exec(\"DROP TABLE IF EXISTS documents_vec\");\n this.createVectorTable(newDimension);\n\n // Update metadata to reflect the new configuration\n this.setEmbeddingMetadata(newModel, newDimension);\n\n logger.info(\n `✅ Embedding vectors invalidated. Metadata updated to: ${newModel} (${newDimension}d)`,\n );\n }\n\n /**\n * Initialize the embeddings client using the provided config.\n * If no embedding config is provided (null or undefined), embeddings will not be initialized.\n * This allows DocumentStore to be used without embeddings for FTS-only operations.\n *\n * Environment variables per provider:\n * - openai: OPENAI_API_KEY (and optionally OPENAI_API_BASE, OPENAI_ORG_ID)\n * - vertex: GOOGLE_APPLICATION_CREDENTIALS (path to service account JSON)\n * - gemini: GOOGLE_API_KEY\n * - aws: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION\n * - microsoft: Azure OpenAI credentials (AZURE_OPENAI_API_*)\n */\n private async initializeEmbeddings(): Promise<void> {\n // If embedding config is explicitly null or undefined, skip embedding initialization\n if (this.embeddingConfig === null || this.embeddingConfig === undefined) {\n logger.debug(\n \"Embedding initialization skipped (no config provided - FTS-only mode)\",\n );\n return;\n }\n\n const config = this.embeddingConfig;\n\n // Check if credentials are available for the provider\n if (!areCredentialsAvailable(config.provider)) {\n logger.warn(\n `⚠️ No credentials found for ${config.provider} embedding provider. Vector search is disabled.\\n` +\n ` Only full-text search will be available. To enable vector search, please configure the required\\n` +\n ` environment variables for ${config.provider} or choose a different provider.\\n` +\n ` See README.md for configuration options or run with --help for more details.`,\n );\n return; // Skip initialization, keep isVectorSearchEnabled = false\n }\n\n // Create embedding model\n try {\n if (this.embeddings === null) {\n this.embeddings = this.createEmbeddingClient(this.dbDimension);\n }\n\n const modelDimension = this.modelDimension ?? this.dbDimension;\n\n // For models wrapped in FixedDimensionEmbeddings with truncation enabled\n // (e.g., Gemini with MRL support), the effective output dimension is capped\n // at the target dimension. Use the effective dimension for validation.\n if (\n this.embeddings instanceof FixedDimensionEmbeddings &&\n this.embeddings.allowTruncate\n ) {\n this.modelDimension = Math.min(modelDimension, this.dbDimension);\n } else {\n this.modelDimension = modelDimension;\n }\n\n if (this.modelDimension > this.dbDimension) {\n throw new DimensionError(config.modelSpec, this.modelDimension, this.dbDimension);\n }\n\n // If we reach here, embeddings are successfully initialized\n this.isVectorSearchEnabled = true;\n logger.debug(\n `Embeddings initialized: ${config.provider}:${config.model} (${this.dbDimension}d)`,\n );\n\n // Persist the active embedding model identity for change detection on next startup\n this.setEmbeddingMetadata(config.modelSpec, this.dbDimension);\n } catch (error) {\n this.throwEmbeddingInitializationError(error, config);\n }\n }\n\n private createEmbeddingClient(vectorDimension: number): Embeddings {\n const config = this.embeddingConfig;\n if (!config) {\n throw new StoreError(\"Cannot create embedding client without configuration\");\n }\n\n return createEmbeddingModel(config.modelSpec, {\n requestTimeoutMs: this.config.embeddings.requestTimeoutMs,\n vectorDimension,\n });\n }\n\n private async detectEmbeddingDimension(embeddings: Embeddings): Promise<number> {\n const testPromise = embeddings.embedQuery(\"test\");\n let timeoutId: NodeJS.Timeout | undefined;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = setTimeout(() => {\n reject(\n new Error(\n `Embedding service connection timed out after ${this.embeddingInitTimeoutMs / 1000} seconds`,\n ),\n );\n }, this.embeddingInitTimeoutMs);\n });\n\n try {\n const testVector = await Promise.race([testPromise, timeoutPromise]);\n return testVector.length;\n } finally {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n }\n }\n\n private async resolveEffectiveEmbeddingDimension(\n options: { ignoreStoredMetadata?: boolean } = {},\n ): Promise<void> {\n this.validateVectorDimension(this.dbDimension);\n\n if (this.embeddingConfig === null || this.embeddingConfig === undefined) {\n return;\n }\n\n const config = this.embeddingConfig;\n if (!areCredentialsAvailable(config.provider)) {\n return;\n }\n\n try {\n const storedDimension = options.ignoreStoredMetadata\n ? null\n : this.getStoredDimensionForCurrentModel();\n if (storedDimension !== null) {\n if (!isVectorDimensionExplicit(this.config)) {\n this.dbDimension = storedDimension;\n }\n this.modelDimension = this.dbDimension;\n logger.debug(\n `Vector dimension loaded from metadata: ${this.dbDimension} for ${config.provider}:${config.model}`,\n );\n return;\n }\n\n const stored = this.getEmbeddingMetadata();\n if (\n !options.ignoreStoredMetadata &&\n stored.model !== null &&\n stored.model !== config.modelSpec\n ) {\n if (!isVectorDimensionExplicit(this.config) && config.dimensions !== null) {\n this.validateDetectedVectorDimension(\n config.dimensions,\n \"known model dimension lookup\",\n );\n this.dbDimension = config.dimensions;\n this.modelDimension = config.dimensions;\n }\n return;\n }\n\n let nativeDimension = config.dimensions;\n let nativeDimensionSource = \"known model dimension lookup\";\n\n if (nativeDimension === null) {\n this.embeddings = this.createEmbeddingClient(this.dbDimension);\n nativeDimension = await this.detectEmbeddingDimension(this.embeddings);\n nativeDimensionSource = \"embedding provider probe\";\n }\n\n this.validateDetectedVectorDimension(nativeDimension, nativeDimensionSource);\n\n if (config.dimensions === null) {\n EmbeddingConfig.setKnownModelDimensions(config.model, nativeDimension);\n }\n\n this.modelDimension = nativeDimension;\n\n if (!isVectorDimensionExplicit(this.config)) {\n this.dbDimension = nativeDimension;\n logger.info(\n `📐 Vector dimension auto-resolved to ${this.dbDimension} for ${config.provider}:${config.model}`,\n );\n }\n } catch (error) {\n this.throwEmbeddingInitializationError(error, config);\n }\n }\n\n private validateVectorDimension(dim: number): void {\n if (typeof dim !== \"number\" || !Number.isInteger(dim) || dim < 1) {\n throw new StoreError(\n `Invalid embeddings.vectorDimension: ${dim}. Must be a positive integer.`,\n );\n }\n }\n\n private validateDetectedVectorDimension(dim: number, source: string): void {\n if (typeof dim !== \"number\" || !Number.isInteger(dim) || dim < 1) {\n throw new StoreError(\n `Invalid detected embedding dimension from ${source}: ${dim}. Must be a positive integer.`,\n );\n }\n }\n\n private throwEmbeddingInitializationError(\n error: unknown,\n config: EmbeddingModelConfig,\n ): never {\n if (error instanceof Error) {\n if (\n error.message.includes(\"does not exist\") ||\n error.message.includes(\"MODEL_NOT_FOUND\")\n ) {\n throw new ModelConfigurationError(\n `Invalid embedding model: ${config.model}\\n` +\n ` The model \"${config.model}\" is not available or you don't have access to it.\\n` +\n \" See README.md for supported models or run with --help for more details.\",\n );\n }\n if (\n error.message.includes(\"API key\") ||\n error.message.includes(\"401\") ||\n error.message.includes(\"authentication\")\n ) {\n throw new ModelConfigurationError(\n `Authentication failed for ${config.provider} embedding provider\\n` +\n \" Please check your API key configuration.\\n\" +\n \" See README.md for configuration options or run with --help for more details.\",\n );\n }\n if (\n error.message.includes(\"timed out\") ||\n error.message.includes(\"ECONNREFUSED\") ||\n error.message.includes(\"ENOTFOUND\") ||\n error.message.includes(\"ETIMEDOUT\") ||\n error.message.includes(\"ECONNRESET\") ||\n error.message.includes(\"network\") ||\n error.message.includes(\"fetch failed\")\n ) {\n throw new ModelConfigurationError(\n `Failed to connect to ${config.provider} embedding service\\n` +\n ` ${error.message}\\n` +\n ` Please check that the embedding service is running and accessible.\\n` +\n ` If using a local model (e.g., Ollama), ensure the service is started.`,\n );\n }\n }\n\n throw error;\n }\n\n /**\n * Generates a safe FTS query by tokenizing the input and escaping for FTS5.\n *\n * Strategy:\n * - Quotes toggle between \"phrase mode\" and \"word mode\" (simple state machine)\n * - Text inside quotes becomes a single phrase token\n * - Text outside quotes is split by whitespace into word tokens\n * - All tokens are escaped (double quotes -> \"\") and wrapped in quotes for safety\n *\n * This prevents FTS5 syntax errors while supporting intuitive phrase searches.\n *\n * Query construction:\n * - Exact match of full input: `\"escaped full query\"`\n * - Individual terms: `\"term1\" OR \"term2\" OR \"phrase\"`\n * - Combined: `\"full query\" OR \"term1\" OR \"term2\"`\n *\n * Unquoted words in `FTS_STOP_WORDS` (\"the\", \"to\", \"is\", ...) are left out of\n * the individual terms. They stay in the exact match and in quoted phrases. A\n * query with nothing but stop words and punctuation keeps every word as a term.\n *\n * Examples:\n * - `foo bar` -> `\"foo bar\" OR \"foo\" OR \"bar\"`\n * - `\"hello world\"` -> `\"hello world\"`\n * - `test \"exact phrase\" word` -> `\"test exact phrase word\" OR \"test\" OR \"exact phrase\" OR \"word\"`\n * - `how to use the hooks` -> `\"how to use the hooks\" OR \"how\" OR \"use\" OR \"hooks\"`\n * - `\"is it\" in the docs` -> `\"is it in the docs\" OR \"is it\" OR \"docs\"`\n * - `is it in the` -> `\"is it in the\" OR \"is\" OR \"it\" OR \"in\" OR \"the\"`\n * - `is it in the ?` -> `\"is it in the ?\" OR \"is\" OR \"it\" OR \"in\" OR \"the\" OR \"?\"`\n */\n private escapeFtsQuery(query: string): string {\n // Tokenize the query using a simple quote-toggle state machine\n const tokens: { text: string; quoted: boolean }[] = [];\n let currentToken = \"\";\n let inQuote = false;\n\n for (let i = 0; i < query.length; i++) {\n const char = query[i];\n\n if (char === '\"') {\n // Save the accumulated token: a phrase on a closing quote, a word on an opening one\n if (currentToken.length > 0) {\n tokens.push({ text: currentToken, quoted: inQuote });\n currentToken = \"\";\n }\n inQuote = !inQuote;\n } else if (char === \" \" && !inQuote) {\n // Whitespace outside quotes: token separator\n if (currentToken.length > 0) {\n tokens.push({ text: currentToken, quoted: false });\n currentToken = \"\";\n }\n } else {\n // Regular character: accumulate\n currentToken += char;\n }\n }\n\n // Save any remaining token (an unclosed quote still counts as a phrase)\n if (currentToken.length > 0) {\n tokens.push({ text: currentToken, quoted: inQuote });\n }\n\n // Handle empty query or only whitespace\n if (tokens.length === 0) {\n return '\"\"';\n }\n\n // Escape and quote each token for FTS5 safety\n const quote = (text: string) => `\"${text.replace(/\"/g, '\"\"')}\"`;\n\n // If single token, just return it\n if (tokens.length === 1) {\n return quote(tokens[0].text);\n }\n\n // Build query: (Exact match of semantic content) OR (Terms ORed together)\n // Join tokens with space to match the semantic phrase, not the syntactic quotes\n const exactMatch = quote(tokens.map((token) => token.text).join(\" \"));\n const keptTokens = tokens.filter(\n (token) => token.quoted || !isFtsStopWord(token.text),\n );\n // FTS5 ignores tokens without letters or digits (`?`, `/`), so they don't\n // count as something left to search for\n const hasSearchableTerm = keptTokens.some((token) =>\n /[\\p{L}\\p{N}]/u.test(token.text),\n );\n const termTokens = hasSearchableTerm ? keptTokens : tokens;\n const termsQuery = termTokens.map((token) => quote(token.text)).join(\" OR \");\n\n return `${exactMatch} OR ${termsQuery}`;\n }\n\n /**\n * Escapes SQL LIKE wildcard characters (`%`, `_`) and the escape character\n * itself so a user-supplied filter is matched as a literal substring rather\n * than interpreted as a pattern. Pair with `LIKE ? ESCAPE '\\'`.\n */\n private escapeLikePattern(value: string): string {\n return value.replace(/[\\\\%_]/g, (match) => `\\\\${match}`);\n }\n\n /**\n * Initializes database connection and ensures readiness\n */\n async initialize(): Promise<void> {\n try {\n // 1. Load extensions first (moved before migrations)\n sqliteVec.load(this.db);\n\n // 2. Apply migrations (after extensions are loaded, includes metadata table creation)\n await applyMigrations(this.db, {\n maxRetries: this.config.db.migrationMaxRetries,\n retryDelayMs: this.config.db.migrationRetryDelayMs,\n });\n\n // 3. Resolve the effective vector dimension before metadata checks or table DDL.\n await this.resolveEffectiveEmbeddingDimension();\n\n // 4. Check embedding model/dimension metadata for changes\n // Uses inline db.prepare() so it works before prepareStatements().\n // Throws EmbeddingModelChangedError if mismatch detected.\n // The CLI layer catches this to prompt (TTY) or fail (non-interactive).\n this.checkEmbeddingModelChange();\n\n // 5. Create vector table at runtime with resolved dimension\n // Must run before prepareStatements() because triggers on `documents`\n // reference `documents_vec`.\n this.ensureVectorTable();\n\n // 6. Initialize prepared statements (after vec table exists)\n this.prepareStatements();\n\n // 7. Initialize embeddings client (await to catch errors)\n // On success, persists model identity to metadata table.\n await this.initializeEmbeddings();\n } catch (error) {\n // Re-throw StoreError, ModelConfigurationError, and UnsupportedProviderError directly\n if (\n error instanceof StoreError ||\n error instanceof ModelConfigurationError ||\n error instanceof UnsupportedProviderError\n ) {\n throw error;\n }\n throw new ConnectionError(\"Failed to initialize database connection\", error);\n }\n }\n\n /**\n * Resolves a model change by invalidating all vectors and completing initialization.\n * Called by the CLI layer after the user confirms a model/dimension change.\n * Assumes initialize() was previously called and threw EmbeddingModelChangedError,\n * meaning steps 1-2 (load extensions, apply migrations) completed successfully.\n * Steps 3+ (ensureVectorTable, prepareStatements, initializeEmbeddings) are\n * completed here after invalidation.\n */\n async resolveModelChange(): Promise<void> {\n await this.resolveEffectiveEmbeddingDimension({ ignoreStoredMetadata: true });\n\n const currentModel = this.config.app.embeddingModel;\n const currentDimension = this.dbDimension;\n\n // Invalidate all existing vectors and update metadata\n this.invalidateAllVectors(currentModel, currentDimension);\n\n // Complete the remaining initialization steps that were skipped when\n // checkEmbeddingModelChange() threw in initialize():\n\n // Re-create vector table (no-op since invalidateAllVectors already did it with correct dimension)\n this.ensureVectorTable();\n\n // Initialize prepared statements (must run after vec table exists)\n this.prepareStatements();\n\n // Initialize embeddings client (will also persist metadata on success)\n await this.initializeEmbeddings();\n }\n\n /**\n * Gracefully closes database connections\n */\n async shutdown(): Promise<void> {\n this.db.close();\n }\n\n /**\n * Combined on-disk size of the database file plus WAL and SHM sidecars.\n */\n private getOnDiskSizeBytes(): number {\n if (this.dbPath === \":memory:\") {\n return 0;\n }\n\n let total = 0;\n for (const filePath of [this.dbPath, `${this.dbPath}-wal`, `${this.dbPath}-shm`]) {\n try {\n total += statSync(filePath).size;\n } catch (error) {\n if (!(error instanceof Error && \"code\" in error && error.code === \"ENOENT\")) {\n throw error;\n }\n }\n }\n return total;\n }\n\n /**\n * Runs VACUUM with temp storage on disk so large stores do not duplicate the\n * compacted database in process memory.\n */\n private vacuumWithFileTempStore(): void {\n const prevTempStore = Number(this.db.pragma(\"temp_store\", { simple: true }) ?? 0);\n this.db.pragma(\"temp_store = FILE\");\n try {\n this.db.exec(\"VACUUM\");\n } finally {\n this.db.pragma(`temp_store = ${prevTempStore}`);\n }\n }\n\n /**\n * Reclaims unused SQLite pages and truncates the WAL file.\n * In-memory databases are skipped.\n *\n * VACUUM takes an exclusive lock and blocks readers, so it runs only when\n * `vacuum` is not `false` (the explicit compact path). After deletes, pass\n * `{ vacuum: false }` to checkpoint with PASSIVE, which never waits on\n * readers or writers.\n *\n * The explicit path also merges the FTS5 index first. FTS5 records deletes\n * as markers in new index segments, so removed text keeps occupying live\n * pages until a merge drops it; only then does VACUUM see those pages as free.\n *\n * @param options.force Always VACUUM even if no free pages are detected\n * @param options.vacuum When `false`, only run a non-blocking WAL checkpoint\n * @returns Size before/after compaction and whether VACUUM ran\n */\n async compact(options?: { force?: boolean; vacuum?: boolean }): Promise<CompactResult> {\n if (this.dbPath === \":memory:\") {\n return {\n skipped: true,\n vacuumed: false,\n beforeBytes: 0,\n afterBytes: 0,\n reclaimedBytes: 0,\n };\n }\n\n try {\n const force = options?.force === true;\n const allowVacuum = options?.vacuum !== false;\n const beforeBytes = this.getOnDiskSizeBytes();\n\n if (allowVacuum) {\n this.db.exec(\"INSERT INTO documents_fts(documents_fts) VALUES('optimize')\");\n }\n\n // PASSIVE never waits; TRUNCATE is reserved for the exclusive compact path.\n this.db.pragma(\n allowVacuum ? \"wal_checkpoint(TRUNCATE)\" : \"wal_checkpoint(PASSIVE)\",\n );\n\n const freelistCount = Number(\n this.db.pragma(\"freelist_count\", { simple: true }) ?? 0,\n );\n const shouldVacuum = allowVacuum && (force || freelistCount > 0);\n\n if (shouldVacuum) {\n this.vacuumWithFileTempStore();\n this.db.pragma(\"journal_mode = WAL\");\n this.db.pragma(\"wal_autocheckpoint = 1000\");\n this.db.pragma(\"wal_checkpoint(TRUNCATE)\");\n }\n\n const afterBytes = this.getOnDiskSizeBytes();\n return {\n skipped: false,\n vacuumed: shouldVacuum,\n beforeBytes,\n afterBytes,\n reclaimedBytes: Math.max(0, beforeBytes - afterBytes),\n };\n } catch (error) {\n throw new ConnectionError(\"Failed to compact document store\", error);\n }\n }\n\n /**\n * Creates or reconciles the documents_vec virtual table with configurable dimension.\n * Called after migrations and model change detection. The table is initially created\n * by migrations with a fixed 1536 dimension; this method reconciles it at runtime\n * if the configured dimension or partition-key schema differs.\n * Idempotent: if the table already has the expected dimension and partition keys,\n * no-op; otherwise, drops and recreates so any embedding provider works and KNN\n * queries can use selective partition filters.\n *\n * Compatible existing vectors are preserved, and missing rows are backfilled from\n * documents.embedding when available. Old vectors from a different dimension or model\n * are handled by the model change detection system (checkEmbeddingModelChange).\n */\n private ensureVectorTable(): void {\n const dim = this.dbDimension;\n this.validateVectorDimension(dim);\n\n const existingSql = this.db\n .prepare(\n \"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'documents_vec';\",\n )\n .get() as { sql: string } | undefined;\n\n if (existingSql) {\n const match = existingSql.sql.match(/embedding\\s+FLOAT\\s*\\[\\s*(\\d+)\\s*]/i);\n const existingDim = match ? Number(match[1]) : null;\n if (existingDim === dim && this.hasVectorPartitionKeys(existingSql.sql)) {\n return;\n }\n }\n\n logger.info(\n existingSql\n ? \"🔄 Rebuilding vector index with partition-key schema\"\n : \"🔄 Creating vector index with partition-key schema\",\n );\n this.rebuildVectorTable(dim, Boolean(existingSql));\n }\n\n private hasVectorPartitionKeys(sql: string): boolean {\n return (\n this.hasVectorPartitionKeyColumn(sql, \"library_id\") &&\n this.hasVectorPartitionKeyColumn(sql, \"version_id\")\n );\n }\n\n private hasVectorPartitionKeyColumn(sql: string, columnName: string): boolean {\n const quotedColumnName = columnName.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const columnDefinition = sql.match(\n new RegExp(\n String.raw`(?:^|[(,])\\s*(?:\"${quotedColumnName}\"|\\[${quotedColumnName}\\]|${quotedColumnName})\\s+([^,]*)`,\n \"i\",\n ),\n )?.[1];\n\n return (\n columnDefinition !== undefined &&\n /\\bINTEGER\\b/i.test(columnDefinition) &&\n /\\bpartition\\s+key\\b/i.test(columnDefinition)\n );\n }\n\n private createVectorTable(dimension: number): void {\n this.db.exec(`\n CREATE VIRTUAL TABLE documents_vec USING vec0(\n library_id INTEGER partition key,\n version_id INTEGER partition key,\n embedding FLOAT[${dimension}]\n );\n `);\n }\n\n private backfillVectorTable(dimension: number): void {\n this.db\n .prepare<[number]>(`\n INSERT OR REPLACE INTO documents_vec (rowid, library_id, version_id, embedding)\n SELECT\n d.id,\n v.library_id,\n v.id,\n d.embedding\n FROM documents d\n JOIN pages p ON d.page_id = p.id\n JOIN versions v ON p.version_id = v.id\n WHERE d.embedding IS NOT NULL\n AND vec_length(d.embedding) = ?\n AND NOT EXISTS (\n SELECT 1 FROM documents_vec existing WHERE existing.rowid = d.id\n )\n `)\n .run(dimension);\n }\n\n private rebuildVectorTable(dimension: number, preserveExisting: boolean): void {\n const transaction = this.db.transaction(() => {\n this.db.exec(\"DROP TABLE IF EXISTS _documents_vec_migration\");\n\n if (preserveExisting) {\n this.db\n .prepare<[number]>(`\n CREATE TABLE _documents_vec_migration AS\n SELECT\n d.id AS rowid,\n v.library_id,\n v.id AS version_id,\n dv.embedding\n FROM documents_vec dv\n JOIN documents d ON dv.rowid = d.id\n JOIN pages p ON d.page_id = p.id\n JOIN versions v ON p.version_id = v.id\n WHERE vec_length(dv.embedding) = ?\n `)\n .run(dimension);\n this.db.exec(\"DROP TABLE documents_vec\");\n } else {\n this.db.exec(`\n CREATE TABLE _documents_vec_migration(\n rowid INTEGER PRIMARY KEY,\n library_id INTEGER NOT NULL,\n version_id INTEGER NOT NULL,\n embedding BLOB NOT NULL\n )\n `);\n }\n\n this.createVectorTable(dimension);\n\n this.db.exec(`\n INSERT OR REPLACE INTO documents_vec (rowid, library_id, version_id, embedding)\n SELECT rowid, library_id, version_id, embedding\n FROM _documents_vec_migration\n `);\n this.backfillVectorTable(dimension);\n this.db.exec(\"DROP TABLE _documents_vec_migration\");\n });\n\n transaction();\n }\n\n /**\n * Resolves a library name and version string to version_id.\n * Creates library and version records if they don't exist, in one transaction.\n */\n async resolveVersionId(library: string, version: string): Promise<number> {\n return (await this.claimVersion(library, version, \"replace\")).versionId;\n }\n\n /**\n * Creates or verifies the library and version an indexing job writes into.\n *\n * Runs as one IMMEDIATE transaction with no `await` inside, so the database\n * decides a race: two connections claiming the same target cannot both win.\n *\n * @param library Library name as submitted; its display name is kept when the library is new.\n * @param version Version label; normalized like every other write.\n * @param policy What to do when the library or version already exists.\n * @returns The version id and the library's stored display name.\n * @throws {LibraryAlreadyExistsError} Policy `reject-library` and the library exists.\n * @throws {VersionAlreadyExistsError} Policy `reject-version` and the version exists.\n * @throws {InvalidLibraryNameError} The library is new and its name fails validation.\n */\n async claimVersion(\n library: string,\n version: string,\n policy: ExistingTargetPolicy,\n ): Promise<ResolvedVersion> {\n // Last point every write passes through: apply the single version label\n // contract here so an entry point that forgets to normalize cannot create a\n // duplicate bucket (e.g. \" 1.0.0 \" alongside \"1.0.0\").\n const label = normalizeVersionLabel(version);\n const storedVersion = denormalizeVersionName(label);\n\n const claim = this.db.transaction((): ResolvedVersion => {\n const libraryRow = this.getOrCreateLibraryRow(library, policy === \"reject-library\");\n\n // Insert-or-ignore; inside the IMMEDIATE transaction, an insert that\n // changed nothing means the version already exists.\n const inserted = this.statements.insertVersion.run(libraryRow.id, storedVersion);\n if (inserted.changes === 0 && policy === \"reject-version\") {\n throw new VersionAlreadyExistsError(libraryRow.displayName, label);\n }\n\n const versionIdRow = this.statements.resolveVersionId.get(\n libraryRow.id,\n storedVersion,\n ) as { id: number } | undefined;\n if (!versionIdRow) {\n throw new StoreError(\n `Failed to resolve version_id for library: ${quoteName(library)}, version: ${quoteName(version)}`,\n );\n }\n return { versionId: versionIdRow.id, library: libraryRow.displayName };\n });\n return claim.immediate();\n }\n\n /**\n * Looks up a version without creating anything, with its library's display name.\n *\n * @param library Library name in any casing or padding.\n * @param version Version label; empty for unversioned documentation.\n * @returns The version id and the library's stored display name, or `null`\n * when the library or version does not exist.\n */\n async findVersion(library: string, version: string): Promise<ResolvedVersion | null> {\n const row = this.statements.getVersionId.get(\n normalizeLibraryName(library),\n normalizeVersionLabel(version),\n ) as { id: number; display_name: string } | undefined;\n return row ? { versionId: row.id, library: row.display_name } : null;\n }\n\n /**\n * The single place a library row is created. Must run inside a transaction\n * together with the version insert that accompanies it.\n *\n * @param library Library name as submitted.\n * @param mustBeNew Whether an existing library is an error (explicit \"Add library\").\n * @throws {LibraryAlreadyExistsError} `mustBeNew` and the library exists.\n * @throws {InvalidLibraryNameError} The library is new and its name fails validation.\n */\n private getOrCreateLibraryRow(\n library: string,\n mustBeNew: boolean,\n ): { id: number; displayName: string } {\n const key = normalizeLibraryName(library);\n const existing = this.statements.getLibraryIdByName.get(key) as\n | { id: number; display_name: string }\n | undefined;\n if (existing) {\n if (mustBeNew) {\n throw new LibraryAlreadyExistsError(existing.display_name);\n }\n return { id: existing.id, displayName: existing.display_name };\n }\n\n const displayName = normalizeLibraryDisplayName(library);\n const problem = describeLibraryNameProblem(displayName);\n if (problem) {\n throw new InvalidLibraryNameError(displayName, problem);\n }\n const result = this.statements.insertLibrary.run(key, displayName);\n return { id: Number(result.lastInsertRowid), displayName };\n }\n\n /**\n * Retrieves all unique versions for a specific library\n */\n async queryUniqueVersions(library: string): Promise<string[]> {\n try {\n const rows = this.statements.queryVersions.all(\n normalizeLibraryName(library),\n ) as Array<{\n name: string | null;\n }>;\n return rows.map((row) => normalizeVersionName(row.name));\n } catch (error) {\n throw new ConnectionError(\"Failed to query versions\", error);\n }\n }\n\n /**\n * Updates the status of a version record in the database.\n * @param versionId The version ID to update\n * @param status The new status to set\n * @param errorMessage Optional error message for failed statuses\n */\n async updateVersionStatus(\n versionId: number,\n status: VersionStatus,\n errorMessage?: string,\n ): Promise<void> {\n try {\n this.statements.updateVersionStatus.run(status, errorMessage ?? null, versionId);\n } catch (error) {\n throw new StoreError(`Failed to update version status: ${error}`);\n }\n }\n\n /**\n * Updates the progress counters for a version being indexed.\n * @param versionId The version ID to update\n * @param pages Current number of pages processed\n * @param maxPages Total number of pages to process\n */\n async updateVersionProgress(\n versionId: number,\n pages: number,\n maxPages: number,\n /** Omit or pass null to leave the stored value untouched. */\n pagesIndexed: number | null = null,\n ): Promise<void> {\n try {\n this.statements.updateVersionProgress.run(pages, maxPages, pagesIndexed, versionId);\n } catch (error) {\n throw new StoreError(`Failed to update version progress: ${error}`);\n }\n }\n\n /**\n * Retrieves versions by their status.\n * @param statuses Array of statuses to filter by\n * @returns Array of version records matching the statuses\n */\n async getVersionsByStatus(statuses: VersionStatus[]): Promise<DbVersionWithLibrary[]> {\n try {\n const statusJson = JSON.stringify(statuses);\n const rows = this.statements.getVersionsByStatus.all(\n statusJson,\n ) as DbVersionWithLibrary[];\n return rows;\n } catch (error) {\n throw new StoreError(`Failed to get versions by status: ${error}`);\n }\n }\n\n /**\n * Marks the jobs of versions alive for other processes on the store, by\n * setting their `updated_at` to now. Versions no longer QUEUED or RUNNING are\n * left unchanged.\n * @param versionIds The versions whose jobs are alive\n * @throws {StoreError} When the write fails\n */\n async markVersionsAlive(versionIds: number[]): Promise<void> {\n try {\n this.statements.markVersionsAlive.run(JSON.stringify(versionIds));\n } catch (error) {\n throw new StoreError(`Failed to mark versions alive: ${error}`);\n }\n }\n\n /**\n * Claims a version an earlier run left QUEUED or RUNNING, provided nothing\n * has written it since its `updated_at` was read, by setting `updated_at` to\n * now. Of several processes acting on the same read only one succeeds, and\n * the others treat the version as recently written. The read must be older\n * than a second, the resolution of `updated_at`, for the claim to change it.\n * @param versionId The version to claim\n * @param updatedAt The `updated_at` the caller read\n * @returns Whether the claim succeeded\n * @throws {StoreError} When the write fails\n */\n async claimInterruptedVersion(\n versionId: number,\n updatedAt: string | null,\n ): Promise<boolean> {\n try {\n return (\n this.statements.claimInterruptedVersion.run(versionId, updatedAt).changes > 0\n );\n } catch (error) {\n throw new StoreError(`Failed to claim interrupted version: ${error}`);\n }\n }\n\n /**\n * Retrieves a version by its ID.\n * @param versionId The version ID to retrieve\n * @returns The version record, or null if not found\n */\n async getVersionById(versionId: number): Promise<DbVersion | null> {\n try {\n const row = this.statements.getVersionById.get(versionId) as DbVersion | undefined;\n return row || null;\n } catch (error) {\n throw new StoreError(`Failed to get version by ID: ${error}`);\n }\n }\n\n /**\n * Retrieves a library by its ID.\n * @param libraryId The library ID to retrieve\n * @returns The library record, or null if not found\n */\n async getLibraryById(libraryId: number): Promise<{ id: number; name: string } | null> {\n try {\n const row = this.statements.getLibraryById.get(libraryId) as\n | { id: number; name: string }\n | undefined;\n return row || null;\n } catch (error) {\n throw new StoreError(`Failed to get library by ID: ${error}`);\n }\n }\n\n /**\n * Retrieves a library by its name.\n * @param name The library name to retrieve\n * @returns The library record, or null if not found\n */\n async getLibrary(\n name: string,\n ): Promise<{ id: number; name: string; displayName: string } | null> {\n try {\n const normalizedName = normalizeLibraryName(name);\n const row = this.statements.getLibraryIdByName.get(normalizedName) as\n | { id: number; display_name: string }\n | undefined;\n if (!row) {\n return null;\n }\n return { id: row.id, name: normalizedName, displayName: row.display_name };\n } catch (error) {\n throw new StoreError(`Failed to get library by name: ${error}`);\n }\n }\n\n /**\n * Deletes a library by its ID.\n * This should only be called when the library has no remaining versions.\n * @param libraryId The library ID to delete\n */\n async deleteLibrary(libraryId: number): Promise<void> {\n try {\n this.statements.deleteLibraryById.run(libraryId);\n } catch (error) {\n throw new StoreError(`Failed to delete library: ${error}`);\n }\n }\n\n /**\n * Stores scraper options for a version to enable reproducible indexing.\n * @param versionId The version ID to update\n * @param options Complete scraper options used for indexing\n */\n async storeScraperOptions(versionId: number, options: ScraperOptions): Promise<void> {\n try {\n // Extract source URL and exclude runtime-only fields using destructuring\n const {\n url: source_url,\n library: _library,\n version: _version,\n ...scraper_options\n } = withoutRunOnlyOptions(options);\n\n const optionsJson = JSON.stringify(scraper_options);\n this.statements.updateVersionScraperOptions.run(source_url, optionsJson, versionId);\n } catch (error) {\n throw new StoreError(`Failed to store scraper options: ${error}`);\n }\n }\n\n /**\n * Retrieves stored scraping configuration (source URL and options) for a version.\n * Returns null when no source URL is recorded (not re-indexable).\n */\n async getScraperOptions(versionId: number): Promise<StoredScraperOptions | null> {\n try {\n const row = this.statements.getVersionWithOptions.get(versionId) as\n | DbVersion\n | undefined;\n\n if (!row?.source_url) {\n return null;\n }\n\n let parsed: VersionScraperOptions = {} as VersionScraperOptions;\n if (row.scraper_options) {\n try {\n parsed = JSON.parse(row.scraper_options) as VersionScraperOptions;\n } catch (e) {\n logger.warn(`⚠️ Invalid scraper_options JSON for version ${versionId}: ${e}`);\n parsed = {} as VersionScraperOptions;\n }\n }\n\n return { sourceUrl: row.source_url, options: parsed };\n } catch (error) {\n throw new StoreError(`Failed to get scraper options: ${error}`);\n }\n }\n\n /**\n * Finds versions that were indexed from the same source URL.\n * Useful for finding similar configurations or detecting duplicates.\n * @param url Source URL to search for\n * @returns Array of versions with the same source URL\n */\n async findVersionsBySourceUrl(url: string): Promise<DbVersionWithLibrary[]> {\n try {\n const rows = this.statements.getVersionsBySourceUrl.all(\n url,\n ) as DbVersionWithLibrary[];\n return rows;\n } catch (error) {\n throw new StoreError(`Failed to find versions by source URL: ${error}`);\n }\n }\n\n /**\n * Verifies existence of documents for a specific library version\n */\n async checkDocumentExists(library: string, version: string): Promise<boolean> {\n try {\n const normalizedVersion = normalizeVersionLabel(version);\n const result = this.statements.checkExists.get(\n normalizeLibraryName(library),\n normalizedVersion,\n );\n return result !== undefined;\n } catch (error) {\n throw new ConnectionError(\"Failed to check document existence\", error);\n }\n }\n\n /**\n * Retrieves a mapping of all libraries to their available versions with details.\n */\n async queryLibraryVersions(): Promise<Map<string, Array<LibraryVersionSummary>>> {\n try {\n const rows = this.statements.queryLibraryVersions.all() as DbLibraryVersion[];\n const libraryMap = new Map<string, Array<LibraryVersionSummary>>();\n\n for (const row of rows) {\n // Process all rows, including those where version is \"\" (unversioned)\n const library = row.library;\n if (!libraryMap.has(library)) {\n libraryMap.set(library, []);\n }\n\n // Format indexedAt to ISO string if available\n const indexedAtISO = row.indexedAt ? new Date(row.indexedAt).toISOString() : null;\n\n libraryMap.get(library)?.push({\n version: row.version,\n versionId: row.versionId,\n // Preserve raw string status here; DocumentManagementService will cast to VersionStatus\n status: row.status,\n errorMessage: row.errorMessage,\n progressPages: row.progressPages,\n progressMaxPages: row.progressMaxPages,\n progressPagesIndexed: row.progressPagesIndexed ?? null,\n sourceUrl: row.sourceUrl,\n documentCount: row.documentCount,\n uniqueUrlCount: row.uniqueUrlCount,\n indexedAt: indexedAtISO,\n });\n }\n\n // Sort versions within each library: descending (latest first), unversioned is \"latest\"\n for (const versions of libraryMap.values()) {\n versions.sort((a, b) => compareVersionsDescending(a.version, b.version));\n }\n\n return libraryMap;\n } catch (error) {\n throw new ConnectionError(\"Failed to query library versions\", error);\n }\n }\n\n /**\n * Helper method to detect if an error is related to input size limits.\n * Checks for common error messages from various embedding providers.\n */\n private isInputSizeError(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n\n const message = error.message.toLowerCase();\n return (\n message.includes(\"maximum context length\") ||\n message.includes(\"too long\") ||\n message.includes(\"token limit\") ||\n message.includes(\"input is too large\") ||\n message.includes(\"exceeds\") ||\n (message.includes(\"max\") && message.includes(\"token\"))\n );\n }\n\n private getEmbeddingErrorHint(error: unknown): string | null {\n if (this.isInputSizeError(error)) {\n return \"The embedding input appears to exceed provider or model limits. Check model context size and reduce embedding batch size if needed.\";\n }\n\n if (error instanceof Error) {\n const message = error.message.toLowerCase();\n if (message.includes(\"rate limit\") || message.includes(\"429\")) {\n return \"The embedding provider appears to be rate limiting requests. Reduce concurrency or retry after the provider quota resets.\";\n }\n if (\n message.includes(\"timed out\") ||\n message.includes(\"econnrefused\") ||\n message.includes(\"enotfound\") ||\n message.includes(\"etimedout\") ||\n message.includes(\"econnreset\") ||\n message.includes(\"network\") ||\n message.includes(\"fetch failed\")\n ) {\n return \"The embedding service appears unreachable. Check that the provider endpoint is running and accessible.\";\n }\n }\n\n return null;\n }\n\n private createEmbeddingConnectionError(\n error: unknown,\n context: EmbeddingBatchContext,\n ): EmbeddingError {\n const modelSpec = this.embeddingConfig?.modelSpec ?? \"unknown\";\n const errorHint = this.getEmbeddingErrorHint(error);\n const providerHint = this.embeddingConfig\n ? \"Verify embedding provider configuration, model availability, credentials, quota, request size, and backend logs.\"\n : null;\n const hints = [errorHint, providerHint].filter((hint) => hint !== null);\n const hintText = hints.length > 0 ? `\\n ${hints.join(\"\\n \")}` : \"\";\n\n return new EmbeddingError(\n `Failed to generate embeddings for ${context.url} using ${modelSpec}.\\n` +\n ` Batch ${context.batchIndex}: ${context.batchTextCount} text(s), ${context.batchChars} chars, ${context.totalChunks} page chunk(s).\\n` +\n ` Config: batchSize=${this.embeddingBatchSize}, batchChars=${this.embeddingBatchChars}, vectorDimension=${this.dbDimension}.` +\n hintText,\n error,\n );\n }\n\n /**\n * Creates embeddings for an array of texts with automatic retry logic for size-related errors.\n * If a batch fails due to size limits:\n * - Batches with multiple texts are split in half and retried recursively\n * - Single texts that are too large are truncated and retried once\n *\n * @param texts Array of texts to embed\n * @param isRetry Internal flag to prevent duplicate warning logs\n * @param hasTruncatedSingleText Whether a single text has already been truncated once\n * @returns Array of embedding vectors\n */\n private async embedDocumentsWithRetry(\n texts: string[],\n isRetry = false,\n hasTruncatedSingleText = false,\n ): Promise<number[][]> {\n if (texts.length === 0) {\n return [];\n }\n\n try {\n // Try to embed the batch normally\n const embeddings = this.embeddings;\n if (embeddings === null) {\n throw new StoreError(\"Embeddings are not initialized\");\n }\n return await embeddings.embedDocuments(texts);\n } catch (error) {\n // Check if this is a size-related error\n if (this.isInputSizeError(error)) {\n if (texts.length > 1) {\n // Split batch in half and retry each half recursively\n const midpoint = Math.floor(texts.length / 2);\n const firstHalf = texts.slice(0, midpoint);\n const secondHalf = texts.slice(midpoint);\n\n // Only log if this is not already a retry\n if (!isRetry) {\n logger.warn(\n `⚠️ Batch of ${texts.length} texts exceeded size limit, splitting into ${firstHalf.length} + ${secondHalf.length}`,\n );\n }\n\n const [firstEmbeddings, secondEmbeddings] = await Promise.all([\n this.embedDocumentsWithRetry(firstHalf, true, false),\n this.embedDocumentsWithRetry(secondHalf, true, false),\n ]);\n\n return [...firstEmbeddings, ...secondEmbeddings];\n } else {\n // Single text that's too large - split in half and retry\n if (hasTruncatedSingleText) {\n throw error;\n }\n\n const text = texts[0];\n const midpoint = Math.floor(text.length / 2);\n const firstHalf = text.substring(0, midpoint);\n\n // Only log once for the original text\n if (!isRetry) {\n logger.warn(\n `⚠️ Single text exceeded embedding size limit (${text.length} chars).`,\n );\n }\n\n try {\n // Recursively retry with first half only (mark as retry to prevent duplicate logs)\n // This preserves the beginning of the text which typically contains the most important context\n const embedding = await this.embedDocumentsWithRetry([firstHalf], true, true);\n return embedding;\n } catch (retryError) {\n // If even split text fails, log error and throw\n logger.error(\n `❌ Failed to embed even after splitting. Original length: ${text.length}`,\n );\n throw retryError;\n }\n }\n }\n\n // Not a size error, re-throw\n throw error;\n }\n }\n\n /**\n * Removes the row a refreshed page was read from, when it is not the row now\n * being written.\n *\n * A refresh carries the id of the page it is re-fetching, and that page can\n * move: a redirect renames it, and resolving a `.md` URL to the page it\n * represents folds it onto another row. Either way the old row is stale. When\n * the id names the row being written it is the same page, not a stale one, and\n * deleting it would throw away the very content the write is competing with.\n *\n * Runs inside the caller's transaction so the decision and the write cannot be\n * separated by another representation landing in between.\n *\n * @param previousPageId Page the refresh item was read from, if any.\n * @param current The row presently stored under the URL being written.\n */\n private retirePreviousPage(\n previousPageId: number | undefined,\n current: PageIdRow | undefined,\n ): void {\n if (previousPageId === undefined || previousPageId === current?.id) return;\n this.statements.deleteDocumentsByPageId.run(previousPageId);\n const deleted = this.statements.deletePage.run(previousPageId);\n if (deleted.changes > 0) {\n logger.debug(`Retired page ${previousPageId}, superseded by another URL`);\n }\n }\n\n /**\n * Records a page that exists but holds no content.\n *\n * A successful fetch that yields no extractable text is a statement about the\n * page, not an absence of information, so it replaces whatever was stored\n * rather than leaving stale content behind. Callers withhold `etag` and\n * `lastModified` when extraction failed, which keeps the next refresh\n * unconditional instead of caching a failure against the server's validator.\n *\n * @param library Library name.\n * @param version Version string.\n * @param depth Crawl depth the page was found at.\n * @param page Page identity and optional validators.\n */\n async addEmptyPage(\n library: string,\n version: string,\n depth: number,\n page: {\n url: string;\n contentUrl?: string;\n title: string;\n sourceContentType: string | null;\n contentType: string | null;\n etag: string | null;\n lastModified: string | null;\n isAdditionalRepresentation?: boolean;\n },\n previousPageId?: number,\n ): Promise<void> {\n try {\n const versionId = await this.resolveVersionId(library, version);\n this.db.transaction(() => {\n const current = this.statements.getPageId.get(versionId, page.url) as\n | PageIdRow\n | undefined;\n\n // An empty representation is still a representation, and it competes on\n // the same terms: an HTML twin that extracted nothing must not erase the\n // Markdown this crawl already stored under the same identity.\n if (\n losesToStoredRepresentation(\n current,\n page.sourceContentType,\n page.isAdditionalRepresentation,\n )\n ) {\n logger.debug(\n `Keeping stored ${current?.source_content_type} representation of ${page.url}; ignoring empty ${page.sourceContentType} version`,\n );\n this.retirePreviousPage(previousPageId, current);\n return;\n }\n\n this.retirePreviousPage(previousPageId, current);\n\n this.statements.insertPage.run(\n versionId,\n page.url,\n page.title || \"\",\n page.etag,\n page.lastModified,\n page.sourceContentType,\n page.contentType,\n depth,\n page.contentUrl ?? null,\n );\n\n // Clear any chunks the page had before it became empty. Without this the\n // old content keeps matching searches while the row carries the new\n // validator, so the next refresh answers 304 and it never self-corrects.\n //\n // `current` is reused when it exists: `insertPage` upserts, so the row\n // keeps its id. Only a page that did not exist before needs looking up.\n const stored =\n current ??\n (this.statements.getPageId.get(versionId, page.url) as PageIdRow | undefined);\n if (stored) {\n this.statements.deleteDocumentsByPageId.run(stored.id);\n }\n })();\n } catch (error) {\n throw new StoreError(`Failed to record empty page: ${error}`);\n }\n }\n\n /**\n * Stores documents with library and version metadata, generating embeddings\n * for vector similarity search. Uses the new pages table to normalize page-level\n * metadata and avoid duplication across document chunks.\n */\n async addDocuments(\n library: string,\n version: string,\n depth: number,\n result: ScrapeResult,\n previousPageId?: number,\n ): Promise<void> {\n try {\n const { title, url, chunks } = result;\n if (chunks.length === 0) {\n return;\n }\n\n // Resolve library and version IDs (creates them if they don't exist)\n const versionId = await this.resolveVersionId(library, version);\n const existingPage = this.statements.getPageId.get(versionId, url) as\n | PageIdRow\n | undefined;\n\n // Checked here as an optimisation only — a write that is going to be\n // dropped should not first pay for a billed embedding round-trip. The\n // authoritative check is repeated inside the write transaction below,\n // because this snapshot is taken before the embedding await and a\n // concurrent write for the same identity can land in between.\n //\n // Taken only when this write has no previous row to retire. Retiring has\n // to happen inside that transaction, so returning early with one pending\n // would strand it: the losing write is the only thing that knows the old\n // spelling folded into this identity, and the row would stay searchable\n // and lose again on every later refresh.\n if (\n previousPageId === undefined &&\n losesToStoredRepresentation(\n existingPage,\n result.sourceContentType,\n result.isAdditionalRepresentation,\n )\n ) {\n logger.debug(\n `Keeping stored ${existingPage?.source_content_type} representation of ${url}; ignoring ${result.sourceContentType} version`,\n );\n return;\n }\n\n // Generate embeddings in batch only if vector search is enabled\n let paddedEmbeddings: number[][] = [];\n\n if (this.isVectorSearchEnabled) {\n const texts = chunks.map((chunk) => {\n const header = `<title>${title}</title>\\n<url>${url}</url>\\n<path>${(chunk.section.path || []).join(\" / \")}</path>\\n`;\n return `${header}${chunk.content}`;\n });\n\n // Validate chunk body sizes before creating embeddings.\n // Note: We compare the chunk body (without the metadata header) against maxChunkSize,\n // because the splitter's size budget applies to the content body only. The metadata\n // header (title, URL, path) is expected overhead added after splitting.\n for (let i = 0; i < chunks.length; i++) {\n const bodySize = chunks[i].content.length;\n if (bodySize > this.splitterMaxChunkSize) {\n logger.warn(\n `⚠️ Chunk ${i + 1}/${chunks.length} body exceeds max size: ${bodySize} > ${this.splitterMaxChunkSize} chars (URL: ${url})`,\n );\n }\n }\n\n // Batch embedding creation to avoid token limit errors\n const maxBatchChars = this.embeddingBatchChars;\n const rawEmbeddings: number[][] = [];\n\n let currentBatch: string[] = [];\n let currentBatchSize = 0;\n let batchCount = 0;\n\n const processEmbeddingBatch = async (isFinalBatch = false) => {\n batchCount++;\n const batchTexts = currentBatch;\n const batchChars = currentBatchSize;\n logger.debug(\n `Processing ${isFinalBatch ? \"final \" : \"\"}embedding batch ${batchCount}: ${batchTexts.length} texts, ${batchChars} chars`,\n );\n\n try {\n const batchEmbeddings = await this.embedDocumentsWithRetry(batchTexts);\n rawEmbeddings.push(...batchEmbeddings);\n } catch (error) {\n throw this.createEmbeddingConnectionError(error, {\n url,\n batchIndex: batchCount,\n batchTextCount: batchTexts.length,\n batchChars,\n totalChunks: chunks.length,\n });\n }\n\n currentBatch = [];\n currentBatchSize = 0;\n };\n\n for (const text of texts) {\n const textSize = text.length;\n\n // If adding this text would exceed the limit, process the current batch first\n if (currentBatchSize + textSize > maxBatchChars && currentBatch.length > 0) {\n await processEmbeddingBatch();\n }\n\n // Add text to current batch\n currentBatch.push(text);\n currentBatchSize += textSize;\n\n // Also respect the count-based limit for APIs that have per-request item limits\n if (currentBatch.length >= this.embeddingBatchSize) {\n await processEmbeddingBatch();\n }\n }\n\n // Process any remaining texts in the final batch\n if (currentBatch.length > 0) {\n await processEmbeddingBatch(true);\n }\n paddedEmbeddings = rawEmbeddings.map((vector) => this.padVector(vector));\n }\n\n // Insert documents in a transaction\n const transaction = this.db.transaction((): boolean => {\n // Re-read inside the transaction. The snapshot above predates the\n // embedding await, so when both representations of one identity are\n // processed concurrently each can observe no row, and both would insert\n // — leaving two chunk sets under one page. Reading and writing in the\n // same synchronous transaction closes that window.\n const current = this.statements.getPageId.get(versionId, url) as\n | PageIdRow\n | undefined;\n\n if (\n losesToStoredRepresentation(\n current,\n result.sourceContentType,\n result.isAdditionalRepresentation,\n )\n ) {\n logger.debug(\n `Keeping stored ${current?.source_content_type} representation of ${url}; ignoring ${result.sourceContentType} version`,\n );\n // The row this write came from is still retired below: this crawl has\n // decided that URL folds into `url`, so leaving it would keep a second\n // copy of the page under its old spelling.\n this.retirePreviousPage(previousPageId, current);\n return false;\n }\n\n this.retirePreviousPage(previousPageId, current);\n\n if (current) {\n const deleted = this.statements.deleteDocumentsByPageId.run(current.id);\n if (deleted.changes > 0) {\n logger.debug(`Deleted ${deleted.changes} existing documents for URL: ${url}`);\n }\n }\n\n // Extract content type from metadata if available\n const sourceContentType = result.sourceContentType || result.contentType || null;\n const contentType = result.contentType || result.sourceContentType || null;\n\n // Extract etag from document metadata if available\n const etag = result.etag || null;\n\n // Extract lastModified from document metadata if available\n const lastModified = result.lastModified || null;\n\n // Insert or update page record\n this.statements.insertPage.run(\n versionId,\n url,\n title || \"\",\n etag,\n lastModified,\n sourceContentType,\n contentType,\n depth,\n // NULL means \"retrieved from its own URL\"; the strategy reports this\n // only when the two genuinely differ.\n result.contentUrl ?? null,\n );\n\n // Query for the page ID since we can't use RETURNING\n const insertedPage = this.statements.getPageId.get(versionId, url) as\n | PageIdRow\n | undefined;\n if (!insertedPage) {\n throw new StoreError(`Failed to get page ID for URL: ${url}`);\n }\n const pageId = insertedPage.id;\n\n // Then insert document chunks linked to their pages\n let docIndex = 0;\n for (let i = 0; i < chunks.length; i++) {\n const chunk = chunks[i];\n\n // Insert document chunk\n const result = this.statements.insertDocument.run(\n pageId,\n chunk.content,\n JSON.stringify({\n types: chunk.types,\n level: chunk.section.level,\n path: chunk.section.path,\n } satisfies DbChunkMetadata),\n i, // sort_order within this page\n );\n const rowId = result.lastInsertRowid;\n\n // Insert into vector table only if vector search is enabled\n if (this.isVectorSearchEnabled && paddedEmbeddings.length > 0) {\n this.statements.insertEmbedding.run(\n Buffer.from(new Float32Array(paddedEmbeddings[docIndex]).buffer),\n BigInt(rowId),\n );\n }\n\n docIndex++;\n }\n return true;\n });\n\n transaction();\n } catch (error) {\n if (error instanceof StoreError) {\n throw error;\n }\n throw new ConnectionError(\"Failed to add documents to store\", error);\n }\n }\n\n /**\n * Removes documents and pages matching specified library and version.\n * This consolidated method deletes both documents and their associated pages.\n * @returns Number of documents deleted\n */\n async deletePages(library: string, version: string): Promise<number> {\n try {\n return this.deleteVersionContent(\n normalizeLibraryName(library),\n normalizeVersionLabel(version),\n );\n } catch (error) {\n throw new ConnectionError(\"Failed to delete documents\", error);\n }\n }\n\n /**\n * Deletes a version's documents, then its pages (documents reference pages).\n * Synchronous so it can run inside a caller's transaction.\n * @returns The number of documents deleted.\n */\n private deleteVersionContent(libraryKey: string, version: string): number {\n const { changes } = this.statements.deleteDocuments.run(libraryKey, version);\n this.statements.deletePages.run(libraryKey, version);\n return changes;\n }\n\n /**\n * Deletes a page and all its associated document chunks.\n * Performs manual deletion in the correct order to satisfy foreign key constraints:\n * 1. Delete document chunks (page_id references pages.id)\n * 2. Delete page record\n *\n * This method is used during refresh operations when a page returns 404 Not Found.\n */\n async deletePage(pageId: number): Promise<void> {\n try {\n // Delete documents first (due to foreign key constraint)\n const docResult = this.statements.deleteDocumentsByPageId.run(pageId);\n logger.debug(`Deleted ${docResult.changes} document(s) for page ID ${pageId}`);\n\n // Then delete the page record\n const pageResult = this.statements.deletePage.run(pageId);\n if (pageResult.changes > 0) {\n logger.debug(`Deleted page record for page ID ${pageId}`);\n }\n } catch (error) {\n throw new ConnectionError(`Failed to delete page ${pageId}`, error);\n }\n }\n\n /**\n * Retrieves all pages for a specific version ID with their metadata.\n * Used for refresh operations to get existing pages with their ETags and depths.\n * @returns Array of page records\n */\n async getPagesByVersionId(versionId: number): Promise<DbPage[]> {\n try {\n const result = this.statements.getPagesByVersionId.all(versionId) as DbPage[];\n return result;\n } catch (error) {\n throw new ConnectionError(\"Failed to get pages by version ID\", error);\n }\n }\n\n /**\n * Finds pages whose URL or content URL equals one of the candidates.\n *\n * @param library Library name.\n * @param version Version label.\n * @param candidates URLs to match exactly.\n * @returns Page URLs, pages matched by `url` before pages matched by `content_url`.\n */\n async findPageUrls(\n library: string,\n version: string,\n candidates: string[],\n ): Promise<string[]> {\n if (candidates.length === 0) return [];\n try {\n const placeholders = candidates.map(() => \"?\").join(\", \");\n const rows = this.db\n .prepare(\n `SELECT p.url FROM pages p\n JOIN versions v ON p.version_id = v.id\n JOIN libraries l ON v.library_id = l.id\n WHERE l.name = ? AND COALESCE(v.name, '') = ?\n AND (p.url IN (${placeholders}) OR p.content_url IN (${placeholders}))\n ORDER BY p.url IN (${placeholders}) DESC, p.id ASC`,\n )\n .all(\n normalizeLibraryName(library),\n normalizeVersionLabel(version),\n ...candidates,\n ...candidates,\n ...candidates,\n ) as Array<{ url: string }>;\n return rows.map((row) => row.url);\n } catch (error) {\n throw new ConnectionError(\"Failed to find pages by URL\", error);\n }\n }\n\n /**\n * Finds pages whose URL, ignoring trailing slashes, ends with one of the suffixes.\n *\n * @param library Library name.\n * @param version Version label.\n * @param suffixes URL endings, matched literally.\n * @param limit Maximum number of URLs to return.\n * @returns Matching page URLs, shortest first.\n */\n async findPageUrlsBySuffix(\n library: string,\n version: string,\n suffixes: string[],\n limit: number,\n ): Promise<string[]> {\n if (suffixes.length === 0) return [];\n try {\n const conditions = suffixes\n .map(() => \"rtrim(p.url, '/') LIKE '%' || ? ESCAPE '\\\\'\")\n .join(\" OR \");\n const rows = this.db\n .prepare(\n `SELECT p.url FROM pages p\n JOIN versions v ON p.version_id = v.id\n JOIN libraries l ON v.library_id = l.id\n WHERE l.name = ? AND COALESCE(v.name, '') = ? AND (${conditions})\n ORDER BY LENGTH(p.url) ASC, p.id ASC\n LIMIT ?`,\n )\n .all(\n normalizeLibraryName(library),\n normalizeVersionLabel(version),\n ...suffixes.map((suffix) => this.escapeLikePattern(suffix)),\n limit,\n ) as Array<{ url: string }>;\n return rows.map((row) => row.url);\n } catch (error) {\n throw new ConnectionError(\"Failed to find pages by URL suffix\", error);\n }\n }\n\n /**\n * Lists the pages of a library version, ordered by crawl depth and then URL.\n *\n * @param library Library name.\n * @param version Version label.\n * @param options `contains` keeps only URLs containing the text; `limit` and `offset` paginate.\n * @returns The requested pages and the total number of matching pages.\n */\n async listPages(\n library: string,\n version: string,\n options: { contains?: string; limit?: number; offset?: number },\n ): Promise<{ total: number; pages: PageListItem[] }> {\n try {\n const filter = options.contains ? \"AND p.url LIKE '%' || ? || '%' ESCAPE '\\\\'\" : \"\";\n const params: unknown[] = [\n normalizeLibraryName(library),\n normalizeVersionLabel(version),\n ...(options.contains ? [this.escapeLikePattern(options.contains)] : []),\n ];\n const from = `FROM pages p\n JOIN versions v ON p.version_id = v.id\n JOIN libraries l ON v.library_id = l.id\n WHERE l.name = ? AND COALESCE(v.name, '') = ? ${filter}`;\n\n const { total } = this.db\n .prepare(`SELECT COUNT(*) AS total ${from}`)\n .get(...params) as { total: number };\n const pages = this.db\n .prepare(\n `SELECT p.url, p.title, p.depth ${from}\n ORDER BY p.depth ASC NULLS LAST, p.url ASC\n LIMIT ? OFFSET ?`,\n )\n .all(...params, options.limit ?? -1, options.offset ?? 0) as PageListItem[];\n return { total, pages };\n } catch (error) {\n throw new ConnectionError(\"Failed to list pages\", error);\n }\n }\n\n /**\n * Completely removes a library version and all associated documents.\n * Optionally removes the library if no other versions remain.\n * @param library Library name\n * @param version Version string (empty string for unversioned)\n * @param removeLibraryIfEmpty Whether to remove the library if no versions remain\n * @returns Object with counts of deleted documents, version deletion status, and library deletion status\n */\n async removeVersion(\n library: string,\n version: string,\n removeLibraryIfEmpty = true,\n ): Promise<{\n documentsDeleted: number;\n versionDeleted: boolean;\n libraryDeleted: boolean;\n }> {\n try {\n const normalizedLibrary = normalizeLibraryName(library);\n const normalizedVersion = normalizeVersionLabel(version);\n\n // One transaction for every delete, so a failure part-way through cannot\n // leave a library without versions, or a version without its pages.\n const remove = this.db.transaction(() => {\n const versionResult = this.statements.getVersionId.get(\n normalizedLibrary,\n normalizedVersion,\n ) as { id: number; library_id: number } | undefined;\n\n if (!versionResult) {\n // Version doesn't exist, return zero counts\n return { documentsDeleted: 0, versionDeleted: false, libraryDeleted: false };\n }\n\n const { id: versionId, library_id: libraryId } = versionResult;\n\n // Delete in order to respect foreign key constraints:\n // 1. documents (page_id → pages.id)\n // 2. pages (version_id → versions.id)\n // 3. versions (library_id → libraries.id)\n // 4. libraries (if empty)\n const documentsDeleted = this.deleteVersionContent(\n normalizedLibrary,\n normalizedVersion,\n );\n\n const versionDeleted =\n this.statements.deleteVersionById.run(versionId).changes > 0;\n\n let libraryDeleted = false;\n if (removeLibraryIfEmpty && versionDeleted) {\n const countResult = this.statements.countVersionsByLibraryId.get(libraryId) as\n | { count: number }\n | undefined;\n if ((countResult?.count ?? 0) === 0) {\n libraryDeleted = this.statements.deleteLibraryById.run(libraryId).changes > 0;\n }\n }\n\n return { documentsDeleted, versionDeleted, libraryDeleted };\n });\n return remove.immediate();\n } catch (error) {\n throw new ConnectionError(\"Failed to remove version\", error);\n }\n }\n\n /**\n * Parses the metadata field from a JSON string to an object.\n * This is necessary because better-sqlite3's json() function returns a string, not an object.\n */\n private parseMetadata<M extends {}, T extends { metadata: M }>(row: T): T {\n if (row.metadata && typeof row.metadata === \"string\") {\n try {\n row.metadata = JSON.parse(row.metadata);\n } catch (error) {\n logger.warn(`Failed to parse metadata JSON: ${error}`);\n row.metadata = {} as M;\n }\n }\n return row;\n }\n\n /**\n * Parses metadata for an array of rows.\n */\n private parseMetadataArray<M extends {}, T extends { metadata: M }>(rows: T[]): T[] {\n return rows.map((row) => this.parseMetadata(row));\n }\n\n /**\n * Retrieves a document by its ID.\n * @param id The ID of the document.\n * @returns The document, or null if not found.\n */\n async getById(id: string): Promise<DbPageChunk | null> {\n try {\n const row = this.statements.getById.get(BigInt(id)) as DbQueryResult<DbPageChunk>;\n if (!row) {\n return null;\n }\n\n return this.parseMetadata(row);\n } catch (error) {\n throw new ConnectionError(`Failed to get document by ID ${id}`, error);\n }\n }\n\n /**\n * Finds documents matching a text query using hybrid search when vector search is enabled,\n * or falls back to full-text search only when vector search is disabled.\n * Uses Reciprocal Rank Fusion for hybrid search or simple FTS ranking for fallback mode.\n */\n async findByContent(\n library: string,\n version: string,\n query: string,\n limit: number,\n ): Promise<(DbPageChunk & DbChunkRank)[]> {\n try {\n // Return empty array for empty or whitespace-only queries\n if (!query || typeof query !== \"string\" || query.trim().length === 0) {\n return [];\n }\n\n const ftsQuery = this.escapeFtsQuery(query);\n const normalizedVersion = normalizeVersionLabel(version);\n\n // Resolve library/version upfront so we can short-circuit missing versions\n // and constrain FTS queries by version_id.\n const versionRow = this.statements.getVersionId.get(\n normalizeLibraryName(library),\n normalizedVersion,\n ) as { id: number; library_id: number } | undefined;\n\n if (!versionRow) {\n return [];\n }\n\n const { id: versionId, library_id: libraryId } = versionRow;\n\n if (this.isVectorSearchEnabled && this.embeddings !== null) {\n // Hybrid search: vector + full-text search with RRF ranking\n const rawEmbedding = await this.embeddings.embedQuery(query);\n const embedding = this.padVector(rawEmbedding);\n\n // Apply overfetch factor to both vector and FTS searches for better recall\n const overfetchLimit = Math.max(1, limit * this.searchOverfetchFactor);\n\n // Use a multiplier to cast a wider net in vector search before final ranking\n const vectorSearchK = overfetchLimit * this.vectorSearchMultiplier;\n\n const stmt = this.db.prepare(`\n WITH vec_distances AS MATERIALIZED (\n SELECT\n dv.rowid as id,\n dv.distance as vec_distance\n FROM documents_vec dv\n WHERE dv.library_id = ?\n AND dv.version_id = ?\n AND dv.embedding MATCH ?\n AND dv.k = ?\n ORDER BY dv.distance\n ),\n fts_window AS MATERIALIZED (\n -- No join here; see VERSION_FTS_FILTER.\n SELECT\n f.rowid as id,\n bm25(documents_fts, 10.0, 1.0, 5.0, 1.0) as fts_score\n FROM documents_fts f\n WHERE ${VERSION_FTS_FILTER}\n AND documents_fts MATCH ?\n ORDER BY fts_score\n LIMIT ?\n ),\n fts_scores AS MATERIALIZED (\n -- Ties at the cut-off go by URL and chunk position, not storage\n -- order; see FTS_TIE_WINDOW_FACTOR.\n SELECT w.id, w.fts_score\n FROM fts_window w\n JOIN documents d ON d.id = w.id\n JOIN pages p ON p.id = d.page_id\n ORDER BY w.fts_score, p.url, d.sort_order\n LIMIT ?\n ),\n candidates AS (\n -- Union of vector and full-text candidate ids so the final query is\n -- driven by the small match set instead of scanning the entire\n -- documents table. Keeps search cost proportional to matches, not\n -- total database size.\n --\n -- Both source CTEs are referenced twice (here and in the LEFT JOINs\n -- below) and are pinned with MATERIALIZED so they are evaluated\n -- exactly once. Leaving this to the query planner is what caused\n -- the search regression in #454.\n SELECT id FROM vec_distances\n UNION\n SELECT id FROM fts_scores\n )\n SELECT\n d.id,\n d.content,\n d.metadata,\n d.sort_order,\n p.url as url,\n p.title as title,\n p.source_content_type as source_content_type,\n p.content_type as content_type,\n p.content_url as content_url,\n -- NULL when the method did not return the chunk, so it gets no\n -- rank from that method (see assignRanks).\n 1 / (1 + v.vec_distance) as vec_score,\n -MIN(f.fts_score, 0) as fts_score\n FROM candidates c\n JOIN documents d ON d.id = c.id\n JOIN pages p ON d.page_id = p.id\n LEFT JOIN vec_distances v ON d.id = v.id\n LEFT JOIN fts_scores f ON d.id = f.id\n WHERE NOT EXISTS (\n SELECT 1 FROM json_each(json_extract(d.metadata, '$.types')) je\n WHERE je.value = 'structural'\n )\n `);\n\n const rawResults = stmt.all(\n libraryId,\n versionId,\n JSON.stringify(embedding),\n vectorSearchK,\n versionId,\n ftsQuery,\n overfetchLimit * FTS_TIE_WINDOW_FACTOR,\n overfetchLimit,\n ) as RawSearchResult[];\n\n // Apply RRF ranking with configurable weights\n const rankedResults = this.assignRanks(rawResults);\n\n // Sort by RRF score and take top results (truncate to original limit)\n const topResults = rankedResults\n .sort((a, b) => b.rrf_score - a.rrf_score || compareTies(a, b))\n .slice(0, limit);\n\n return topResults.map((row) => {\n const result: DbPageChunk = {\n ...this.parseMetadata(row),\n url: row.url || \"\", // Ensure url is never undefined\n title: row.title || null,\n source_content_type: row.source_content_type || null,\n content_type: row.content_type || null,\n };\n // Add search scores as additional properties (not in metadata)\n return Object.assign(result, {\n score: row.rrf_score,\n vec_rank: row.vec_rank,\n fts_rank: row.fts_rank,\n });\n });\n } else {\n // Fallback: full-text search only\n const stmt = this.db.prepare(`\n SELECT\n d.id,\n d.content,\n d.metadata,\n d.sort_order,\n p.url as url,\n p.title as title,\n p.source_content_type as source_content_type,\n p.content_type as content_type,\n p.content_url as content_url,\n bm25(documents_fts, 10.0, 1.0, 5.0, 1.0) as fts_score\n FROM documents_fts f\n JOIN documents d ON f.rowid = d.id\n JOIN pages p ON d.page_id = p.id\n WHERE ${VERSION_FTS_FILTER}\n AND documents_fts MATCH ?\n AND NOT EXISTS (\n SELECT 1 FROM json_each(json_extract(d.metadata, '$.types')) je\n WHERE je.value = 'structural'\n )\n ORDER BY fts_score, p.url, d.sort_order\n LIMIT ?\n `);\n\n const rawResults = stmt.all(versionId, ftsQuery, limit) as (RawSearchResult & {\n fts_score: number;\n })[];\n\n // Assign FTS ranks based on order (best score = rank 1)\n return rawResults.map((row, index) => {\n const result: DbPageChunk = {\n ...this.parseMetadata(row),\n url: row.url || \"\", // Ensure url is never undefined\n title: row.title || null,\n source_content_type: row.source_content_type || null,\n content_type: row.content_type || null,\n };\n // Add search scores as additional properties (not in metadata)\n return Object.assign(result, {\n score: -row.fts_score, // Convert BM25 score to positive value for consistency\n fts_rank: index + 1, // Assign rank based on order (1-based)\n });\n });\n }\n } catch (error) {\n throw new ConnectionError(\n `Failed to find documents by content with query \"${query}\"`,\n error,\n );\n }\n }\n\n /**\n * Finds the child chunks of a chunk: the chunks on the same page, after it in\n * document order, whose path extends its path by exactly one element.\n *\n * @param library Library name.\n * @param version Version label.\n * @param id ID of the parent chunk.\n * @param limit Maximum number of children to return.\n * @returns The children in document order, or an empty array if the parent does not exist.\n */\n async findChildChunks(\n library: string,\n version: string,\n id: string,\n limit: number,\n ): Promise<DbPageChunk[]> {\n try {\n const parent = await this.getById(id);\n if (!parent) {\n return [];\n }\n\n const parentPath = parent.metadata.path ?? [];\n const normalizedVersion = normalizeVersionLabel(version);\n\n const result = this.statements.getChildChunks.all(\n normalizeLibraryName(library),\n normalizedVersion,\n parent.url,\n parentPath.length + 1,\n JSON.stringify(parentPath),\n BigInt(id),\n limit,\n ) as Array<DbPageChunk>;\n\n return this.parseMetadataArray(result);\n } catch (error) {\n throw new ConnectionError(`Failed to find child chunks for ID ${id}`, error);\n }\n }\n\n /**\n * Finds preceding sibling chunks of a given document.\n */\n async findPrecedingSiblingChunks(\n library: string,\n version: string,\n id: string,\n limit: number,\n ): Promise<DbPageChunk[]> {\n try {\n const reference = await this.getById(id);\n if (!reference) {\n return [];\n }\n\n const normalizedVersion = normalizeVersionLabel(version);\n\n const result = this.statements.getPrecedingSiblings.all(\n normalizeLibraryName(library),\n normalizedVersion,\n reference.url,\n BigInt(id),\n JSON.stringify(reference.metadata.path),\n limit,\n ) as Array<DbPageChunk>;\n\n return this.parseMetadataArray(result).reverse();\n } catch (error) {\n throw new ConnectionError(\n `Failed to find preceding sibling chunks for ID ${id}`,\n error,\n );\n }\n }\n\n /**\n * Finds subsequent sibling chunks of a given document.\n */\n async findSubsequentSiblingChunks(\n library: string,\n version: string,\n id: string,\n limit: number,\n ): Promise<DbPageChunk[]> {\n try {\n const reference = await this.getById(id);\n if (!reference) {\n return [];\n }\n\n const normalizedVersion = normalizeVersionLabel(version);\n\n const result = this.statements.getSubsequentSiblings.all(\n normalizeLibraryName(library),\n normalizedVersion,\n reference.url,\n BigInt(id),\n JSON.stringify(reference.metadata.path),\n limit,\n ) as Array<DbPageChunk>;\n\n return this.parseMetadataArray(result);\n } catch (error) {\n throw new ConnectionError(\n `Failed to find subsequent sibling chunks for ID ${id}`,\n error,\n );\n }\n }\n\n /**\n * Finds the parent chunk of a given document.\n * Returns null if no parent is found or if there's a database error.\n * Database errors are logged but not thrown to maintain consistent behavior.\n */\n async findParentChunk(\n library: string,\n version: string,\n id: string,\n ): Promise<DbPageChunk | null> {\n try {\n const child = await this.getById(id);\n if (!child) {\n return null;\n }\n\n const path = child.metadata.path ?? [];\n const parentPath = path.slice(0, -1);\n\n if (parentPath.length === 0) {\n return null;\n }\n\n const normalizedVersion = normalizeVersionLabel(version);\n const result = this.statements.getParentChunk.get(\n normalizeLibraryName(library),\n normalizedVersion,\n child.url,\n JSON.stringify(parentPath),\n BigInt(id),\n ) as DbQueryResult<DbPageChunk>;\n\n if (!result) {\n return null;\n }\n\n return this.parseMetadata(result);\n } catch (error) {\n logger.warn(`Failed to find parent chunk for ID ${id}: ${error}`);\n return null;\n }\n }\n\n /**\n * Fetches multiple documents by their IDs in a single call.\n * Returns an array of DbPageChunk objects, sorted by their sort_order.\n */\n async findChunksByIds(\n library: string,\n version: string,\n ids: string[],\n ): Promise<DbPageChunk[]> {\n if (!ids.length) return [];\n try {\n const normalizedVersion = normalizeVersionLabel(version);\n // Use parameterized query for variable number of IDs\n const placeholders = ids.map(() => \"?\").join(\",\");\n const stmt = this.db.prepare(\n `SELECT d.id, d.page_id, d.content, json(d.metadata) as metadata, d.sort_order, d.created_at, p.url, p.title, p.source_content_type, p.content_type, p.content_url FROM documents d\n JOIN pages p ON d.page_id = p.id\n JOIN versions v ON p.version_id = v.id\n JOIN libraries l ON v.library_id = l.id\n WHERE l.name = ? \n AND COALESCE(v.name, '') = COALESCE(?, '')\n AND d.id IN (${placeholders}) \n ORDER BY d.sort_order`,\n );\n const rows = stmt.all(\n normalizeLibraryName(library),\n normalizedVersion,\n ...ids,\n ) as DbPageChunk[];\n return this.parseMetadataArray(rows);\n } catch (error) {\n throw new ConnectionError(\"Failed to fetch documents by IDs\", error);\n }\n }\n\n /**\n * Fetches all document chunks for a specific URL within a library and version.\n * Returns DbPageChunk objects sorted by their sort_order for proper reassembly.\n */\n async findChunksByUrl(\n library: string,\n version: string,\n url: string,\n ): Promise<DbPageChunk[]> {\n try {\n const normalizedVersion = normalizeVersionLabel(version);\n const stmt = this.db.prepare(\n `SELECT d.id, d.page_id, d.content, json(d.metadata) as metadata, d.sort_order, d.created_at, p.url, p.title, p.source_content_type, p.content_type, p.content_url FROM documents d\n JOIN pages p ON d.page_id = p.id\n JOIN versions v ON p.version_id = v.id\n JOIN libraries l ON v.library_id = l.id\n WHERE l.name = ? \n AND COALESCE(v.name, '') = COALESCE(?, '')\n AND p.url = ?\n ORDER BY d.sort_order`,\n );\n const rows = stmt.all(\n normalizeLibraryName(library),\n normalizedVersion,\n url,\n ) as DbPageChunk[];\n return this.parseMetadataArray(rows);\n } catch (error) {\n throw new ConnectionError(`Failed to fetch documents by URL ${url}`, error);\n }\n }\n\n /**\n * Lists stored chunks for a library version with pagination and an optional\n * case-insensitive content filter. Powers the admin dashboard's chunk explorer.\n *\n * Position (`chunkIndex`/`pageChunkCount`) is computed with window functions\n * over `sort_order` rather than trusted verbatim, so results stay correct\n * even if a page's chunks were ever stored with non-contiguous ordering.\n * Token counts are never fabricated: the current schema has no per-chunk\n * token column, so every item's `tokenCount` is `null`.\n *\n * @param library Library name (case-insensitive).\n * @param version Version string (empty string for unversioned).\n * @param options Pagination (`limit`/`offset`) and optional content `filter`.\n * @returns The requested page of chunks plus the total count matching the filter.\n */\n async listVersionChunks(\n library: string,\n version: string,\n options: ListVersionChunksOptions,\n ): Promise<ListVersionChunksResult> {\n try {\n const normalizedVersion = normalizeVersionLabel(version);\n const versionRow = this.statements.getVersionId.get(\n normalizeLibraryName(library),\n normalizedVersion,\n ) as { id: number; library_id: number } | undefined;\n\n if (!versionRow) {\n return { chunks: [], total: 0 };\n }\n\n const offset = options.offset ?? 0;\n const trimmedFilter = options.filter?.trim();\n\n const whereParams: (string | number)[] = [versionRow.id];\n let whereClause = \"WHERE p.version_id = ?\";\n if (trimmedFilter) {\n whereClause += \" AND LOWER(d.content) LIKE LOWER(?) ESCAPE '\\\\'\";\n whereParams.push(`%${this.escapeLikePattern(trimmedFilter)}%`);\n }\n\n const countStmt = this.db.prepare(\n `SELECT COUNT(*) as count\n FROM documents d\n JOIN pages p ON d.page_id = p.id\n ${whereClause}`,\n );\n const countRow = countStmt.get(...whereParams) as { count: number };\n const total = countRow.count;\n\n const dataStmt = this.db.prepare(\n `SELECT\n d.id,\n d.content,\n (d.embedding IS NOT NULL) as has_embedding,\n p.url as url,\n p.content_type as mime_type,\n ROW_NUMBER() OVER (PARTITION BY d.page_id ORDER BY d.sort_order, d.id) as chunk_index,\n COUNT(*) OVER (PARTITION BY d.page_id) as page_chunk_count\n FROM documents d\n JOIN pages p ON d.page_id = p.id\n ${whereClause}\n ORDER BY p.url, d.sort_order, d.id\n LIMIT ? OFFSET ?`,\n );\n const rows = dataStmt.all(...whereParams, options.limit, offset) as Array<{\n id: number;\n content: string;\n has_embedding: number;\n url: string;\n mime_type: string | null;\n chunk_index: number;\n page_chunk_count: number;\n }>;\n\n const chunks: VersionChunkListItem[] = rows.map((row) => ({\n id: String(row.id),\n url: row.url,\n content: row.content,\n mimeType: row.mime_type,\n chunkIndex: row.chunk_index,\n pageChunkCount: row.page_chunk_count,\n charCount: row.content.length,\n tokenCount: null,\n hasEmbedding: Boolean(row.has_embedding),\n }));\n\n return { chunks, total };\n } catch (error) {\n throw new ConnectionError(\"Failed to list version chunks\", error);\n }\n }\n\n /**\n * Computes aggregate chunk/page/embedding statistics for a library version,\n * for the chunk explorer's header strip.\n *\n * `avgTokensPerChunk` is always `null`: the schema does not persist\n * per-chunk token counts, so this is reported as unavailable rather than\n * fabricated from character counts.\n *\n * @param library Library name (case-insensitive).\n * @param version Version string (empty string for unversioned).\n * @returns Aggregate statistics, or all-zero/`null` values if the version doesn't exist.\n */\n async getVersionStats(library: string, version: string): Promise<VersionChunkStats> {\n try {\n const normalizedVersion = normalizeVersionLabel(version);\n const versionRow = this.statements.getVersionId.get(\n normalizeLibraryName(library),\n normalizedVersion,\n ) as { id: number; library_id: number } | undefined;\n\n if (!versionRow) {\n return {\n pageCount: 0,\n chunkCount: 0,\n avgChunksPerPage: null,\n avgTokensPerChunk: null,\n embeddedChunkCount: 0,\n };\n }\n\n const stmt = this.db.prepare(\n `SELECT\n COUNT(DISTINCT p.id) as page_count,\n COUNT(d.id) as chunk_count,\n SUM(CASE WHEN d.embedding IS NOT NULL THEN 1 ELSE 0 END) as embedded_chunk_count\n FROM pages p\n LEFT JOIN documents d ON d.page_id = p.id\n WHERE p.version_id = ?`,\n );\n const row = stmt.get(versionRow.id) as {\n page_count: number;\n chunk_count: number;\n embedded_chunk_count: number | null;\n };\n\n return {\n pageCount: row.page_count,\n chunkCount: row.chunk_count,\n avgChunksPerPage: row.page_count > 0 ? row.chunk_count / row.page_count : null,\n avgTokensPerChunk: null,\n embeddedChunkCount: row.embedded_chunk_count ?? 0,\n };\n } catch (error) {\n throw new ConnectionError(\"Failed to get version stats\", error);\n }\n }\n\n /**\n * Returns per-day indexing activity over the trailing `days`-day window,\n * derived from the `created_at` timestamps already stored on pages. Days\n * with no activity are zero-filled so the returned series is contiguous.\n *\n * Rows are grouped by UTC calendar day to match SQLite's `date('now')`.\n * A page's `created_at` reflects first insertion, and its chunks count on\n * that same day, so a refresh that re-chunks an existing page does not\n * inflate the counts (it is genuinely new content, not re-touched content,\n * that registers as activity). The window is read through the\n * `pages(created_at)` and `documents(page_id, sort_order)` indexes.\n *\n * @param days - Window length in days; clamped to 1..366.\n */\n async getActivityHistory(days: number): Promise<ActivityHistory> {\n try {\n const windowDays = Math.max(1, Math.min(366, Math.floor(days) || 1));\n // A recursive calendar drives the zero-fill: every day in the window is\n // emitted even when neither `pages` nor `documents` has a row for it.\n const stmt = this.db.prepare(\n `WITH RECURSIVE calendar(day) AS (\n SELECT date('now', '-' || (@days - 1) || ' days')\n UNION ALL\n SELECT date(day, '+1 day') FROM calendar WHERE day < date('now')\n )\n SELECT\n calendar.day AS date,\n COALESCE(activity.pages, 0) AS pages,\n COALESCE(activity.chunks, 0) AS chunks\n FROM calendar\n LEFT JOIN (\n SELECT\n date(p.created_at) AS day,\n COUNT(*) AS pages,\n SUM((SELECT COUNT(*) FROM documents c WHERE c.page_id = p.id)) AS chunks\n FROM pages p\n WHERE p.created_at >= date('now', '-' || (@days - 1) || ' days')\n GROUP BY day\n ) activity ON activity.day = calendar.day\n ORDER BY calendar.day`,\n );\n const rows = stmt.all({ days: windowDays }) as Array<{\n date: string;\n pages: number;\n chunks: number;\n }>;\n\n let totalPages = 0;\n let totalChunks = 0;\n for (const row of rows) {\n totalPages += row.pages;\n totalChunks += row.chunks;\n }\n\n return {\n days: rows.map((row) => ({\n date: row.date,\n pages: row.pages,\n chunks: row.chunks,\n })),\n since: rows[0]?.date ?? \"\",\n until: rows[rows.length - 1]?.date ?? \"\",\n totalPages,\n totalChunks,\n };\n } catch (error) {\n throw new ConnectionError(\"Failed to get activity history\", error);\n }\n }\n\n /**\n * Returns a per-version content-type breakdown: pages grouped by MIME type\n * (`content_type`, falling back to `source_content_type`, else `unknown`),\n * most common first. Derived from the stored pages.\n *\n * @param library - Library name (case-insensitive).\n * @param version - Version name (empty string for unversioned).\n */\n async getVersionComposition(\n library: string,\n version: string,\n ): Promise<VersionComposition> {\n try {\n const versionRow = this.statements.getVersionId.get(\n normalizeLibraryName(library),\n normalizeVersionLabel(version),\n ) as { id: number } | undefined;\n\n if (!versionRow) return { mimeTypes: [] };\n\n const mimeRows = this.db\n .prepare(\n `SELECT\n COALESCE(NULLIF(p.content_type, ''), NULLIF(p.source_content_type, ''), 'unknown') AS label,\n COUNT(*) AS pages\n FROM pages p\n WHERE p.version_id = ?\n GROUP BY label\n ORDER BY pages DESC, label`,\n )\n .all(versionRow.id) as Array<{ label: string; pages: number }>;\n\n return {\n mimeTypes: mimeRows.map((row) => ({ label: row.label, pages: row.pages })),\n };\n } catch (error) {\n throw new ConnectionError(\"Failed to get version composition\", error);\n }\n }\n}\n","import path from \"node:path\";\nimport Fuse from \"fuse.js\";\nimport semver from \"semver\";\nimport type { EventBusService } from \"../events\";\nimport { EventType } from \"../events\";\nimport { PipelineFactory } from \"../scraper/pipelines/PipelineFactory\";\nimport type { ContentPipeline } from \"../scraper/pipelines/types\";\nimport type { ScrapeResult, ScraperOptions } from \"../scraper/types\";\nimport type { Chunk } from \"../splitter/types\";\nimport { telemetry } from \"../telemetry\";\nimport type { AppConfig } from \"../utils/config\";\nimport { logger } from \"../utils/logger\";\nimport { formatBytes } from \"../utils/string\";\nimport { normalizeUrl } from \"../utils/url\";\nimport {\n isSemanticVersion,\n type SemanticVersionCandidate,\n sortVersionsDescending,\n toVersionCandidates,\n VERSION_REQUEST_PATTERN,\n type VersionCandidate,\n} from \"../utils/version\";\nimport { createContentAssemblyStrategy } from \"./assembly/ContentAssemblyStrategyFactory\";\nimport { DocumentRetrieverService } from \"./DocumentRetrieverService\";\nimport { DocumentStore } from \"./DocumentStore\";\nimport type { EmbeddingModelConfig } from \"./embeddings/EmbeddingConfig\";\nimport {\n AmbiguousPageInStoreError,\n LibraryNotFoundInStoreError,\n PageNotFoundInStoreError,\n StoreError,\n VersionNotFoundInStoreError,\n} from \"./errors\";\nimport type {\n ActivityHistory,\n CompactResult,\n DbPageChunk,\n DbVersionWithLibrary,\n EmbeddingConfigInfo,\n FindVersionResult,\n LibrarySummary,\n ListPagesOptions,\n ListPagesResult,\n ListVersionChunksOptions,\n ListVersionChunksResult,\n PageContentOptions,\n PageContentResult,\n ResolvedVersion,\n ScraperConfig,\n StoreSearchResult,\n VersionChunkStats,\n VersionComposition,\n VersionRef,\n VersionStatus,\n VersionSummary,\n} from \"./types\";\nimport {\n type ExistingTargetPolicy,\n normalizeVersionLabel,\n normalizeVersionRef,\n} from \"./types\";\n\n/** Upper bound on the pages listed when a path matches more than one. */\nconst MAX_AMBIGUOUS_PAGE_MATCHES = 10;\n\n/**\n * Returns the distinct spellings a stored URL may use for `value`: as given,\n * encoded, and percent-decoded.\n */\nfunction spellingsOf(value: string, encode: (value: string) => string): string[] {\n let decoded = value;\n try {\n decoded = decodeURIComponent(value);\n } catch {\n // Not valid percent-encoding; the other spellings still apply.\n }\n return [...new Set([value, encode(value), decoded])];\n}\n\n/**\n * Percent-encodes a path the way URL parsing does when the scraper stores a URL.\n * Hash-only routes are left alone because they carry no path.\n */\nfunction encodePath(path: string): string {\n if (!path.startsWith(\"/\")) return path;\n const url = new URL(path, \"http://placeholder\");\n return `${url.pathname}${url.search}${url.hash}`;\n}\n\n/**\n * Turns a page path into the URL ending to match: rooted at `/` (hash routes\n * excepted), without trailing slashes. Empty for the root path.\n */\nfunction toPathSuffix(path: string): string {\n const trimmed = path.replace(/\\/+$/, \"\");\n if (!trimmed) return \"\";\n return trimmed.startsWith(\"/\") || trimmed.startsWith(\"#\") ? trimmed : `/${trimmed}`;\n}\n\n/**\n * Provides semantic search capabilities across different versions of library documentation.\n * Uses content-type-specific pipelines for processing and splitting content.\n */\nexport class DocumentManagementService {\n private readonly appConfig: AppConfig;\n private readonly store: DocumentStore;\n private readonly documentRetriever: DocumentRetrieverService;\n private readonly pipelines: ContentPipeline[];\n private readonly eventBus: EventBusService;\n\n constructor(eventBus: EventBusService, appConfig: AppConfig) {\n this.appConfig = appConfig;\n this.eventBus = eventBus;\n const storePath = this.appConfig.app.storePath;\n if (!storePath) {\n throw new Error(\"storePath is required when not using a remote server\");\n }\n // Handle special :memory: case for in-memory databases (primarily for testing)\n const dbPath =\n storePath === \":memory:\" ? \":memory:\" : path.join(storePath, \"documents.db\");\n\n logger.debug(`Using database path: ${dbPath}`);\n\n // Directory creation is handled by the centralized path resolution\n\n this.store = new DocumentStore(dbPath, this.appConfig);\n this.documentRetriever = new DocumentRetrieverService(this.store, this.appConfig);\n\n // Initialize content pipelines for different content types including universal TextPipeline fallback\n this.pipelines = PipelineFactory.createStandardPipelines(this.appConfig);\n }\n\n /**\n * Returns the active embedding configuration if vector search is enabled,\n * or null if embeddings are disabled.\n */\n getActiveEmbeddingConfig(): EmbeddingModelConfig | null {\n return this.store.getActiveEmbeddingConfig();\n }\n\n async getEmbeddingConfigInfo(): Promise<EmbeddingConfigInfo | null> {\n const config = this.getActiveEmbeddingConfig();\n return config\n ? {\n provider: config.provider,\n model: config.model,\n dimensions: config.dimensions,\n }\n : null;\n }\n\n /**\n * Initializes the underlying document store.\n */\n async initialize(): Promise<void> {\n await this.store.initialize();\n }\n\n /**\n * Resolves a confirmed embedding model change by invalidating all vectors\n * and completing the initialization that was interrupted by EmbeddingModelChangedError.\n */\n async resolveModelChange(): Promise<void> {\n await this.store.resolveModelChange();\n }\n\n /**\n * Shuts down the underlying document store and cleans up pipeline resources.\n */\n\n async shutdown(): Promise<void> {\n logger.debug(\"Shutting down store manager\");\n\n // Cleanup all pipelines to prevent resource leaks (e.g., browser instances)\n await Promise.allSettled(this.pipelines.map((pipeline) => pipeline.close()));\n\n await this.store.shutdown();\n }\n\n // Status tracking methods for pipeline integration\n\n /**\n * Gets versions by their current status.\n */\n async getVersionsByStatus(statuses: VersionStatus[]): Promise<DbVersionWithLibrary[]> {\n return this.store.getVersionsByStatus(statuses);\n }\n\n /**\n * Marks the jobs of QUEUED or RUNNING versions alive for other processes on\n * the store.\n * @param versionIds The versions whose jobs are alive\n * @throws {StoreError} When the write fails\n */\n async markVersionsAlive(versionIds: number[]): Promise<void> {\n return this.store.markVersionsAlive(versionIds);\n }\n\n /**\n * Claims a version an earlier run left QUEUED or RUNNING, if nothing has\n * written it since `updatedAt` was read; see {@link DocumentStore.claimInterruptedVersion}.\n * @returns Whether the claim succeeded\n */\n async claimInterruptedVersion(\n versionId: number,\n updatedAt: string | null,\n ): Promise<boolean> {\n return this.store.claimInterruptedVersion(versionId, updatedAt);\n }\n\n /**\n * Updates the status of a version, and tells views the library list changed.\n */\n async updateVersionStatus(\n versionId: number,\n status: VersionStatus,\n errorMessage?: string,\n ): Promise<void> {\n await this.store.updateVersionStatus(versionId, status, errorMessage);\n this.eventBus.emit(EventType.LIBRARY_CHANGE, undefined);\n }\n\n /**\n * Updates the progress of a version being indexed.\n */\n async updateVersionProgress(\n versionId: number,\n pages: number,\n maxPages: number,\n pagesIndexed: number | null = null,\n ): Promise<void> {\n return this.store.updateVersionProgress(versionId, pages, maxPages, pagesIndexed);\n }\n\n /**\n * Stores scraper options for a version to enable reproducible indexing.\n */\n async storeScraperOptions(versionId: number, options: ScraperOptions): Promise<void> {\n return this.store.storeScraperOptions(versionId, options);\n }\n\n /**\n * Retrieves stored scraper options for a version.\n */\n /**\n * Retrieves stored scraping configuration for a version.\n */\n async getScraperOptions(versionId: number): Promise<ScraperConfig | null> {\n return this.store.getScraperOptions(versionId);\n }\n\n /**\n * Ensures a library/version exists using a VersionRef and returns version ID.\n * The `VersionRef` form of {@link ensureLibraryAndVersion}.\n */\n async ensureVersion(ref: VersionRef): Promise<number> {\n return this.ensureLibraryAndVersion(ref.library, ref.version);\n }\n\n /**\n * Creates or verifies the library and version an indexing job writes into, atomically.\n * See {@link DocumentStore.claimVersion} for the policy semantics and errors.\n */\n async claimVersion(\n library: string,\n version: string,\n policy: ExistingTargetPolicy,\n ): Promise<ResolvedVersion> {\n return this.store.claimVersion(library, version, policy);\n }\n\n /**\n * Looks up a version that must already exist, without creating anything.\n *\n * @returns The version id and the library's stored display name.\n * @throws {LibraryNotFoundInStoreError} When the library does not exist (with suggestions).\n * @throws {VersionNotFoundInStoreError} When the library exists but the version does not.\n */\n async requireVersion(ref: VersionRef): Promise<ResolvedVersion> {\n const found = await this.store.findVersion(ref.library, ref.version);\n if (found) {\n return found;\n }\n throw await this.versionNotFound(ref.library, normalizeVersionLabel(ref.version));\n }\n\n /**\n * Builds the version-not-found error for a version that does not resolve,\n * naming the library as it is stored.\n * @throws {LibraryNotFoundInStoreError} When the library itself is missing (with suggestions).\n */\n private async versionNotFound(\n library: string,\n version: string,\n ): Promise<VersionNotFoundInStoreError> {\n const { displayName } = await this.requireLibrary(library);\n return new VersionNotFoundInStoreError(\n displayName,\n version,\n await this.listAvailableLabels(library),\n );\n }\n\n /**\n * Returns enriched library summaries including version status/progress and counts.\n * Uses existing store APIs; keeps DB details encapsulated.\n */\n async listLibraries(): Promise<LibrarySummary[]> {\n const libMap = await this.store.queryLibraryVersions();\n const summaries: LibrarySummary[] = [];\n for (const [library, versions] of libMap) {\n const vs = await Promise.all(\n versions.map(async (v) => {\n const scraperOptions = await this.store.getScraperOptions(v.versionId);\n return {\n id: v.versionId,\n ref: { library, version: v.version },\n status: v.status as VersionStatus,\n errorMessage: v.errorMessage,\n // Include progress only while indexing is active; set undefined for COMPLETED\n progress:\n v.status === \"completed\"\n ? undefined\n : { pages: v.progressPages, maxPages: v.progressMaxPages },\n counts: { documents: v.documentCount, uniqueUrls: v.uniqueUrlCount },\n indexedAt: v.indexedAt,\n sourceUrl: v.sourceUrl ?? undefined,\n preserveHashes: scraperOptions?.options.preserveHashes,\n } satisfies VersionSummary;\n }),\n );\n summaries.push({ library, versions: vs });\n }\n return summaries;\n }\n\n /**\n * Finds versions that were indexed from the same source URL.\n */\n async findVersionsBySourceUrl(url: string): Promise<DbVersionWithLibrary[]> {\n return this.store.findVersionsBySourceUrl(url);\n }\n\n /**\n * Validates if a library exists in the store.\n * Checks if the library record exists in the database, regardless of whether it has versions or documents.\n * Throws LibraryNotFoundInStoreError with suggestions if the library is not found.\n * @param library The name of the library to validate.\n * @throws {LibraryNotFoundInStoreError} If the library does not exist.\n */\n async validateLibraryExists(library: string): Promise<void> {\n logger.info(`🔎 Validating existence of library: ${library}`);\n\n await this.requireLibrary(library);\n\n logger.info(`✅ Library '${library}' confirmed to exist.`);\n }\n\n /**\n * Looks up a library that must exist, without creating anything.\n * @throws {LibraryNotFoundInStoreError} When it does not (with suggestions).\n */\n private async requireLibrary(library: string): Promise<{ displayName: string }> {\n const libraryRecord = await this.store.getLibrary(library);\n if (!libraryRecord) {\n throw await this.libraryNotFound(library);\n }\n return libraryRecord;\n }\n\n /** Builds the library-not-found error, suggesting similarly named libraries. */\n private async libraryNotFound(library: string): Promise<LibraryNotFoundInStoreError> {\n logger.warn(`⚠️ Library '${library}' not found.`);\n\n // Library doesn't exist; suggest from the stored display names\n const libraryNames = [...(await this.store.queryLibraryVersions()).keys()];\n\n let suggestions: string[] = [];\n if (libraryNames.length > 0) {\n const fuse = new Fuse(libraryNames, {\n threshold: 0.7, // Adjust threshold for desired fuzziness (0=exact, 1=match anything)\n });\n const results = fuse.search(library.toLowerCase());\n // Take top 3 suggestions\n suggestions = results.slice(0, 3).map((result) => result.item);\n logger.info(`🔍 Found suggestions: ${suggestions.join(\", \")}`);\n }\n\n return new LibraryNotFoundInStoreError(library, suggestions);\n }\n\n /**\n * Returns every label stored for a library — semantic versions and opaque tags\n * alike — in canonical display order.\n *\n * Dropping tags here is what made documentation indexed as \"latest\" or\n * \"stable\" unreachable. The empty label is excluded because it represents\n * unversioned content, which is tracked separately.\n */\n async listVersions(library: string): Promise<string[]> {\n const versions = await this.store.queryUniqueVersions(library);\n return sortVersionsDescending(versions.filter((v) => v !== \"\"));\n }\n\n /**\n * Checks if documents exist for a given library and optional version.\n * If version is omitted, checks for documents without a specific version.\n */\n async exists(library: string, version?: string | null): Promise<boolean> {\n const normalizedVersion = normalizeVersionLabel(version);\n return this.store.checkDocumentExists(library, normalizedVersion);\n }\n\n /**\n * Lists every label stored for a library, for inclusion in error messages.\n *\n * Unlike {@link listVersions} this is not filtered or ordered for matching —\n * it is what a caller may ask for, including opaque tags the resolver could\n * not rank.\n *\n * @param library Library name.\n * @returns Every stored label, including the empty unversioned label.\n */\n private async listAvailableLabels(library: string): Promise<string[]> {\n return this.store.queryUniqueVersions(library);\n }\n\n /**\n * Resolves a requested version against a library's stored labels.\n *\n * The ladder is ordered so that the most specific answer wins:\n *\n * 1. A literal match on a stored label, so any indexed bucket is always\n * reachable by the name it was indexed under — including an opaque tag.\n * 2. Semantic version matching over the version-tier labels, ranking\n * prereleases as ordinary versions.\n * 3. A library's single opaque tag, when it has no semantic versions at all.\n *\n * @param candidates Classified labels stored for the library.\n * @param targetVersion The version the caller requested, if any.\n * @returns The stored label to use, or `null` when nothing resolves.\n * @throws {VersionNotFoundInStoreError} When only tags exist and several are\n * available, so no single one can be called newest.\n */\n private resolveVersionLabel(\n candidates: VersionCandidate[],\n targetVersion?: string,\n ): string | null {\n const requested = normalizeVersionLabel(targetVersion);\n\n // Rung 1: literal match.\n if (requested !== \"\") {\n const literal = candidates.find((c) => c.stored === requested);\n if (literal) {\n return literal.stored;\n }\n }\n\n // Rung 2: semantic version matching.\n const versions = candidates.filter(isSemanticVersion);\n if (versions.length > 0) {\n const matched = this.matchSemanticVersion(versions, requested);\n if (matched) {\n return matched;\n }\n }\n\n // Rung 3: a lone opaque tag, only when the caller expressed no preference\n // and there is no semantic version to rank ahead of it. With no semantic\n // versions every candidate is a tag, so one candidate means one tag.\n if (requested === \"\" && versions.length === 0 && candidates.length === 1) {\n return candidates[0].stored;\n }\n\n return null;\n }\n\n /**\n * Matches a request against semantic-version labels.\n *\n * A request naming a specific version matches that version or the highest one\n * below it, because older documentation is more useful than none. Prereleases\n * are ranked as ordinary versions: `includePrerelease` keeps semver from\n * skipping a prerelease that is the closest available match, which matters for\n * documentation in a way it does not for installing packages.\n *\n * @param versions Semantic-version candidates for the library.\n * @param requested Normalized request; empty means no preference.\n * @returns The stored label of the best match, or `null` when none matches.\n */\n private matchSemanticVersion(\n versions: SemanticVersionCandidate[],\n requested: string,\n ): string | null {\n const normalizedCandidates = versions.map((c) => c.normalized);\n const options: semver.RangeOptions = { includePrerelease: true };\n\n let range: string;\n if (requested === \"\" || requested === \"latest\") {\n range = \"*\";\n } else if (semver.valid(requested)) {\n // An exact version: allow matching it OR any older version\n range = `${requested} || <=${requested}`;\n } else if (VERSION_REQUEST_PATTERN.test(requested)) {\n // A partial version or X-range (\"1\", \"1.2\", \"1.x\"): already a valid range\n range = requested;\n } else {\n logger.warn(`⚠️ Invalid target version format: ${requested}`);\n return null;\n }\n\n const best = semver.maxSatisfying(normalizedCandidates, range, options);\n if (!best) {\n return null;\n }\n\n // Map the winning normalized version back to a stored label. Several labels\n // can normalize to the same version (\"1.20\" and \"1.20.0\"); rung 1 already\n // handled a caller asking for one by name, so prefer the strict spelling.\n const matches = versions.filter((c) => c.normalized === best);\n return (matches.find((c) => c.strict) ?? matches[0]).stored;\n }\n\n /**\n * Finds the most appropriate stored label for a requested version.\n *\n * Resolution itself lives in {@link resolveVersionLabel}; this adds the\n * unversioned bucket, which a resolved label always outranks, and the error\n * raised when neither produces anything.\n *\n * @param library Library name.\n * @param targetVersion The version requested, if any.\n * @returns The resolved label (or `null`) and whether unversioned docs exist.\n * @throws {VersionNotFoundInStoreError} When nothing resolves and no\n * unversioned documentation exists.\n * @throws {LibraryNotFoundInStoreError} When the library has no content.\n */\n async findBestVersion(\n library: string,\n targetVersion?: string,\n ): Promise<FindVersionResult> {\n const libraryAndVersion = `${library}${targetVersion ? `@${targetVersion}` : \"\"}`;\n logger.info(`🔍 Finding best version for ${libraryAndVersion}`);\n\n // Unversioned content is tracked separately from labelled buckets, so check\n // for it before any label handling.\n const hasUnversioned = await this.store.checkDocumentExists(library, \"\");\n const labels = await this.listVersions(library);\n\n if (labels.length === 0) {\n if (hasUnversioned) {\n logger.info(`ℹ️ Unversioned documents exist for ${library}`);\n return { bestMatch: null, hasUnversioned: true };\n }\n logger.warn(`⚠️ No versions found for ${library}`);\n // The next line should usually throw\n await this.validateLibraryExists(library);\n // Fallback, should not reach here\n throw new LibraryNotFoundInStoreError(library, []);\n }\n\n const candidates = toVersionCandidates(labels);\n const bestMatch = this.resolveVersionLabel(candidates, targetVersion);\n\n if (bestMatch) {\n logger.info(`✅ Found best match version ${bestMatch} for ${libraryAndVersion}`);\n } else {\n logger.warn(`⚠️ No matching version found for ${libraryAndVersion}`);\n }\n\n // A resolved label always wins over the unversioned bucket, so indexed\n // documentation is never silently skipped. Only when nothing resolves does\n // unversioned content come into play, and failing that we report the error.\n if (!bestMatch && !hasUnversioned) {\n throw await this.versionNotFound(library, targetVersion ?? \"\");\n }\n\n return { bestMatch, hasUnversioned };\n }\n\n /**\n * Removes all documents for a specific library and optional version.\n * If version is omitted, removes documents without a specific version.\n */\n async removeAllDocuments(library: string, version?: string | null): Promise<void> {\n const normalizedVersion = normalizeVersionLabel(version);\n logger.info(\n `🗑️ Removing all documents from ${library}@${normalizedVersion || \"latest\"} store`,\n );\n const count = await this.store.deletePages(library, normalizedVersion);\n logger.info(`🗑️ Deleted ${count} documents`);\n await this.compactAfterDelete();\n\n // Emit library change event\n this.eventBus.emit(EventType.LIBRARY_CHANGE, undefined);\n }\n\n /**\n * Deletes a page and all its associated document chunks.\n * This is used during refresh operations when a page returns 404 Not Found.\n */\n async deletePage(pageId: number): Promise<void> {\n logger.debug(`Deleting page ID: ${pageId}`);\n await this.store.deletePage(pageId);\n\n // Emit library change event\n this.eventBus.emit(EventType.LIBRARY_CHANGE, undefined);\n }\n\n /**\n * Retrieves all pages for a specific version ID with their metadata.\n * Used for refresh operations to get existing pages with their ETags and depths.\n */\n async getPagesByVersionId(versionId: number): Promise<\n Array<{\n id: number;\n url: string;\n etag: string | null;\n depth: number | null;\n content_url: string | null;\n }>\n > {\n return this.store.getPagesByVersionId(versionId);\n }\n\n /**\n * Completely removes a library version and all associated documents.\n * Also removes the library if no other versions remain.\n * If the specified version doesn't exist but the library exists with no versions, removes the library.\n * @param library Library name\n * @param version Version string (null/undefined for unversioned)\n */\n async removeVersion(library: string, version?: string | null): Promise<void> {\n const normalizedVersion = normalizeVersionLabel(version);\n logger.debug(`Removing version: ${library}@${normalizedVersion || \"latest\"}`);\n\n const result = await this.store.removeVersion(library, normalizedVersion, true);\n\n logger.info(`🗑️ Removed ${result.documentsDeleted} documents`);\n\n if (result.versionDeleted && result.libraryDeleted) {\n logger.info(`🗑️ Completely removed library ${library} (was last version)`);\n } else if (result.versionDeleted) {\n logger.info(`🗑️ Removed version ${library}@${normalizedVersion || \"latest\"}`);\n } else {\n // Version not found - check if library exists but is empty (has no versions)\n logger.warn(`⚠️ Version ${library}@${normalizedVersion || \"latest\"} not found`);\n\n const libraryRecord = await this.store.getLibrary(library);\n if (libraryRecord) {\n // Library exists - check if it has any versions\n const versions = await this.store.queryUniqueVersions(library);\n if (versions.length === 0) {\n // Library exists but has no versions - delete the library itself\n logger.info(`🗑️ Library ${library} has no versions, removing library record`);\n await this.store.deleteLibrary(libraryRecord.id);\n logger.info(`🗑️ Completely removed library ${library} (had no versions)`);\n }\n }\n }\n\n await this.compactAfterDelete();\n\n // Emit library change event\n this.eventBus.emit(EventType.LIBRARY_CHANGE, undefined);\n }\n\n /**\n * Reclaims unused SQLite pages and truncates the WAL file.\n * VACUUM takes an exclusive lock; use the CLI/`compact` mutation when idle.\n *\n * @param options.force Always VACUUM even if no free pages are detected\n * @param options.vacuum When `false`, only run a non-blocking WAL checkpoint\n */\n async compact(options?: { force?: boolean; vacuum?: boolean }): Promise<CompactResult> {\n const result = await this.store.compact(options);\n if (result.skipped) {\n logger.info(\"🧹 Skipped compaction for in-memory store\");\n } else if (result.vacuumed) {\n logger.info(\n `🧹 Compacted store: ${formatBytes(result.beforeBytes)} → ${formatBytes(result.afterBytes)} (reclaimed ${formatBytes(result.reclaimedBytes)})`,\n );\n } else if (result.reclaimedBytes > 0) {\n logger.info(\n `🧹 Checkpointed store: ${formatBytes(result.beforeBytes)} → ${formatBytes(result.afterBytes)} (reclaimed ${formatBytes(result.reclaimedBytes)})`,\n );\n } else if (options?.vacuum === false) {\n logger.info(\"🧹 Checkpointed WAL after delete\");\n } else {\n logger.info(\"🧹 No free pages to reclaim\");\n }\n return result;\n }\n\n /**\n * Best-effort WAL checkpoint after a bulk delete. Does not VACUUM, so readers\n * stay unblocked. Remove succeeds even if the checkpoint fails.\n */\n private async compactAfterDelete(): Promise<void> {\n try {\n await this.compact({ force: false, vacuum: false });\n } catch (error) {\n logger.error(\n `❌ Failed to checkpoint store after delete: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n /**\n * Records a page that exists but holds no content, replacing anything stored\n * for it previously.\n *\n * @param library Library name.\n * @param version Version string (null/undefined for unversioned).\n * @param depth Crawl depth the page was found at.\n * @param page Page identity and optional validators.\n */\n async addEmptyPage(\n library: string,\n version: string | null | undefined,\n depth: number,\n page: {\n url: string;\n contentUrl?: string;\n title: string;\n sourceContentType: string | null;\n contentType: string | null;\n etag: string | null;\n lastModified: string | null;\n isAdditionalRepresentation?: boolean;\n },\n previousPageId?: number,\n ): Promise<void> {\n if (!page.url) {\n throw new StoreError(\"Empty page metadata must include a valid URL\");\n }\n await this.store.addEmptyPage(\n library,\n normalizeVersionLabel(version),\n depth,\n page,\n previousPageId,\n );\n this.eventBus.emit(EventType.LIBRARY_CHANGE, undefined);\n }\n\n /**\n * Adds pre-processed content directly to the store.\n * This method is used when content has already been processed by a pipeline,\n * avoiding redundant processing. Used primarily by the scraping pipeline.\n *\n * @param library Library name\n * @param version Version string (null/undefined for unversioned)\n * @param processed Pre-processed content with chunks already created\n * @param previousPageId Page a refresh read this content from, retired by the\n * store when the write lands under a different row.\n */\n async addScrapeResult(\n library: string,\n version: string | null | undefined,\n depth: number,\n result: ScrapeResult,\n previousPageId?: number,\n ): Promise<void> {\n const processingStart = performance.now();\n const normalizedVersion = normalizeVersionLabel(version);\n const { url, title, chunks, contentType } = result;\n if (!url) {\n throw new StoreError(\"Processed content metadata must include a valid URL\");\n }\n\n logger.info(`📚 Adding processed content: ${title || url}`);\n\n if (chunks.length === 0) {\n logger.warn(`⚠️ No chunks in processed content for ${url}. Skipping.`);\n return;\n }\n\n try {\n logger.info(`✂️ Storing ${chunks.length} pre-split chunks`);\n\n // Add split documents to store\n await this.store.addDocuments(\n library,\n normalizedVersion,\n depth,\n result,\n previousPageId,\n );\n\n // Emit library change event after adding documents\n this.eventBus.emit(EventType.LIBRARY_CHANGE, undefined);\n } catch (error) {\n // Track processing failures with native error tracking\n const processingTime = performance.now() - processingStart;\n\n if (error instanceof Error) {\n telemetry.captureException(error, {\n mimeType: contentType,\n contentSizeBytes: chunks.reduce(\n (sum: number, chunk: Chunk) => sum + chunk.content.length,\n 0,\n ),\n processingTimeMs: Math.round(processingTime),\n library,\n libraryVersion: normalizedVersion || null,\n context: \"processed_content_storage\",\n component: DocumentManagementService.constructor.name,\n });\n }\n\n throw error;\n }\n }\n\n /**\n * Searches for documentation content across versions.\n * Uses hybrid search (vector + FTS).\n * If version is omitted, searches documents without a specific version.\n */\n async searchStore(\n library: string,\n version: string | null | undefined,\n query: string,\n limit = 5,\n ): Promise<StoreSearchResult[]> {\n const normalizedVersion = normalizeVersionLabel(version);\n return this.documentRetriever.search(library, normalizedVersion, query, limit);\n }\n\n /**\n * Reads consecutive chunks of a stored page, assembled for the page's content type.\n *\n * The page is identified by its URL, the URL its content was fetched from, or a\n * path matching the end of exactly one page URL. Only whole chunks are returned,\n * so the content never ends inside a code block; `nextChunk` tells the caller\n * where to continue.\n *\n * @param library Library name.\n * @param version Version or version range, resolved like `findBestVersion`.\n * @param pathOrUrl Page URL or path.\n * @param options `startChunk` to continue reading, `maxChars` to bound the size.\n * @returns The assembled window and its position within the page.\n * @throws PageNotFoundInStoreError when no page matches, with similar pages as suggestions.\n * @throws AmbiguousPageInStoreError when a path matches more than one page.\n */\n async getPageContent(\n library: string,\n version: string | null | undefined,\n pathOrUrl: string,\n options: PageContentOptions = {},\n ): Promise<PageContentResult> {\n const resolved = await this.resolvePageVersion(library, version);\n const url = await this.findPageUrl(resolved.library, resolved.version, pathOrUrl);\n const chunks = await this.store.findChunksByUrl(library, resolved.version, url);\n const contentType = chunks[0]?.content_type ?? null;\n const strategy = createContentAssemblyStrategy(contentType, this.appConfig);\n\n const startChunk = options.startChunk ?? 0;\n const maxChars = options.maxChars ?? Number.POSITIVE_INFINITY;\n const window: DbPageChunk[] = [];\n for (const chunk of chunks.slice(startChunk)) {\n // The first chunk is always included so every call makes progress.\n if (\n window.length > 0 &&\n strategy.assembleContent([...window, chunk]).length > maxChars\n ) {\n break;\n }\n window.push(chunk);\n }\n const end = startChunk + window.length;\n\n return {\n url,\n title: chunks[0]?.title ?? null,\n contentType,\n content: strategy.assembleContent(window),\n startChunk,\n totalChunks: chunks.length,\n nextChunk: end < chunks.length ? end : null,\n };\n }\n\n /**\n * Lists the stored pages of a library version.\n *\n * @param library Library name.\n * @param version Version or version range, resolved like `findBestVersion`.\n * @param options `contains` filters URLs; `limit` (default 50) and `offset` paginate.\n * @returns One page of results and whether more follow.\n */\n async listPages(\n library: string,\n version: string | null | undefined,\n options: ListPagesOptions = {},\n ): Promise<ListPagesResult> {\n const resolved = await this.resolvePageVersion(library, version);\n const limit = options.limit ?? 50;\n const offset = options.offset ?? 0;\n const { total, pages } = await this.store.listPages(library, resolved.version, {\n contains: options.contains,\n limit,\n offset,\n });\n return {\n library: resolved.library,\n version: resolved.version,\n total,\n pages,\n limit,\n offset,\n hasMore: offset + pages.length < total,\n };\n }\n\n /**\n * Validates the library and resolves the version label whose pages to read.\n * @returns The library's stored display name and the resolved version label.\n * @throws {LibraryNotFoundInStoreError} When the library does not exist (with suggestions).\n */\n private async resolvePageVersion(\n library: string,\n version: string | null | undefined,\n ): Promise<{ library: string; version: string }> {\n const { displayName } = await this.requireLibrary(library);\n const { bestMatch } = await this.findBestVersion(library, version ?? undefined);\n return { library: displayName, version: bestMatch ?? \"\" };\n }\n\n /**\n * Resolves a page URL or path to the URL of exactly one stored page.\n * `library` is the stored display name, which the not-found and ambiguous\n * errors repeat.\n *\n * An absolute URL must equal a stored URL; a path must match the end of one.\n * Each is tried as given, spelled the way the scraper stores URLs, and decoded,\n * and then again without its fragment and query.\n */\n private async findPageUrl(\n library: string,\n version: string,\n pathOrUrl: string,\n ): Promise<string> {\n const isAbsolute = /^[a-z][a-z\\d+.-]*:\\/\\//i.test(pathOrUrl);\n const withoutAnchor = pathOrUrl.replace(/[?#].*$/, \"\");\n\n for (const input of new Set([pathOrUrl, withoutAnchor])) {\n if (isAbsolute) {\n const [url] = await this.store.findPageUrls(\n library,\n version,\n spellingsOf(input, (value) => normalizeUrl(value, { removeHash: false })),\n );\n if (url) return url;\n continue;\n }\n\n const suffix = toPathSuffix(input);\n if (!suffix) continue;\n const urls = await this.store.findPageUrlsBySuffix(\n library,\n version,\n spellingsOf(suffix, encodePath),\n MAX_AMBIGUOUS_PAGE_MATCHES,\n );\n if (urls.length === 1) return urls[0];\n if (urls.length > 1) {\n throw new AmbiguousPageInStoreError(library, version, pathOrUrl, urls);\n }\n }\n\n throw new PageNotFoundInStoreError(\n library,\n version,\n pathOrUrl,\n await this.suggestPages(library, version, withoutAnchor),\n );\n }\n\n /**\n * Suggests up to three pages for input that matched none: pages whose URL\n * contains its last path segment, or else the top-level pages.\n */\n private async suggestPages(\n library: string,\n version: string,\n input: string,\n ): Promise<string[]> {\n const keyword = input.split(\"/\").filter(Boolean).pop() ?? \"\";\n if (keyword.length >= 2) {\n const { pages } = await this.store.listPages(library, version, {\n contains: keyword,\n limit: 3,\n });\n if (pages.length > 0) return pages.map((page) => page.url);\n }\n const { pages } = await this.store.listPages(library, version, { limit: 3 });\n return pages.map((page) => page.url);\n }\n\n // Deprecated simple listing removed: enriched listLibraries() is canonical\n\n /**\n * Ensures a library and version exist in the database and returns the version ID.\n * Creates the library and version records if they don't exist.\n */\n async ensureLibraryAndVersion(library: string, version: string): Promise<number> {\n // Same resolution as addDocuments, which creates the library and version if\n // they don't exist. Both halves go through as submitted: the store computes\n // the lookup key, normalizes the version, and keeps a new library's display name.\n return this.store.resolveVersionId(library, version);\n }\n\n /**\n * Retrieves a version by its ID from the database.\n */\n async getVersionById(versionId: number) {\n return this.store.getVersionById(versionId);\n }\n\n /**\n * Retrieves a library by its ID from the database.\n */\n async getLibraryById(libraryId: number) {\n return this.store.getLibraryById(libraryId);\n }\n\n /**\n * Lists stored chunks for a library version with pagination and an optional\n * content filter. Powers the admin dashboard's chunk explorer.\n * @param ref Library/version reference; normalized before querying the store.\n * @param options Pagination (`limit`, defaults to 50; `offset`) and optional content `filter`.\n */\n async listVersionChunks(\n ref: VersionRef,\n options: Partial<ListVersionChunksOptions> = {},\n ): Promise<ListVersionChunksResult> {\n const normalized = normalizeVersionRef(ref);\n return this.store.listVersionChunks(normalized.library, normalized.version, {\n limit: options.limit ?? 50,\n offset: options.offset,\n filter: options.filter,\n });\n }\n\n /**\n * Computes aggregate chunk/page/embedding statistics for a library version,\n * for the chunk explorer's header strip.\n * @param ref Library/version reference; normalized before querying the store.\n */\n async getVersionStats(ref: VersionRef): Promise<VersionChunkStats> {\n const normalized = normalizeVersionRef(ref);\n return this.store.getVersionStats(normalized.library, normalized.version);\n }\n\n /**\n * Returns per-day indexing activity across the whole store over a trailing\n * window, derived from stored page/chunk creation timestamps. Powers the\n * Overview \"Indexing activity\" chart.\n * @param days Window length in days; defaults to 90, clamped to 1..366.\n */\n async getActivityHistory(days = 90): Promise<ActivityHistory> {\n return this.store.getActivityHistory(days);\n }\n\n /**\n * Computes a per-version content-type breakdown (pages grouped by MIME type)\n * for the library-detail Content types panel.\n * @param ref Library/version reference; normalized before querying the store.\n */\n async getVersionComposition(ref: VersionRef): Promise<VersionComposition> {\n const normalized = normalizeVersionRef(ref);\n return this.store.getVersionComposition(normalized.library, normalized.version);\n }\n}\n","/**\n * Client for the merged application API (`AppRouter`) served at `/api`.\n *\n * The web UI and every Node process that talks to a remote worker build their\n * client from the same links, so URL handling, the transformer and the\n * WebSocket used for `events.subscribe` live in one place. The module runs in\n * the browser too: it imports only `@trpc/client`, `superjson` and the router\n * type (enforced by a Biome rule in `biome.json`).\n */\n\nimport {\n createTRPCClient,\n createWSClient,\n httpBatchLink,\n splitLink,\n type TRPCClient,\n type TRPCLink,\n wsLink,\n} from \"@trpc/client\";\nimport superjson from \"superjson\";\nimport type { AppRouter } from \"./appRouter\";\n\n/** Typed client for every procedure of the merged application API. */\nexport type ApiClient = TRPCClient<AppRouter>;\n\n/** Links for the application API and a way to close their WebSocket. */\nexport interface ApiLinks {\n links: TRPCLink<AppRouter>[];\n /** Closes the WebSocket, if the links opened one. */\n close(): void;\n}\n\n/**\n * The WebSocket URL for an HTTP(S) endpoint: the same URL, path and query\n * included, with `http:`/`https:` replaced by `ws:`/`wss:`. Keeping the path\n * lets the connection pass a reverse proxy that serves the endpoint under a\n * prefix, such as `https://example.com/docs/api`.\n *\n * @param httpUrl An absolute `http:` or `https:` URL\n * @returns The matching `ws:` or `wss:` URL\n */\nexport function toWebSocketUrl(httpUrl: string): string {\n const url = new URL(httpUrl);\n url.protocol = url.protocol === \"https:\" ? \"wss:\" : \"ws:\";\n return url.href;\n}\n\n/**\n * Builds the links for the application API at `apiUrl`. Queries and\n * mutations go over a batching HTTP link. With `subscriptions`, a WebSocket\n * with keep-alive carries subscriptions, so a half-open connection is noticed;\n * without, no WebSocket is opened.\n *\n * @param apiUrl The API's URL, e.g. `http://localhost:8080/api`.\n * @param options.subscriptions Whether the client will subscribe to events.\n * @returns The links and a function that closes their WebSocket.\n */\nexport function createApiLinks(\n apiUrl: string,\n options: { subscriptions: boolean },\n): ApiLinks {\n const url = apiUrl.replace(/\\/$/, \"\");\n const httpLink = httpBatchLink({ url, transformer: superjson });\n if (!options.subscriptions) {\n return { links: [httpLink], close: () => {} };\n }\n\n const wsClient = createWSClient({\n url: toWebSocketUrl(url),\n keepAlive: { enabled: true },\n });\n return {\n links: [\n splitLink({\n condition: (op) => op.type === \"subscription\",\n true: wsLink({ client: wsClient, transformer: superjson }),\n false: httpLink,\n }),\n ],\n close: () => wsClient.close(),\n };\n}\n\n/**\n * Creates a typed client for the application API at `apiUrl`.\n *\n * @param apiUrl The API's URL, e.g. `http://localhost:8080/api`.\n * @param options.subscriptions Whether the client will subscribe to events.\n * @returns The client and a function that closes its WebSocket.\n */\nexport function createApiClient(\n apiUrl: string,\n options: { subscriptions: boolean },\n): { api: ApiClient; close(): void } {\n const { links, close } = createApiLinks(apiUrl, options);\n return { api: createTRPCClient<AppRouter>({ links }), close };\n}\n\n/**\n * Checks that the application API at `apiUrl` answers.\n *\n * @param api A client for the API.\n * @param apiUrl The URL the client was created for, named in the error.\n * @throws Error with a hint about the expected URL when the API does not answer.\n */\nexport async function pingApi(api: ApiClient, apiUrl: string): Promise<void> {\n try {\n await api.ping.query();\n } catch {\n throw new Error(\n `Failed to connect to server at ${apiUrl.replace(/\\/$/, \"\")}.\\n\\nPlease verify the server URL includes the correct port (default 8080) and ends with '/api' (e.g., 'http://localhost:8080/api').`,\n );\n }\n}\n","/**\n * The services an entry point runs on: document management, an optional\n * pipeline and the event bus, either in this process or on a remote worker.\n *\n * Every CLI command and server opens its services here, so local and remote\n * runs get the same guarantees: a remote backend relays the worker's events to\n * the local bus, and the backend owns starting and stopping what it created.\n */\n\nimport type { EventBusService } from \"../events\";\nimport { RemoteEventProxy } from \"../events/RemoteEventProxy\";\nimport { EVENTS_CONNECT_TIMEOUT_MS, PipelineClient } from \"../pipeline/PipelineClient\";\nimport { PipelineManager } from \"../pipeline/PipelineManager\";\nimport type { IPipeline } from \"../pipeline/trpc/interfaces\";\nimport type { InterruptedJobs } from \"../pipeline/types\";\nimport { DocumentManagementClient } from \"../store/DocumentManagementClient\";\nimport { DocumentManagementService } from \"../store/DocumentManagementService\";\nimport { EmbeddingModelChangedError } from \"../store/errors\";\nimport type { IDocumentManagement } from \"../store/trpc/interfaces\";\nimport { TelemetryService } from \"../telemetry/TelemetryService\";\nimport type { AppConfig } from \"../utils/config\";\nimport { logger } from \"../utils/logger\";\nimport { createApiClient, pingApi } from \"./apiClient\";\n\n/**\n * How much of the pipeline a caller needs:\n * - `false`: documents only; no pipeline, and no WebSocket to a worker. A local\n * backend starts no pipeline, so it never interrupts jobs that another\n * process runs on the same store.\n * - `{ interruptedJobs }`: run jobs. Locally a started pipeline that handles\n * the jobs an earlier run left unfinished as asked (see {@link InterruptedJobs});\n * remotely the worker's pipeline (the worker handles its own, so\n * `interruptedJobs` does not apply).\n */\nexport type BackendJobs = false | { interruptedJobs: InterruptedJobs };\n\n/** Options for {@link openBackend}. */\nexport interface OpenBackendOptions {\n appConfig: AppConfig;\n eventBus: EventBusService;\n /** The remote worker's API URL; the backend is local without it. */\n serverUrl?: string;\n /** How much of the pipeline is needed. Defaults to `false`. */\n jobs?: BackendJobs;\n /**\n * Handles a changed embedding model when the local store opens. Without it,\n * the error propagates.\n */\n onEmbeddingModelChange?: (\n error: EmbeddingModelChangedError,\n service: DocumentManagementService,\n ) => Promise<void>;\n}\n\n/** Services opened by {@link openBackend}. */\nexport interface Backend {\n /** The worker's API URL for a remote backend; undefined for a local one. */\n readonly workerUrl: string | undefined;\n readonly docService: IDocumentManagement;\n /** The pipeline, when `jobs` asked for one that this backend can provide. */\n readonly pipeline: IPipeline | undefined;\n readonly eventBus: EventBusService;\n /** Whether the worker's events reach the bus; only for a remote backend with a pipeline. */\n readonly isWorkerConnected: (() => boolean) | undefined;\n /**\n * Stops everything the backend started, in reverse order. Runs every step\n * even when one fails, logs each failure, and rejects with the first. Later\n * calls return the first call's result.\n */\n close(): Promise<void>;\n}\n\n/** A backend that runs jobs, as servers need it. */\nexport interface JobsBackend extends Backend {\n readonly pipeline: IPipeline;\n}\n\n/**\n * Opens the services for an entry point, local or on the worker at\n * `serverUrl`. A remote backend that has a pipeline starts relaying the\n * worker's events in the background; job submission waits briefly for it.\n *\n * @throws Error when the worker does not answer, or the local store fails to\n * open. Whatever was opened before the failure is closed first.\n */\nexport function openBackend(\n options: OpenBackendOptions & { jobs: { interruptedJobs: InterruptedJobs } },\n): Promise<JobsBackend>;\nexport function openBackend(options: OpenBackendOptions): Promise<Backend>;\nexport async function openBackend(options: OpenBackendOptions): Promise<Backend> {\n const closer = new Closer();\n try {\n return options.serverUrl\n ? await openRemote(options, options.serverUrl, closer)\n : await openLocal(options, closer);\n } catch (error) {\n await closer.close().catch(() => {});\n throw error;\n }\n}\n\nasync function openLocal(options: OpenBackendOptions, closer: Closer): Promise<Backend> {\n const { appConfig, eventBus, jobs = false } = options;\n if (!appConfig.app.storePath) {\n throw new Error(\"storePath is required when not using a remote server\");\n }\n\n const docService = new DocumentManagementService(eventBus, appConfig);\n closer.add(() => docService.shutdown());\n try {\n await docService.initialize();\n } catch (error) {\n if (\n !(error instanceof EmbeddingModelChangedError) ||\n !options.onEmbeddingModelChange\n ) {\n throw error;\n }\n await options.onEmbeddingModelChange(error, docService);\n }\n\n let pipeline: IPipeline | undefined;\n if (jobs) {\n // Reports the jobs this process runs, from the first one recovered on start\n const jobTelemetry = new TelemetryService(eventBus);\n closer.add(() => jobTelemetry.shutdown());\n const manager = new PipelineManager(docService, eventBus, {\n interruptedJobs: jobs.interruptedJobs,\n appConfig,\n });\n await manager.start();\n closer.add(() => manager.stop());\n pipeline = manager;\n }\n\n return {\n workerUrl: undefined,\n docService,\n pipeline,\n eventBus,\n isWorkerConnected: undefined,\n close: () => closer.close(),\n };\n}\n\nasync function openRemote(\n options: OpenBackendOptions,\n workerUrl: string,\n closer: Closer,\n): Promise<Backend> {\n const { eventBus, jobs = false } = options;\n const withPipeline = jobs !== false;\n\n const { api, close } = createApiClient(workerUrl, { subscriptions: withPipeline });\n closer.add(close);\n await pingApi(api, workerUrl);\n const docService = new DocumentManagementClient(api);\n\n let pipeline: IPipeline | undefined;\n let isWorkerConnected: (() => boolean) | undefined;\n if (withPipeline) {\n const relay = new RemoteEventProxy(api, eventBus);\n closer.add(() => relay.disconnect());\n pipeline = new PipelineClient(api, eventBus, relay);\n isWorkerConnected = () => relay.isActive();\n // Connect in the background; submitting a job waits for this attempt.\n void relay.connect(EVENTS_CONNECT_TIMEOUT_MS);\n }\n\n return {\n workerUrl,\n docService,\n pipeline,\n eventBus,\n isWorkerConnected,\n close: () => closer.close(),\n };\n}\n\n/** Collects close steps and runs them once, in reverse order. */\nclass Closer {\n private readonly steps: Array<() => void | Promise<void>> = [];\n private closing: Promise<void> | undefined;\n\n add(step: () => void | Promise<void>): void {\n this.steps.push(step);\n }\n\n close(): Promise<void> {\n this.closing ??= this.runSteps();\n return this.closing;\n }\n\n private async runSteps(): Promise<void> {\n let firstError: unknown;\n for (const step of [...this.steps].reverse()) {\n try {\n await step();\n } catch (error) {\n logger.error(`❌ Failed to close a backend service: ${error}`);\n firstError ??= error;\n }\n }\n if (firstError !== undefined) {\n throw firstError;\n }\n }\n}\n","import { encode as encodeToToon } from \"@toon-format/toon\";\nimport yaml from \"yaml\";\nimport type { Argv } from \"yargs\";\nimport { getLogLevelFromEnv, LogLevel, logger, setLogLevel } from \"../utils/logger\";\n\nexport type OutputFormat = \"json\" | \"yaml\" | \"toon\";\n\nexport interface HasOutputOption {\n [key: string]: unknown;\n output?: unknown;\n}\n\ntype PrimitiveValue = boolean | null | number | string;\n\nexport function isInteractiveOutput(): boolean {\n return !!process.stdout.isTTY && !!process.stderr.isTTY;\n}\n\nexport function resolveOutputFormat(argv: HasOutputOption): OutputFormat {\n const requestedFormat = argv.output as OutputFormat | undefined;\n if (requestedFormat) {\n return requestedFormat;\n }\n\n return \"json\";\n}\n\nexport function formatStructuredOutput(value: unknown, format: OutputFormat): string {\n if (format === \"yaml\") {\n return yaml.stringify(value).trimEnd();\n }\n\n if (format === \"toon\") {\n return encodeToToon(value).trimEnd();\n }\n\n return JSON.stringify(value, null, 2);\n}\n\nexport function renderStructuredOutput(value: unknown, argv: HasOutputOption): void {\n const format = resolveOutputFormat(argv);\n process.stdout.write(`${formatStructuredOutput(value, format)}\\n`);\n}\n\nexport function renderTextOutput(value: string): void {\n process.stdout.write(value.endsWith(\"\\n\") ? value : `${value}\\n`);\n}\n\nexport function renderScalarOutput(value: PrimitiveValue, argv: HasOutputOption): void {\n const hasExplicitFormat = typeof argv.output === \"string\";\n if (!hasExplicitFormat) {\n renderTextOutput(String(value));\n return;\n }\n\n renderStructuredOutput(value, argv);\n}\n\nexport function applyGlobalCliOutputMode(options: {\n verbose?: boolean;\n quiet?: boolean;\n}): void {\n const interactive = isInteractiveOutput();\n const envLogLevel = getLogLevelFromEnv();\n\n if (options.verbose) {\n setLogLevel(LogLevel.DEBUG);\n } else if (options.quiet) {\n setLogLevel(LogLevel.ERROR);\n } else if (envLogLevel !== null && envLogLevel !== undefined) {\n setLogLevel(envLogLevel);\n } else if (interactive) {\n setLogLevel(LogLevel.INFO);\n } else {\n setLogLevel(LogLevel.ERROR);\n }\n}\n\nexport function registerGlobalOutputOptions<T>(yargs: Argv<T>): Argv<T> {\n return yargs.option(\"output\", {\n type: \"string\",\n choices: [\"json\", \"yaml\", \"toon\"],\n description: \"Structured output format for commands that return data\",\n });\n}\n\nexport function reportCliError(message: string): void {\n logger.error(message);\n}\n\nexport function reportCliWarning(message: string): void {\n logger.warn(message);\n}\n\nexport function reportCliInfo(message: string): void {\n logger.info(message);\n}\n","/**\n * Shared CLI utilities and helper functions.\n */\n\nimport { execFileSync } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport type { AppServerConfig } from \"../app\";\nimport type { AuthConfig } from \"../auth/types\";\nimport type { EventBusService } from \"../events\";\nimport { ManagedBrowser } from \"../scraper/fetcher/ManagedBrowser\";\nimport type { DocumentManagementService } from \"../store/DocumentManagementService\";\nimport {\n EmbeddingConfig,\n type EmbeddingModelConfig,\n} from \"../store/embeddings/EmbeddingConfig\";\nimport { describeEmbeddingModel, type EmbeddingModelChangedError } from \"../store/errors\";\nimport { parseEnvBoolean } from \"../utils/config\";\nimport { logger } from \"../utils/logger\";\nimport type { GlobalOptions } from \"./types\";\n\n/**\n * Context extended with EventBusService, injected via middleware.\n */\nexport interface CliContext {\n _eventBus?: EventBusService;\n [key: string]: unknown;\n}\n\n/**\n * Retrieves the global EventBusService from the arguments context.\n * @param argv The parsed arguments context.\n * @returns The global EventBusService.\n * @throws Error if EventBusService is not initialized.\n */\nexport function getEventBus(argv: CliContext): EventBusService {\n const eventBus = argv._eventBus;\n if (!eventBus) {\n throw new Error(\"EventBusService not initialized\");\n }\n return eventBus;\n}\n\n/**\n * Helper to extract GlobalOptions from the argv.\n * In Yargs, all options are in argv, so we just cast/pick.\n */\nexport function getGlobalOptions(argv: Record<string, unknown>): GlobalOptions {\n return argv as unknown as GlobalOptions;\n}\n\n/**\n * Embedding context.\n * Simplified subset of EmbeddingModelConfig for telemetry purposes.\n */\nexport interface EmbeddingContext {\n aiEmbeddingProvider: string;\n aiEmbeddingModel: string;\n aiEmbeddingDimensions: number | null;\n}\n\n/**\n * Ensures a Chromium for scraping is installed, unless a system Chromium path\n * is set.\n *\n * Any Chromium `ManagedBrowser` launches without an explicit path counts: the\n * headless shell or the full build. When neither is there, the headless shell\n * is installed with the CLI of the Playwright this package depends on, so it\n * matches that version. The install leaves other browsers alone, since another\n * process may be running them.\n */\nexport function ensurePlaywrightBrowsersInstalled(): void {\n if (process.env.PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD === \"1\") {\n logger.debug(\n \"PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD is set, skipping Playwright browser install.\",\n );\n return;\n }\n\n // If PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH is set, skip install\n const chromiumEnvPath = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH;\n if (chromiumEnvPath && existsSync(chromiumEnvPath)) {\n logger.debug(\n `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH is set to '${chromiumEnvPath}', skipping Playwright browser install.`,\n );\n return;\n }\n\n if (ManagedBrowser.isPlaywrightChromiumInstalled()) {\n return;\n }\n\n // `playwright/cli.js` is not an exported path, but its package.json is.\n const playwrightCli = path.join(\n path.dirname(createRequire(import.meta.url).resolve(\"playwright/package.json\")),\n \"cli.js\",\n );\n try {\n logger.info(\"🌐 Installing Playwright Chromium browser... (this may take a moment)\");\n execFileSync(\n process.execPath,\n [playwrightCli, \"install\", \"chromium-headless-shell\", \"--no-remove\"],\n { stdio: \"ignore\" },\n );\n } catch (error) {\n logger.debug(String(error));\n logger.error(\n `❌ Failed to install Playwright browsers automatically. Please run:\\n node \"${playwrightCli}\" install --with-deps chromium-headless-shell\\nand try again.`,\n );\n process.exit(1);\n }\n}\n\n/**\n * Resolves the protocol based on auto-detection or explicit specification.\n * Auto-detection uses TTY status to determine appropriate protocol.\n */\nexport function resolveProtocol(protocol: string): \"stdio\" | \"http\" {\n if (protocol === \"auto\") {\n // VS Code and CI/CD typically run without TTY\n if (!process.stdin.isTTY && !process.stdout.isTTY) {\n return \"stdio\";\n }\n return \"http\";\n }\n\n // Explicit protocol specification\n if (protocol === \"stdio\" || protocol === \"http\") {\n return protocol;\n }\n\n throw new Error(`Invalid protocol: ${protocol}. Must be 'auto', 'stdio', or 'http'`);\n}\n\n/**\n * Validates and parses port number\n */\nexport function validatePort(portString: string): number {\n const port = Number.parseInt(portString, 10);\n if (Number.isNaN(port) || port < 1 || port > 65535) {\n throw new Error(\"Invalid port number\");\n }\n return port;\n}\n\n/**\n * Validates host string for basic format checking\n */\nexport function validateHost(hostString: string): string {\n // Basic validation - allow IPv4, IPv6, and hostnames\n const trimmed = hostString.trim();\n if (!trimmed) {\n throw new Error(\"Host cannot be empty\");\n }\n\n // Very basic format check - reject obviously invalid values\n if (trimmed.includes(\" \") || trimmed.includes(\"\\t\") || trimmed.includes(\"\\n\")) {\n throw new Error(\"Host cannot contain whitespace\");\n }\n\n return trimmed;\n}\n\n/**\n * Creates AppServerConfig based on service requirements.\n *\n * AppConfig is the source of truth for host/auth/telemetry/read-only settings.\n * AppServerConfig only selects which services to run and which port to bind to.\n * Whether the server runs jobs itself or uses a worker follows from the backend.\n *\n * @param options Which services to run, the port, and startup details.\n * @returns The server configuration.\n */\nexport function createAppServerConfig(options: {\n enableWebInterface?: boolean;\n enableMcpServer?: boolean;\n enableApiServer?: boolean;\n port: number;\n showLogo?: boolean;\n startupContext?: {\n cliCommand?: string;\n mcpProtocol?: \"stdio\" | \"http\";\n mcpTransport?: \"sse\" | \"streamable\";\n };\n}): AppServerConfig {\n return {\n enableWebInterface: options.enableWebInterface ?? false,\n enableMcpServer: options.enableMcpServer ?? true,\n enableApiServer: options.enableApiServer ?? false,\n port: options.port,\n showLogo: options.showLogo ?? true,\n startupContext: options.startupContext,\n };\n}\n\n/**\n * Parses custom headers from CLI options\n */\nexport function parseHeaders(headerOptions: string[]): Record<string, string> {\n const headers: Record<string, string> = {};\n\n if (Array.isArray(headerOptions)) {\n for (const entry of headerOptions) {\n const idx = entry.indexOf(\":\");\n if (idx > 0) {\n const name = entry.slice(0, idx).trim();\n const value = entry.slice(idx + 1).trim();\n if (name) headers[name] = value;\n }\n }\n }\n\n return headers;\n}\n\n/**\n * Check the auth settings for the transport a command serves. Authentication\n * applies to MCP over HTTP only. Over stdio the host launching the process is\n * the trust boundary, so auth settings are ignored with a warning on stderr,\n * which never carries protocol data.\n * @param auth - The loaded auth settings.\n * @param protocol - The resolved transport.\n * @param port - The HTTP port, for the plain-HTTP warning.\n * @throws Error when an auth setting over HTTP is malformed.\n */\nexport function checkAuthForProtocol(\n auth: AuthConfig,\n protocol: \"stdio\" | \"http\",\n port: number,\n): void {\n if (!auth.enabled) {\n return;\n }\n if (protocol === \"stdio\") {\n console.error(\n \"⚠️ Authentication does not apply to MCP over stdio; auth settings are ignored.\",\n );\n return;\n }\n validateAuthConfig(auth);\n warnHttpUsage(port);\n}\n\n/**\n * Validates the format of auth settings that are present. Whether a setting\n * is required depends on what the process serves, so the server checks that\n * at startup.\n */\nfunction validateAuthConfig(authConfig: AuthConfig): void {\n const errors: string[] = [];\n\n if (authConfig.issuerUrl) {\n try {\n const url = new URL(authConfig.issuerUrl);\n if (url.protocol !== \"https:\") {\n errors.push(\"Issuer URL must use HTTPS protocol\");\n }\n } catch {\n errors.push(\"Issuer URL must be a valid URL\");\n }\n }\n\n // Audience is optional: it defaults to the MCP endpoint's public URL.\n if (authConfig.audience) {\n // Audience can be any valid URI (URL or URN)\n // Examples: https://api.example.com, urn:docs-mcp-server:api, urn:company:service\n try {\n // Try parsing as URL first (most common case)\n const url = new URL(authConfig.audience);\n if (url.protocol === \"http:\" && url.hostname !== \"localhost\") {\n // Warn about HTTP in production but don't fail\n logger.warn(\n \"⚠️ Audience uses HTTP protocol - consider using HTTPS for production\",\n );\n }\n if (url.hash) {\n errors.push(\"Audience must not contain URL fragments\");\n }\n } catch {\n // If not a valid URL, check if it's a valid URN\n if (authConfig.audience.startsWith(\"urn:\")) {\n // Basic URN validation: urn:namespace:specific-string\n const urnParts = authConfig.audience.split(\":\");\n if (urnParts.length < 3 || !urnParts[1] || !urnParts[2]) {\n errors.push(\"URN audience must follow format: urn:namespace:specific-string\");\n }\n } else {\n errors.push(\n \"Audience must be a valid absolute URL or URN (e.g., https://api.example.com or urn:company:service)\",\n );\n }\n }\n }\n\n if (errors.length > 0) {\n throw new Error(`Auth configuration validation failed:\\n${errors.join(\"\\n\")}`);\n }\n}\n\n/**\n * Warns about HTTP usage in production when auth is enabled.\n */\nfunction warnHttpUsage(port: number): void {\n // Check if we're likely running in production (not localhost)\n const isLocalhost =\n process.env.NODE_ENV !== \"production\" ||\n port === 6280 || // default dev port\n process.env.HOSTNAME?.includes(\"localhost\");\n\n if (!isLocalhost) {\n logger.warn(\n \"⚠️ Authentication is enabled but running over HTTP in production. \" +\n \"Consider using HTTPS for security.\",\n );\n }\n}\n\n/**\n * Resolves embedding configuration from the provided model specification.\n * This function centralizes the logic for determining the embedding model.\n *\n * @param embeddingModel The embedding model specification string.\n * @returns Embedding configuration or null if config is unavailable.\n */\nexport function resolveEmbeddingContext(\n embeddingModel?: string,\n): EmbeddingModelConfig | null {\n try {\n const modelSpec = embeddingModel;\n\n if (!modelSpec) {\n logger.debug(\"No embedding model specified. Embeddings are disabled.\");\n return null;\n }\n\n logger.debug(`Resolving embedding configuration for model: ${modelSpec}`);\n return EmbeddingConfig.parseEmbeddingConfig(modelSpec);\n } catch (error) {\n logger.debug(`Failed to resolve embedding configuration: ${error}`);\n return null;\n }\n}\n\n/**\n * Prompts the user interactively to confirm an embedding model change.\n * Returns true if the user confirms (y/Y), false otherwise.\n */\nfunction promptModelChangeConfirmation(\n change: EmbeddingModelChangedError,\n): Promise<boolean> {\n return new Promise((resolve) => {\n console.error(\n `\\n⚠️ Embedding model change detected:\\n` +\n ` Previous: ${describeEmbeddingModel(change.previousModel, change.previousDimension)}\\n` +\n ` Current: ${describeEmbeddingModel(change.currentModel, change.currentDimension)}\\n\\n` +\n ` All existing embedding vectors will be invalidated.\\n` +\n ` Libraries must be re-scraped to restore vector search.\\n` +\n ` Full-text search will continue working for all existing documents.\\n`,\n );\n\n const rl = createInterface({\n input: process.stdin,\n output: process.stderr,\n });\n\n rl.question(\" Proceed with model change? (y/N) \", (answer) => {\n rl.close();\n const confirmed = answer.trim().toLowerCase() === \"y\";\n resolve(confirmed);\n });\n });\n}\n\n/**\n * Handles EmbeddingModelChangedError during service initialization.\n *\n * - When accepted (`--accept-model-change` or `DOCS_MCP_ACCEPT_MODEL_CHANGE`):\n * resolves the model change (invalidates vectors) without asking.\n * - In non-interactive mode (no TTY): re-throws the error to fail startup.\n * - In interactive mode (TTY): prompts the user for confirmation, then either\n * resolves the model change or exits.\n *\n * @param error The EmbeddingModelChangedError thrown by DocumentStore.initialize()\n * @param service The DocumentManagementService instance (already partially initialized)\n * @param acceptFlag The value of `--accept-model-change`; when omitted,\n * `DOCS_MCP_ACCEPT_MODEL_CHANGE` decides\n * @throws Re-throws the error in non-interactive mode or if the user rejects the change\n */\nexport async function handleEmbeddingModelChange(\n error: EmbeddingModelChangedError,\n service: Pick<DocumentManagementService, \"resolveModelChange\">,\n acceptFlag?: boolean,\n): Promise<void> {\n const accepted =\n acceptFlag ?? parseEnvBoolean(process.env.DOCS_MCP_ACCEPT_MODEL_CHANGE) ?? false;\n if (accepted) {\n logger.warn(\n `⚠️ Accepting embedding model change without a prompt: ` +\n `${describeEmbeddingModel(error.previousModel, error.previousDimension)} → ` +\n `${describeEmbeddingModel(error.currentModel, error.currentDimension)}`,\n );\n await service.resolveModelChange();\n return;\n }\n\n // Non-interactive: fail startup entirely\n if (!process.stdin.isTTY || !process.stdout.isTTY) {\n throw error;\n }\n\n // Interactive: prompt user for confirmation\n const confirmed = await promptModelChangeConfirmation(error);\n\n if (!confirmed) {\n throw new Error(\n \"Embedding model change rejected. Startup aborted.\\n\" +\n \"Restore the previous embedding model configuration to continue without changes.\",\n );\n }\n\n // User confirmed: invalidate vectors and complete initialization\n await service.resolveModelChange();\n}\n","/**\n * Compact command - Reclaims unused SQLite pages and truncates the WAL file.\n */\n\nimport type { Argv } from \"yargs\";\nimport { openBackend } from \"../../services/backend\";\nimport { TelemetryEvent, telemetry } from \"../../telemetry\";\nimport { loadConfig } from \"../../utils/config\";\nimport { logger } from \"../../utils/logger\";\nimport { formatBytes } from \"../../utils/string\";\nimport { renderTextOutput } from \"../output\";\nimport { type CliContext, getEventBus } from \"../utils\";\n\nexport function createCompactCommand(cli: Argv) {\n cli.command(\n \"compact\",\n \"Reclaim unused space in the document store (exclusive lock; may block searches)\",\n (yargs) => {\n return yargs\n .option(\"force\", {\n type: \"boolean\",\n description: \"Run VACUUM even when SQLite reports no free pages\",\n default: false,\n })\n .option(\"server-url\", {\n type: \"string\",\n description:\n \"URL of external pipeline worker RPC (e.g., http://localhost:8080/api)\",\n alias: \"serverUrl\",\n });\n },\n async (argv) => {\n await telemetry.track(TelemetryEvent.CLI_COMMAND, {\n command: \"compact\",\n useServerUrl: !!argv.serverUrl,\n });\n\n const serverUrl = argv.serverUrl as string | undefined;\n const appConfig = loadConfig(argv, {\n configPath: argv.config as string,\n searchDir: argv.storePath as string,\n });\n\n const eventBus = getEventBus(argv as CliContext);\n\n const backend = await openBackend({\n serverUrl,\n eventBus,\n appConfig,\n });\n const { docService } = backend;\n try {\n const result = await docService.compact({ force: argv.force === true });\n\n if (result.skipped) {\n renderTextOutput(\"Skipped compaction for in-memory store.\");\n } else if (result.reclaimedBytes > 0) {\n renderTextOutput(\n `Compacted store from ${formatBytes(result.beforeBytes)} to ${formatBytes(result.afterBytes)} (reclaimed ${formatBytes(result.reclaimedBytes)}).`,\n );\n } else {\n renderTextOutput(\"Store is already compact.\");\n }\n } catch (error) {\n logger.error(\n `❌ Failed to compact store: ${error instanceof Error ? error.message : String(error)}`,\n );\n throw error;\n } finally {\n await backend.close();\n }\n },\n );\n}\n","import type { Argv } from \"yargs\";\nimport {\n getConfigValue,\n isValidConfigPath,\n loadConfig,\n parseConfigValue,\n setConfigValue,\n} from \"../../utils/config\";\nimport {\n renderScalarOutput,\n renderStructuredOutput,\n renderTextOutput,\n reportCliError,\n} from \"../output\";\n\nfunction validateConfigPath(path: string): boolean {\n return isValidConfigPath(path);\n}\n\nexport function createConfigCommand(cli: Argv) {\n cli.command(\n \"config [action] [path] [value]\",\n \"View or modify configuration\",\n (yargs) =>\n yargs\n .positional(\"action\", {\n type: \"string\",\n })\n .positional(\"path\", {\n type: \"string\",\n })\n .positional(\"value\", {\n type: \"string\",\n }),\n (argv) => {\n const action = argv.action as string | undefined;\n\n if (!action) {\n const config = loadConfig(argv, {\n configPath: argv.config as string,\n searchDir: argv.storePath as string,\n });\n renderStructuredOutput(config, argv);\n return;\n }\n\n if (action !== \"get\" && action !== \"set\") {\n reportCliError(`Error: Unknown config action '${action}'. Use 'get' or 'set'.`);\n process.exitCode = 1;\n return;\n }\n\n if (action === \"get\") {\n const path = argv.path as string | undefined;\n if (!path || !validateConfigPath(path)) {\n reportCliError(`Error: Invalid config path '${path ?? \"\"}'`);\n reportCliError(\"Use 'docs-mcp-server config' to see all available paths.\");\n process.exitCode = 1;\n return;\n }\n\n const config = loadConfig(argv, {\n configPath: argv.config as string,\n searchDir: argv.storePath as string,\n });\n\n const value = getConfigValue(config, path);\n if (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n renderScalarOutput(value, argv);\n return;\n }\n\n renderStructuredOutput(value, argv);\n return;\n }\n\n const path = argv.path as string | undefined;\n const value = argv.value as string | undefined;\n\n if (!path || !value) {\n reportCliError(\"Error: config set requires both <path> and <value>.\");\n process.exitCode = 1;\n return;\n }\n\n if (argv.config) {\n reportCliError(\n \"Error: Cannot modify configuration when using explicit --config file.\",\n );\n reportCliError(\"Remove the --config flag to modify the default configuration.\");\n process.exitCode = 1;\n return;\n }\n\n if (!validateConfigPath(path)) {\n reportCliError(`Error: Invalid config path '${path}'`);\n reportCliError(\"Use 'docs-mcp-server config' to see all available paths.\");\n process.exitCode = 1;\n return;\n }\n\n const config = loadConfig(argv, {\n configPath: argv.config as string,\n searchDir: argv.storePath as string,\n });\n const currentValue = getConfigValue(config, path);\n if (\n currentValue !== undefined &&\n currentValue !== null &&\n typeof currentValue === \"object\" &&\n !Array.isArray(currentValue)\n ) {\n reportCliError(\n `Error: Config path '${path}' refers to an object. Use a more specific leaf path to set a scalar value.`,\n );\n reportCliError(\n \"Hint: Run 'docs-mcp-server config' to inspect the current structure.\",\n );\n process.exitCode = 1;\n return;\n }\n\n try {\n const savedPath = setConfigValue(path, value);\n const parsedValue = parseConfigValue(value);\n renderTextOutput(`Updated ${path} = ${JSON.stringify(parsedValue)}`);\n renderTextOutput(`Saved to: ${savedPath}`);\n } catch (error) {\n reportCliError(\n `Error: Failed to save configuration: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n process.exitCode = 1;\n }\n },\n );\n}\n","/**\n * Verifies OAuth 2.0 access tokens for the MCP endpoint, which acts as a\n * resource server: a token is accepted only when it is a JWT signed with a key\n * the configured issuer publishes, carries that issuer's `iss`, names this\n * server in `aud`, and has not expired. There is no other path to access.\n */\n\nimport {\n type AuthInfo,\n OAuthError,\n OAuthErrorCode,\n type OAuthTokenVerifier,\n} from \"@modelcontextprotocol/server\";\nimport {\n createRemoteJWKSet,\n errors,\n type JWTPayload,\n type JWTVerifyGetKey,\n jwtVerify,\n} from \"jose\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * The description every rejected token gets. The reason stays in the debug\n * log: telling the client which check failed would show an attacker which of\n * their tokens are close to valid.\n */\nexport const INVALID_TOKEN_DESCRIPTION = \"The access token is invalid.\";\n\n/** How long one metadata discovery request may take before the next URL is tried. */\nconst DISCOVERY_TIMEOUT_MS = 10_000;\n\n/**\n * Metadata URLs to try for an issuer, in the order MCP clients use:\n * RFC 8414 with path insertion, OIDC Discovery with path insertion, then OIDC\n * Discovery with the path appended. Issuers without a path get the first two.\n * @param issuerUrl - The configured issuer identifier.\n * @returns Absolute URLs, most preferred first.\n */\nexport function authorizationServerMetadataUrls(issuerUrl: string): string[] {\n const url = new URL(issuerUrl);\n const path = url.pathname.replace(/\\/+$/, \"\");\n if (!path) {\n return [\n `${url.origin}/.well-known/oauth-authorization-server`,\n `${url.origin}/.well-known/openid-configuration`,\n ];\n }\n return [\n `${url.origin}/.well-known/oauth-authorization-server${path}`,\n `${url.origin}/.well-known/openid-configuration${path}`,\n `${url.origin}${path}/.well-known/openid-configuration`,\n ];\n}\n\nasync function fetchMetadata(url: string): Promise<Record<string, unknown> | undefined> {\n try {\n const response = await fetch(url, {\n headers: { accept: \"application/json\" },\n signal: AbortSignal.timeout(DISCOVERY_TIMEOUT_MS),\n });\n if (!response.ok) {\n return undefined;\n }\n const body: unknown = await response.json();\n return body !== null && typeof body === \"object\"\n ? (body as Record<string, unknown>)\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction stringClaim(payload: JWTPayload, name: string): string | undefined {\n const value = payload[name];\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\n/** The issuer's signing keys could not be retrieved; the token itself may be fine. */\nclass KeyRetrievalError extends Error {}\n\n/**\n * Wrap the key lookup so a failure to retrieve the keys is told apart from a\n * token that no published key fits: only the latter is the token's fault.\n */\nfunction withKeyRetrievalErrors(\n getKey: ReturnType<typeof createRemoteJWKSet>,\n): JWTVerifyGetKey {\n return async (header, token) => {\n try {\n return await getKey(header, token);\n } catch (error) {\n if (\n error instanceof errors.JWKSNoMatchingKey ||\n error instanceof errors.JWKSMultipleMatchingKeys\n ) {\n throw error;\n }\n throw new KeyRetrievalError(\n error instanceof Error ? error.message : String(error),\n {\n cause: error,\n },\n );\n }\n };\n}\n\n/** Verifies JWT access tokens against the configured issuer and audience. */\nexport class JwtAccessTokenVerifier implements OAuthTokenVerifier {\n private constructor(\n private readonly issuer: string,\n private readonly audience: string,\n private readonly keys: JWTVerifyGetKey,\n ) {}\n\n /**\n * Discover the issuer's metadata and prepare its key set.\n *\n * @param options.issuerUrl - The configured issuer. It must be identical to the\n * `issuer` the authorization server publishes.\n * @param options.audience - The audience a token must carry.\n * @returns The verifier.\n * @throws Error when no metadata document answers, when its `issuer` differs\n * from `issuerUrl`, or when it has no `jwks_uri`.\n */\n static async create(options: {\n issuerUrl: string;\n audience: string;\n }): Promise<JwtAccessTokenVerifier> {\n const urls = authorizationServerMetadataUrls(options.issuerUrl);\n let metadata: Record<string, unknown> | undefined;\n for (const url of urls) {\n metadata = await fetchMetadata(url);\n if (metadata) {\n break;\n }\n }\n if (!metadata) {\n throw new Error(\n `Could not discover authorization server metadata for auth.issuerUrl \"${options.issuerUrl}\". Tried: ${urls.join(\", \")}`,\n );\n }\n if (metadata.issuer !== options.issuerUrl) {\n throw new Error(\n `auth.issuerUrl \"${options.issuerUrl}\" does not match the issuer the authorization server publishes, \"${String(metadata.issuer)}\". Set auth.issuerUrl to exactly that value.`,\n );\n }\n if (typeof metadata.jwks_uri !== \"string\") {\n throw new Error(\n `The authorization server metadata for \"${options.issuerUrl}\" has no jwks_uri. Only JWT access tokens are supported.`,\n );\n }\n return new JwtAccessTokenVerifier(\n options.issuerUrl,\n options.audience,\n withKeyRetrievalErrors(createRemoteJWKSet(new URL(metadata.jwks_uri))),\n );\n }\n\n /**\n * Verify an access token.\n * @param token - The raw bearer token.\n * @returns What the token grants.\n * @throws OAuthError(InvalidToken) when the token itself is not acceptable;\n * OAuthError(ServerError) when the issuer's keys cannot be retrieved.\n */\n async verifyAccessToken(token: string): Promise<AuthInfo> {\n let payload: JWTPayload;\n try {\n ({ payload } = await jwtVerify(token, this.keys, {\n issuer: this.issuer,\n audience: this.audience,\n requiredClaims: [\"exp\"],\n }));\n } catch (error) {\n if (error instanceof KeyRetrievalError) {\n throw new OAuthError(\n OAuthErrorCode.ServerError,\n \"The issuer's signing keys could not be retrieved.\",\n );\n }\n logger.debug(\n `Access token rejected: ${error instanceof Error ? error.message : String(error)}`,\n );\n throw new OAuthError(OAuthErrorCode.InvalidToken, INVALID_TOKEN_DESCRIPTION);\n }\n\n return {\n token,\n clientId:\n stringClaim(payload, \"client_id\") ??\n stringClaim(payload, \"azp\") ??\n payload.sub ??\n \"unknown\",\n scopes: (stringClaim(payload, \"scope\") ?? \"\").split(\" \").filter(Boolean),\n expiresAt: payload.exp,\n extra: payload.sub ? { subject: payload.sub } : undefined,\n };\n }\n}\n","/**\n * OAuth 2.0 Protected Resource Metadata (RFC 9728) for the MCP endpoint, and\n * the pieces of the discovery challenge that point clients at it.\n *\n * Every value derives from configuration, never from the request's `Host`\n * header: clients bind tokens to the `resource` published here, so a\n * spoofable value would let an attacker steer that binding.\n */\n\nimport { type BaseMetadata, getDisplayName } from \"@modelcontextprotocol/server\";\n\nconst WELL_KNOWN_PREFIX = \"/.well-known/oauth-protected-resource\";\n\n/**\n * Build the protected resource metadata document.\n *\n * The resource is named the way MCP clients name the server: by its title, or\n * by its name when there is no title.\n * @param options.mcpEndpointUrl - Public URL of the MCP endpoint, which is the resource identifier.\n * @param options.issuerUrl - The authorization server's issuer identifier.\n * @param options.server - The server's configured name and optional title.\n * @returns The RFC 9728 document.\n */\nexport function buildProtectedResourceMetadata(options: {\n mcpEndpointUrl: string;\n issuerUrl: string;\n server: BaseMetadata;\n}): Record<string, unknown> {\n return {\n resource: options.mcpEndpointUrl,\n authorization_servers: [options.issuerUrl],\n bearer_methods_supported: [\"header\"],\n resource_name: getDisplayName(options.server),\n resource_documentation: \"https://github.com/arabold/docs-mcp-server#readme\",\n };\n}\n\n/**\n * Server-side paths the document is served at, after any base path has been\n * stripped from the request.\n *\n * The first path is where the discovery challenge points. With a base path,\n * the server also answers the location RFC 9728 derives from the MCP endpoint\n * URL, which sits at the host root: `/.well-known/oauth-protected-resource/docs/mcp`.\n * @param basePath - The public URL's path, `\"\"` or e.g. `/docs`.\n * @param endpointPath - The MCP endpoint's path under the public URL, e.g. `/mcp`.\n * @returns One or two paths.\n */\nexport function protectedResourceMetadataPaths(\n basePath: string,\n endpointPath: string,\n): string[] {\n const paths = [`${WELL_KNOWN_PREFIX}${endpointPath}`];\n if (basePath) {\n paths.push(`${WELL_KNOWN_PREFIX}${basePath}${endpointPath}`);\n }\n return paths;\n}\n\n/**\n * The metadata URL advertised in the discovery challenge. It lives under the\n * public URL's path, so a reverse proxy forwarding only that path reaches it.\n * @param publicUrl - The public URL, without a trailing slash.\n * @param endpointPath - The MCP endpoint's path under the public URL, e.g. `/mcp`.\n * @returns The absolute metadata URL.\n */\nexport function protectedResourceMetadataUrl(\n publicUrl: string,\n endpointPath: string,\n): string {\n return `${publicUrl}${WELL_KNOWN_PREFIX}${endpointPath}`;\n}\n\n/**\n * The `WWW-Authenticate` value for a request that carried no bearer token. It\n * has no error code, per RFC 6750 §3.1, which says a request lacking any\n * authentication information SHOULD NOT get one.\n * @param resourceMetadataUrl - The metadata URL to advertise.\n * @returns The challenge header value.\n */\nexport function missingTokenChallenge(resourceMetadataUrl: string): string {\n const quoted = resourceMetadataUrl.replaceAll(/[\\\\\"]/g, \"\\\\$&\");\n return `Bearer resource_metadata=\"${quoted}\"`;\n}\n","/**\n * Browser-origin and host-name policies shared by the MCP endpoint, the HTTP\n * API and its WebSocket upgrade.\n *\n * An `Origin` header is allowed when its host is loopback (any scheme and\n * port), when it is the public URL's origin, or when it exactly matches a\n * configured allowed origin. Requests without an `Origin` header come from\n * non-browser clients and are never refused because of it.\n *\n * The host policy closes the gap the origin check leaves: browsers send no\n * `Origin` on same-origin GET requests, so a page on an attacker's domain that\n * DNS-rebinds to this server is recognized by its `Host` header instead.\n */\n\nimport type { ServerResponse } from \"node:http\";\nimport { BlockList, isIP } from \"node:net\";\nimport { localhostAllowedOrigins } from \"@modelcontextprotocol/server\";\nimport { stripIpv6Brackets } from \"../utils/serverOrigin\";\n\n/** How a request's `Origin` header relates to the policy. */\nexport type OriginVerdict = \"absent\" | \"allowed\" | \"denied\";\n\n/** Classifies `Origin` header values. */\nexport interface OriginPolicy {\n /**\n * Classify an `Origin` header value.\n * @param origin - The raw header value, or `undefined` when the header is missing.\n * @returns `\"absent\"` without a header; `\"allowed\"` or `\"denied\"` otherwise.\n * `null`, unparsable and non-HTTP(S) values are `\"denied\"`.\n */\n check(origin: string | undefined): OriginVerdict;\n}\n\n/** What both policies are built from. */\nexport interface BrowserPolicyOptions {\n /** Origin (`scheme://host[:port]`) of the configured public URL, when one is configured. */\n publicOrigin?: string;\n /** Canonical origins (`scheme://host[:port]`) of hosted browser clients. */\n allowedOrigins: readonly string[];\n}\n\n/**\n * Build the origin policy. Loopback origins, the public URL's origin and each\n * allowed origin (matched exactly) are allowed.\n * @param options - The public origin and the allowed origins.\n * @returns The policy.\n */\nexport function createOriginPolicy(options: BrowserPolicyOptions): OriginPolicy {\n const loopbackHosts = new Set(\n localhostAllowedOrigins().map((host) => host.toLowerCase()),\n );\n const exactOrigins = new Set(options.allowedOrigins);\n if (options.publicOrigin !== undefined) {\n exactOrigins.add(options.publicOrigin);\n }\n\n return {\n check(origin) {\n if (origin === undefined) {\n return \"absent\";\n }\n let parsed: URL;\n try {\n parsed = new URL(origin);\n } catch {\n return \"denied\";\n }\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n return \"denied\";\n }\n const hostname = parsed.hostname.toLowerCase();\n if (loopbackHosts.has(hostname)) {\n return \"allowed\";\n }\n return exactOrigins.has(parsed.origin) ? \"allowed\" : \"denied\";\n },\n };\n}\n\n/** Decides which `Host` header values the server answers. */\nexport interface HostPolicy {\n /**\n * Whether a request's `Host` header names a host this server answers to.\n * @param host - The raw header value, or `undefined` when the header is missing.\n * @returns `true` when the request may be served.\n */\n isAllowed(host: string | undefined): boolean;\n}\n\n/**\n * `host[:port]` or `[ipv6][:port]`, the only shapes a browser sends. Captures\n * the host (with brackets for IPv6) and the port.\n */\nconst HOST_HEADER =\n /^([a-z0-9_-]+(?:\\.[a-z0-9_-]+)*\\.?|\\[[0-9a-f:.]+\\])(?::(\\d{1,5}))?$/i;\n\n/**\n * Build the host policy. A host is accepted when it is an IP address literal,\n * `localhost`, a single-label name (no dot, such as a Docker service name),\n * the public URL's host, or the host of an allowed origin. None of these can be\n * pointed at an attacker's page through public DNS, which is what DNS\n * rebinding needs. A request without a `Host` header is served.\n *\n * @param options - The public origin and the allowed origins, whose hosts are accepted.\n * @returns The policy.\n */\nexport function createHostPolicy(options: BrowserPolicyOptions): HostPolicy {\n const knownOrigins = [\n ...options.allowedOrigins,\n ...(options.publicOrigin === undefined ? [] : [options.publicOrigin]),\n ];\n const knownHosts = new Set(\n knownOrigins.map((origin) => new URL(origin).hostname.toLowerCase()),\n );\n\n return {\n isAllowed(host) {\n if (!host) {\n return true;\n }\n const match = HOST_HEADER.exec(host);\n if (!match || Number(match[2] ?? 0) > 65535) {\n return false;\n }\n const hostname = match[1].toLowerCase();\n if (hostname.startsWith(\"[\")) {\n return isIP(hostname.slice(1, -1)) === 6;\n }\n // `localhost` is a single-label name, so the dot check accepts it.\n return isIP(hostname) === 4 || !hostname.includes(\".\") || knownHosts.has(hostname);\n },\n };\n}\n\n/** Header names a CORS preflight may ask for: RFC 9110 field-name tokens only. */\nconst HEADER_TOKEN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n\n/**\n * Reduce a preflight's `Access-Control-Request-Headers` to valid header names,\n * so echoing it can never inject into the response.\n * @param requestedHeaders - The raw header value.\n * @returns The comma-separated valid names, or `undefined` when none remain.\n */\nfunction sanitizeRequestedHeaders(\n requestedHeaders: string | undefined,\n): string | undefined {\n const names = (requestedHeaders ?? \"\")\n .split(\",\")\n .map((name) => name.trim())\n .filter((name) => HEADER_TOKEN.test(name));\n return names.length > 0 ? names.join(\", \") : undefined;\n}\n\nfunction appendVary(res: ServerResponse, ...fields: string[]): void {\n const existing = res.getHeader(\"Vary\");\n const current =\n typeof existing === \"string\" ? existing.split(\",\").map((field) => field.trim()) : [];\n const merged = [...current.filter(Boolean)];\n for (const field of fields) {\n if (!merged.some((entry) => entry.toLowerCase() === field.toLowerCase())) {\n merged.push(field);\n }\n }\n res.setHeader(\"Vary\", merged.join(\", \"));\n}\n\n/**\n * Add the CORS headers a browser needs to read a response from an allowed\n * origin, including the `WWW-Authenticate` challenge. Call only for an\n * `\"allowed\"` verdict, before anything is written.\n * @param res - The response to decorate.\n * @param origin - The request's `Origin` header value.\n */\nexport function setCorsResponseHeaders(res: ServerResponse, origin: string): void {\n res.setHeader(\"Access-Control-Allow-Origin\", origin);\n res.setHeader(\"Access-Control-Expose-Headers\", \"WWW-Authenticate\");\n appendVary(res, \"Origin\");\n}\n\n/**\n * Set the headers of a CORS preflight answer: allow the given methods and echo\n * the request headers the preflight names. The caller sends the `204`.\n * @param res - The response to decorate.\n * @param options.origin - The allowed origin to echo (only for an `\"allowed\"` verdict), or `*`.\n * @param options.methods - The methods to allow, e.g. `POST`.\n * @param options.requestedHeaders - The preflight's `Access-Control-Request-Headers` value.\n */\nexport function setCorsPreflightHeaders(\n res: ServerResponse,\n options: { origin: string; methods: string; requestedHeaders: string | undefined },\n): void {\n res.setHeader(\"Access-Control-Allow-Origin\", options.origin);\n res.setHeader(\"Access-Control-Allow-Methods\", options.methods);\n const headers = sanitizeRequestedHeaders(options.requestedHeaders);\n if (headers) {\n res.setHeader(\"Access-Control-Allow-Headers\", headers);\n }\n res.setHeader(\"Access-Control-Max-Age\", \"600\");\n appendVary(res, \"Origin\", \"Access-Control-Request-Headers\");\n}\n\n/**\n * Loopback addresses. `BlockList` matches every IPv6 notation, IPv4-mapped\n * addresses (`::ffff:127.0.0.1`) and zone IDs (`::1%lo0`).\n */\nconst LOOPBACK_ADDRESSES = new BlockList();\nLOOPBACK_ADDRESSES.addSubnet(\"127.0.0.0\", 8, \"ipv4\");\nLOOPBACK_ADDRESSES.addAddress(\"::1\", \"ipv6\");\n\n/**\n * Whether the server listens only on the loopback interface, where no reverse\n * proxy stands between it and a local browser.\n * @param host - The configured bind host.\n * @returns `true` for `localhost`, `127.0.0.0/8` and `::1`, in any notation.\n */\nexport function isLoopbackBindHost(host: string): boolean {\n const unbracketed = stripIpv6Brackets(host.trim().toLowerCase());\n const family = isIP(unbracketed);\n if (family === 0) {\n return unbracketed === \"localhost\";\n }\n return LOOPBACK_ADDRESSES.check(unbracketed, family === 6 ? \"ipv6\" : \"ipv4\");\n}\n","export class ToolError extends Error {\n constructor(\n message: string,\n public readonly toolName: string,\n ) {\n super(message);\n this.name = this.constructor.name;\n }\n}\n\n/**\n * Error thrown when tool input validation fails.\n * This indicates a client-side issue with the request parameters.\n */\nexport class ValidationError extends ToolError {}\n","/**\n * Built-in instructions sent to MCP clients when no instructions are configured.\n * Tool descriptions each explain one tool; this text explains how the tools work\n * together. Every tool named here must be registered in the matching mode.\n */\n\nconst INTRO =\n \"This server searches up-to-date documentation for libraries and packages. \" +\n \"When a question depends on a library's API or behavior, search here before answering from memory.\";\n\nconst SEARCH =\n \"- `search_docs` searches one library. Pass `version` when the project uses a specific version; \" +\n \"without it, the newest indexed version is searched when there is one.\";\n\nconst DISCOVER =\n \"- Library names must match an indexed library. If a search cannot find the library, \" +\n \"call `list_libraries` for the exact names and versions.\";\n\nconst INDEX =\n \"- `fetch_url` is for libraries that are not indexed: read their documentation to answer now. \" +\n \"`scrape_docs` can index a library so later searches find it. \" +\n \"Indexing runs in the background: check progress with `get_job_info` and search once the job has completed.\";\n\nconst READ_ONLY =\n \"- This server is read-only and cannot index new documentation. \" +\n \"`fetch_url` is for libraries that are not indexed: read their documentation to answer now.\";\n\n/**\n * Builds the built-in instructions for the given mode.\n * @param readOnly Whether the server runs in read-only mode, where indexing tools are not registered.\n * @returns The instructions text.\n */\nexport function buildDefaultInstructions(readOnly: boolean): string {\n return [INTRO, \"\", SEARCH, DISCOVER, readOnly ? READ_ONLY : INDEX].join(\"\\n\");\n}\n","import type { CallToolResult } from \"@modelcontextprotocol/server\";\n\n/**\n * Creates a success response object in the format expected by the MCP server.\n * @param text The text content of the response.\n * @returns The response object.\n */\nexport function createResponse(text: string): CallToolResult {\n return {\n content: [\n {\n type: \"text\",\n text,\n },\n ],\n isError: false,\n };\n}\n\n/**\n * Creates an error response object in the format expected by the MCP server.\n * @param text The error message.\n * @returns The response object.\n */\nexport function createError(errorOrText: unknown): CallToolResult {\n const text = errorOrText instanceof Error ? errorOrText.message : String(errorOrText);\n return {\n content: [\n {\n type: \"text\",\n text,\n },\n ],\n isError: true,\n };\n}\n","import fs from \"node:fs\";\nimport { McpServer, ResourceTemplate } from \"@modelcontextprotocol/server\";\nimport { z } from \"zod\";\nimport { PipelineJobStatus } from \"../pipeline/types\";\nimport { libraryNamesMatch } from \"../store/types\";\nimport {\n extractHostname,\n extractProtocol,\n TelemetryEvent,\n telemetry,\n} from \"../telemetry\";\nimport type { JobInfo } from \"../tools\";\nimport { ToolError } from \"../tools/errors\";\nimport type { AppConfig } from \"../utils/config\";\nimport { logger } from \"../utils/logger\";\nimport { buildDefaultInstructions } from \"./defaultInstructions\";\nimport type { McpServerTools } from \"./tools\";\nimport { createError, createResponse } from \"./utils\";\n\n/**\n * Splits a comma-separated pattern string into an array of patterns. Commas\n * inside `{}`, `[]`, or `()` (regex quantifiers, glob brace expansion,\n * character classes) and escaped commas (`\\,`) are preserved so that a single\n * regex or glob pattern is never torn apart. This keeps the argument\n * renderable as one string for MCP clients that only display primitive tool\n * arguments.\n * @param value The raw pattern string.\n * @returns An array of trimmed, non-empty patterns.\n */\nfunction splitPatterns(value: string): string[] {\n const patterns: string[] = [];\n let current = \"\";\n let braces = 0;\n let brackets = 0;\n let parens = 0;\n for (let i = 0; i < value.length; i++) {\n const ch = value[i];\n if (ch === \"\\\\\") {\n if (i + 1 < value.length) {\n current += ch + value[i + 1];\n i++;\n } else {\n current += ch;\n }\n continue;\n }\n if (ch === \"{\") braces++;\n else if (ch === \"}\") braces = Math.max(0, braces - 1);\n else if (ch === \"[\") brackets++;\n else if (ch === \"]\") brackets = Math.max(0, brackets - 1);\n else if (ch === \"(\") parens++;\n else if (ch === \")\") parens = Math.max(0, parens - 1);\n if (ch === \",\" && braces === 0 && brackets === 0 && parens === 0) {\n patterns.push(current.trim());\n current = \"\";\n continue;\n }\n current += ch;\n }\n patterns.push(current.trim());\n return patterns.filter(Boolean);\n}\n\n/**\n * Schema for URL pattern arguments. Accepts a single pattern as a string or\n * multiple patterns as an array of strings, and normalizes both to an array\n * of trimmed, non-empty patterns. A string is split on top-level commas while\n * commas inside `{}`, `[]`, or `()` are preserved, so regex quantifiers and\n * glob brace expansion survive.\n */\nconst patternsSchema = z.union([z.string(), z.array(z.string())]).transform((value) => {\n if (typeof value === \"string\") return splitPatterns(value);\n return value.map((p) => p.trim()).filter(Boolean);\n});\n\n/**\n * Resolves the instructions text advertised to MCP clients during initialization.\n * `createMcpServerFactory()` calls this once at startup, so the instructions file\n * is read a single time rather than for every client session.\n * `server.instructions` and `server.instructionsFile` are mutually exclusive. When\n * neither is set, the built-in instructions for the current mode are used.\n * @param config The application configuration.\n * @returns The configured instructions text, or the built-in instructions.\n * @throws {Error} If both settings are set, or the configured instructions file cannot be read.\n */\nexport function resolveServerInstructions(config: AppConfig): string {\n const { instructions, instructionsFile: filePath } = config.server;\n if (instructions !== undefined && filePath !== undefined) {\n throw new Error(\n \"Both server.instructions and server.instructionsFile are set; configure only one of them.\",\n );\n }\n if (instructions !== undefined) {\n return instructions;\n }\n if (filePath === undefined) {\n return buildDefaultInstructions(config.app.readOnly);\n }\n try {\n return fs.readFileSync(filePath, \"utf8\");\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Failed to read MCP server instructions file \"${filePath}\": ${reason}`,\n );\n }\n}\n\n/**\n * Decodes a URI template variable once. The SDK hands variables over still\n * percent-encoded; a malformed escape is kept verbatim rather than failing.\n */\nfunction decodeUriVariable(value: string | string[]): string {\n const raw = Array.isArray(value) ? value.join(\"/\") : value;\n try {\n return decodeURIComponent(raw);\n } catch {\n return raw;\n }\n}\n\n/**\n * Build the input schemas of every tool. They depend only on configuration,\n * which does not change while the process runs, so one set serves every MCP\n * server instance. Over HTTP an instance is created per request.\n * @param config The application configuration.\n * @returns The input schema for each tool, keyed by the tool's camel-cased name.\n */\nfunction createToolInputSchemas(config: AppConfig) {\n return {\n scrapeDocs: z.object({\n url: z.string().url().describe(\"Documentation root URL to scrape.\"),\n library: z.string().trim().describe(\"Library name.\"),\n version: z.string().trim().optional().describe(\"Library version (optional).\"),\n maxPages: z\n .number()\n .optional()\n .default(config.scraper.maxPages)\n .describe(\n `Maximum number of pages to scrape (default: ${config.scraper.maxPages}).`,\n ),\n maxDepth: z\n .number()\n .optional()\n .default(config.scraper.maxDepth)\n .describe(`Maximum navigation depth (default: ${config.scraper.maxDepth}).`),\n scope: z\n .enum([\"subpages\", \"hostname\", \"domain\"])\n .optional()\n .default(\"subpages\")\n .describe(\"Crawling boundary: 'subpages', 'hostname', or 'domain'.\"),\n followRedirects: z\n .boolean()\n .optional()\n .default(true)\n .describe(\"Follow HTTP redirects (3xx responses).\"),\n replace: z\n .boolean()\n .optional()\n .default(false)\n .describe(\n \"Rebuild the version from scratch if it already exists. Without it, an existing version is left untouched and the request fails.\",\n ),\n preserveHashes: z\n .boolean()\n .optional()\n .describe(\"Preserve hash fragments for hash-routed SPA documentation sites.\"),\n includePatterns: patternsSchema\n .optional()\n .describe(\n \"Patterns for including URLs during scraping. Pass one or more patterns as a comma-separated string or as an array. Commas inside { }, [ ] or ( ) are preserved; escape a literal comma with a backslash. Regex patterns must be wrapped in slashes, e.g. /pattern/. If not set, all are included by default.\",\n ),\n excludePatterns: patternsSchema\n .optional()\n .describe(\n \"Patterns for excluding URLs during scraping. Pass one or more patterns as a comma-separated string or as an array. Commas inside { }, [ ] or ( ) are preserved; escape a literal comma with a backslash. Exclude takes precedence over include. Regex patterns must be wrapped in slashes, e.g. /pattern/.\",\n ),\n }),\n refreshVersion: z.object({\n library: z.string().trim().describe(\"Library name.\"),\n version: z\n .string()\n .trim()\n .optional()\n .describe(\"Library version (optional, refreshes latest if omitted).\"),\n }),\n searchDocs: z.object({\n library: z.string().trim().describe(\"Library name.\"),\n version: z\n .string()\n .trim()\n .optional()\n .describe(\"Library version (exact or X-Range, optional).\"),\n query: z.string().trim().describe(\"Documentation search query.\"),\n limit: z.number().optional().default(5).describe(\"Maximum number of results.\"),\n }),\n readPage: z.object({\n library: z.string().trim().describe(\"Library name.\"),\n pathOrUrl: z\n .string()\n .trim()\n .min(1)\n .describe(\n \"Page URL, or a path matching the end of one page URL (e.g. 'https://react.dev/reference/react' or '/reference/react').\",\n ),\n version: z\n .string()\n .trim()\n .optional()\n .describe(\"Library version (exact or X-Range, optional).\"),\n startChunk: z\n .number()\n .int()\n .nonnegative()\n .optional()\n .default(0)\n .describe(\"Chunk to start from, as given by a previous response (default 0).\"),\n maxChars: z\n .number()\n .positive()\n .optional()\n .default(30000)\n .describe(\n \"Maximum characters to return (default 30000). Only whole chunks are returned, so a single longer chunk is returned on its own.\",\n ),\n }),\n listPages: z.object({\n library: z.string().trim().describe(\"Library name.\"),\n version: z\n .string()\n .trim()\n .optional()\n .describe(\"Library version (exact or X-Range, optional).\"),\n contains: z\n .string()\n .trim()\n .optional()\n .describe(\"Only list pages whose URL contains this text (e.g. '/components').\"),\n limit: z\n .number()\n .int()\n .positive()\n .max(200)\n .optional()\n .default(50)\n .describe(\"Maximum pages to return (default 50, max 200).\"),\n offset: z\n .number()\n .int()\n .nonnegative()\n .optional()\n .default(0)\n .describe(\"Number of pages to skip (default 0).\"),\n }),\n listLibraries: z.object({\n // no params\n }),\n findVersion: z.object({\n library: z.string().trim().describe(\"Library name.\"),\n targetVersion: z\n .string()\n .trim()\n .optional()\n .describe(\"Version pattern to match (exact or X-Range, optional).\"),\n }),\n listJobs: z.object({\n status: z\n .enum([\"queued\", \"running\", \"completed\", \"failed\", \"cancelling\", \"cancelled\"])\n .optional()\n .describe(\"Filter jobs by status (optional).\"),\n }),\n getJobInfo: z.object({\n jobId: z.string().uuid().describe(\"Job ID to query.\"),\n }),\n cancelJob: z.object({\n jobId: z.string().uuid().describe(\"Job ID to cancel.\"),\n }),\n removeDocs: z.object({\n library: z.string().trim().describe(\"Library name.\"),\n version: z\n .string()\n .trim()\n .optional()\n .describe(\"Library version (optional, removes latest if omitted).\"),\n }),\n fetchUrl: z.object({\n url: z.string().url().describe(\"URL to fetch and convert to Markdown.\"),\n followRedirects: z\n .boolean()\n .optional()\n .default(true)\n .describe(\"Follow HTTP redirects (3xx responses).\"),\n }),\n };\n}\n\n/** Input schemas for every tool, as built by {@link createToolInputSchemas}. */\ntype ToolInputSchemas = ReturnType<typeof createToolInputSchemas>;\n\n/**\n * Build a factory for MCP server instances that share one set of tool input\n * schemas and one instructions text, for transports that create an instance\n * per request or connection. Both are resolved here, once, at startup.\n * @param tools The shared tool instances to use for server operations.\n * @param config The application configuration.\n * @returns A function that creates a configured McpServer instance.\n * @throws {Error} If the configured instructions cannot be resolved.\n */\nexport function createMcpServerFactory(\n tools: McpServerTools,\n config: AppConfig,\n): () => McpServer {\n const instructions = resolveServerInstructions(config);\n const schemas = createToolInputSchemas(config);\n return () => createMcpServerInstance(tools, config, instructions, schemas);\n}\n\n/**\n * Creates and configures an instance of the MCP server with registered tools and resources.\n * @param tools The shared tool instances to use for server operations.\n * @param config The application configuration.\n * @param instructions Instructions text sent to clients during initialization, as\n * returned by `resolveServerInstructions()`.\n * @param schemas The tool input schemas, shared by every instance.\n * @returns A configured McpServer instance.\n */\nfunction createMcpServerInstance(\n tools: McpServerTools,\n config: AppConfig,\n instructions: string,\n schemas: ToolInputSchemas,\n): McpServer {\n const readOnly = config.app.readOnly;\n const { name, title } = config.server;\n const server = new McpServer(\n {\n name,\n ...(title !== undefined ? { title } : {}),\n version: __APP_VERSION__,\n },\n {\n capabilities: {\n tools: {},\n resources: {},\n },\n instructions,\n },\n );\n\n // --- Tool Definitions ---\n\n // Only register write/job tools if not in read-only mode\n if (!readOnly) {\n // Scrape docs tool - suppress deep inference issues\n server.registerTool(\n \"scrape_docs\",\n {\n description:\n \"Scrape and index documentation from a URL for a library. Use this tool to index a new library or a new version. Scraping a library version that already exists is rejected unless `replace` is true; use refresh_version to update an existing version in place.\",\n inputSchema: schemas.scrapeDocs,\n annotations: {\n title: \"Scrape New Library Documentation\",\n destructiveHint: true, // replaces existing docs\n openWorldHint: true, // requires internet access\n },\n },\n async ({\n url,\n library,\n version,\n maxPages,\n maxDepth,\n scope,\n followRedirects,\n replace,\n preserveHashes,\n includePatterns,\n excludePatterns,\n }) => {\n // Track MCP tool usage\n telemetry.track(TelemetryEvent.TOOL_USED, {\n tool: \"scrape_docs\",\n context: \"mcp_server\",\n library,\n version,\n url: extractHostname(url), // Host only, never the full URL\n urlProtocol: extractProtocol(url),\n maxPages,\n maxDepth,\n scope,\n });\n\n try {\n // Execute scrape tool without waiting and without progress callback\n const result = await tools.scrape.execute({\n url,\n library,\n version,\n replace,\n waitForCompletion: false, // Don't wait for completion\n // onProgress: undefined, // Explicitly undefined or omitted\n options: {\n maxPages,\n maxDepth,\n scope,\n followRedirects,\n preserveHashes,\n includePatterns,\n excludePatterns,\n },\n });\n\n // Check the type of result\n if (\"jobId\" in result) {\n // If we got a jobId back, report that\n return createResponse(`🚀 Scraping job started with ID: ${result.jobId}.`);\n }\n // This case shouldn't happen if waitForCompletion is false, but handle defensively\n return createResponse(\n `Scraping finished immediately (unexpectedly) with ${result.pagesScraped} pages.`,\n );\n } catch (error) {\n // Handle errors during job *enqueueing* or initial setup\n return createError(error);\n }\n },\n );\n\n // Refresh version tool - suppress deep inference issues\n server.registerTool(\n \"refresh_version\",\n {\n description:\n \"Re-scrape a previously indexed library version, updating only changed pages.\",\n inputSchema: schemas.refreshVersion,\n annotations: {\n title: \"Refresh Library Version\",\n destructiveHint: false, // Only updates changed content\n openWorldHint: true, // requires internet access\n },\n },\n async ({ library, version }) => {\n // Track MCP tool usage\n telemetry.track(TelemetryEvent.TOOL_USED, {\n tool: \"refresh_version\",\n context: \"mcp_server\",\n library,\n version,\n });\n\n try {\n // Execute refresh tool without waiting\n const result = await tools.refresh.execute({\n library,\n version,\n waitForCompletion: false, // Don't wait for completion\n });\n\n // Check the type of result\n if (\"jobId\" in result) {\n // If we got a jobId back, report that\n return createResponse(`🔄 Refresh job started with ID: ${result.jobId}.`);\n }\n // This case shouldn't happen if waitForCompletion is false, but handle defensively\n return createResponse(\n `Refresh finished immediately (unexpectedly) with ${result.pagesRefreshed} pages.`,\n );\n } catch (error) {\n // Handle errors during job enqueueing or initial setup\n return createError(error);\n }\n },\n );\n }\n\n // Search docs tool\n server.registerTool(\n \"search_docs\",\n {\n description:\n \"Search up-to-date documentation for a library or package. Examples:\\n\\n\" +\n '- {library: \"react\", query: \"hooks lifecycle\"} -> matches latest version of React\\n' +\n '- {library: \"react\", version: \"18.0.0\", query: \"hooks lifecycle\"} -> matches React 18.0.0 or earlier\\n' +\n '- {library: \"typescript\", version: \"5.x\", query: \"ReturnType example\"} -> any TypeScript 5.x.x version\\n' +\n '- {library: \"typescript\", version: \"5.2.x\", query: \"ReturnType example\"} -> any TypeScript 5.2.x version',\n inputSchema: schemas.searchDocs,\n annotations: {\n title: \"Search Library Documentation\",\n readOnlyHint: true,\n destructiveHint: false,\n },\n },\n async ({ library, version, query, limit }) => {\n // Track MCP tool usage\n telemetry.track(TelemetryEvent.TOOL_USED, {\n tool: \"search_docs\",\n context: \"mcp_server\",\n library,\n version,\n queryLength: query.length, // Never the query itself\n limit,\n });\n\n try {\n const result = await tools.search.execute({\n library,\n version,\n query,\n limit,\n exactMatch: false, // Always false for MCP interface\n });\n\n const formattedResults = result.results.map(\n (r: { url: string; content: string }, i: number) => `\n------------------------------------------------------------\nResult ${i + 1}: ${r.url}\n\n${r.content}\\n`,\n );\n\n if (formattedResults.length === 0) {\n return createResponse(\n `No results found for '${query}' in ${library}. Try to use a different or more general query.`,\n );\n }\n return createResponse(formattedResults.join(\"\"));\n } catch (error) {\n return createError(error);\n }\n },\n );\n\n // Read page tool\n server.registerTool(\n \"read_page\",\n {\n description:\n \"Read the full content of an indexed documentation page, for example a URL returned by `search_docs` or `list_pages`. \" +\n \"Long pages are returned in parts; the response says how to continue.\",\n inputSchema: schemas.readPage,\n annotations: {\n title: \"Read Documentation Page\",\n readOnlyHint: true,\n destructiveHint: false,\n },\n },\n async ({ library, pathOrUrl, version, startChunk, maxChars }) => {\n telemetry.track(TelemetryEvent.TOOL_USED, {\n tool: \"read_page\",\n context: \"mcp_server\",\n library,\n version,\n });\n\n try {\n const result = await tools.readPage.execute({\n library,\n pathOrUrl,\n version,\n startChunk,\n maxChars,\n });\n\n if (result.startChunk >= result.totalChunks && result.totalChunks > 0) {\n return createResponse(\n `startChunk ${result.startChunk} is past the end of ${result.url}, which has ${result.totalChunks} chunks.`,\n );\n }\n\n const end = result.nextChunk ?? result.totalChunks;\n const notice =\n result.nextChunk !== null\n ? `\\n\\n> Showing chunks ${result.startChunk + 1}-${end} of ${result.totalChunks}. ` +\n `To continue, call read_page again with startChunk: ${result.nextChunk}.`\n : \"\";\n\n return createResponse(`> Source: ${result.url}\\n\\n${result.content}${notice}`);\n } catch (error) {\n return createError(error);\n }\n },\n );\n\n // List pages tool\n server.registerTool(\n \"list_pages\",\n {\n description:\n \"List the indexed pages of a library version, with an optional URL filter and pagination.\",\n inputSchema: schemas.listPages,\n annotations: {\n title: \"List Library Pages\",\n readOnlyHint: true,\n destructiveHint: false,\n },\n },\n async ({ library, version, contains, limit, offset }) => {\n telemetry.track(TelemetryEvent.TOOL_USED, {\n tool: \"list_pages\",\n context: \"mcp_server\",\n library,\n version,\n limit,\n offset,\n });\n\n try {\n const result = await tools.listPages.execute({\n library,\n version,\n contains,\n limit,\n offset,\n });\n\n if (result.pages.length === 0) {\n return createResponse(\n `No pages found for '${library}'${result.version ? `@${result.version}` : \"\"}${contains ? ` with URLs containing '${contains}'` : \"\"}.`,\n );\n }\n\n const lines = result.pages.map((p) => {\n const safeTitle = (p.title || p.url)\n .replace(/\\[/g, \"\\\\[\")\n .replace(/\\]/g, \"\\\\]\");\n return `- [${safeTitle}](<${p.url}>)${p.depth !== null ? ` (depth: ${p.depth})` : \"\"}`;\n });\n\n let responseText = `Indexed pages for ${result.library}${result.version ? `@${result.version}` : \"\"} (${result.total} total pages, showing ${result.offset + 1}-${result.offset + result.pages.length}):\\n\\n${lines.join(\"\\n\")}`;\n\n if (result.hasMore) {\n responseText += `\\n\\nUse offset: ${result.offset + result.pages.length} to see the next batch of pages.`;\n }\n\n return createResponse(responseText);\n } catch (error) {\n return createError(error);\n }\n },\n );\n\n // List libraries tool\n server.registerTool(\n \"list_libraries\",\n {\n description:\n \"List all indexed libraries and their versions. Use this to find the correct library name.\",\n inputSchema: schemas.listLibraries,\n annotations: {\n title: \"List Libraries\",\n readOnlyHint: true,\n destructiveHint: false,\n },\n },\n async () => {\n // Track MCP tool usage\n telemetry.track(TelemetryEvent.TOOL_USED, {\n tool: \"list_libraries\",\n context: \"mcp_server\",\n });\n\n try {\n const result = await tools.listLibraries.execute();\n if (result.libraries.length === 0) {\n return createResponse(\"No libraries indexed yet.\");\n }\n\n return createResponse(\n `Indexed libraries:\\n\\n${result.libraries.map((lib: { name: string }) => `- ${lib.name}`).join(\"\\n\")}`,\n );\n } catch (error) {\n return createError(error);\n }\n },\n );\n\n // Find version tool\n server.registerTool(\n \"find_version\",\n {\n description:\n \"Find the best matching version for a library. Use to identify available or closest versions.\",\n inputSchema: schemas.findVersion,\n annotations: {\n title: \"Find Library Version\",\n readOnlyHint: true,\n destructiveHint: false,\n },\n },\n async ({ library, targetVersion }) => {\n // Track MCP tool usage\n telemetry.track(TelemetryEvent.TOOL_USED, {\n tool: \"find_version\",\n context: \"mcp_server\",\n library,\n targetVersion,\n });\n\n try {\n const result = await tools.findVersion.execute({\n library,\n targetVersion,\n });\n\n // Tool now returns a structured object with message\n return createResponse(result.message);\n } catch (error) {\n return createError(error);\n }\n },\n );\n\n // Job and write tools - only available when not in read-only mode\n if (!readOnly) {\n // List jobs tool - suppress deep inference issues\n server.registerTool(\n \"list_jobs\",\n {\n description: \"List all indexing jobs. Optionally filter by status.\",\n inputSchema: schemas.listJobs,\n annotations: {\n title: \"List Indexing Jobs\",\n readOnlyHint: true,\n destructiveHint: false,\n },\n },\n async ({ status }) => {\n // Track MCP tool usage\n telemetry.track(TelemetryEvent.TOOL_USED, {\n tool: \"list_jobs\",\n context: \"mcp_server\",\n status,\n });\n\n try {\n const result = await tools.listJobs.execute({\n status: status as PipelineJobStatus | undefined,\n });\n // Format the simplified job list for display\n const formattedJobs = result.jobs\n .map(\n (job: JobInfo) =>\n `- ID: ${job.id}\\n Status: ${job.status}\\n Library: ${job.library}\\n Version: ${job.version}\\n Created: ${job.createdAt}${job.startedAt ? `\\n Started: ${job.startedAt}` : \"\"}${job.finishedAt ? `\\n Finished: ${job.finishedAt}` : \"\"}${job.error ? `\\n Error: ${job.error}` : \"\"}`,\n )\n .join(\"\\n\\n\");\n return createResponse(\n result.jobs.length > 0\n ? `Current Jobs:\\n\\n${formattedJobs}`\n : \"No jobs found.\",\n );\n } catch (error) {\n return createError(error);\n }\n },\n );\n\n // Get job info tool\n server.registerTool(\n \"get_job_info\",\n {\n description:\n \"Get details for a specific indexing job. Use the 'list_jobs' tool to find the job ID.\",\n inputSchema: schemas.getJobInfo,\n annotations: {\n title: \"Get Indexing Job Info\",\n readOnlyHint: true,\n destructiveHint: false,\n },\n },\n async ({ jobId }) => {\n // Track MCP tool usage\n telemetry.track(TelemetryEvent.TOOL_USED, {\n tool: \"get_job_info\",\n context: \"mcp_server\",\n jobId,\n });\n\n try {\n const result = await tools.getJobInfo.execute({ jobId });\n // Tool now guarantees result.job is always present on success\n const job = result.job;\n const formattedJob = `- ID: ${job.id}\\n Status: ${job.status}\\n Library: ${job.library}@${job.version}\\n Created: ${job.createdAt}${job.startedAt ? `\\n Started: ${job.startedAt}` : \"\"}${job.finishedAt ? `\\n Finished: ${job.finishedAt}` : \"\"}${job.error ? `\\n Error: ${job.error}` : \"\"}`;\n return createResponse(`Job Info:\\n\\n${formattedJob}`);\n } catch (error) {\n // Tool now throws error when job not found\n return createError(error);\n }\n },\n );\n\n // Cancel job tool\n server.registerTool(\n \"cancel_job\",\n {\n description:\n \"Cancel a queued or running indexing job. Use the 'list_jobs' tool to find the job ID.\",\n inputSchema: schemas.cancelJob,\n annotations: {\n title: \"Cancel Indexing Job\",\n destructiveHint: true,\n },\n },\n async ({ jobId }) => {\n // Track MCP tool usage\n telemetry.track(TelemetryEvent.TOOL_USED, {\n tool: \"cancel_job\",\n context: \"mcp_server\",\n jobId,\n });\n\n try {\n const result = await tools.cancelJob.execute({ jobId });\n // Tool now always returns success data or throws error\n return createResponse(result.message);\n } catch (error) {\n // Catch any errors thrown by the tool (job not found, cancellation failed, etc.)\n return createError(error);\n }\n },\n );\n\n // Remove docs tool\n server.registerTool(\n \"remove_docs\",\n {\n description:\n \"Remove indexed documentation for a library version. Use only if explicitly instructed.\",\n inputSchema: schemas.removeDocs,\n annotations: {\n title: \"Remove Library Documentation\",\n destructiveHint: true,\n },\n },\n async ({ library, version }) => {\n // Track MCP tool usage\n telemetry.track(TelemetryEvent.TOOL_USED, {\n tool: \"remove_docs\",\n context: \"mcp_server\",\n library,\n version,\n });\n\n try {\n // Execute the remove tool logic\n const result = await tools.remove.execute({ library, version });\n // Use the message from the tool's successful execution\n return createResponse(result.message);\n } catch (error) {\n // Catch errors thrown by the RemoveTool's execute method\n return createError(error);\n }\n },\n );\n }\n\n // Fetch URL tool\n server.registerTool(\n \"fetch_url\",\n {\n description:\n \"Fetch a single URL and convert its content to Markdown. Use this tool to read the content of any web page.\",\n inputSchema: schemas.fetchUrl,\n annotations: {\n title: \"Fetch URL\",\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: true, // requires internet access\n },\n },\n async ({ url, followRedirects }) => {\n // Track MCP tool usage\n telemetry.track(TelemetryEvent.TOOL_USED, {\n tool: \"fetch_url\",\n context: \"mcp_server\",\n url: extractHostname(url), // Host only, never the full URL\n urlProtocol: extractProtocol(url),\n followRedirects,\n });\n\n try {\n const result = await tools.fetchUrl.execute({ url, followRedirects });\n return createResponse(result);\n } catch (error) {\n return createError(error);\n }\n },\n );\n\n server.registerResource(\n \"libraries\",\n \"docs://libraries\",\n {\n description: \"List all indexed libraries\",\n },\n async (uri: URL) => {\n const result = await tools.listLibraries.execute();\n\n return {\n contents: result.libraries.map((lib: { name: string }) => ({\n uri: new URL(lib.name, uri).href,\n text: lib.name,\n })),\n };\n },\n );\n\n server.registerResource(\n \"versions\",\n new ResourceTemplate(\"docs://libraries/{library}/versions\", {\n list: undefined,\n }),\n {\n description: \"List all indexed versions for a library\",\n },\n async (uri: URL, { library }) => {\n const result = await tools.listLibraries.execute();\n\n // The template variable arrives percent-encoded (a name containing \"/\" must\n // be sent as %2F), and names match case-insensitively.\n const requested = decodeUriVariable(library);\n const lib = result.libraries.find((l: { name: string }) =>\n libraryNamesMatch(l.name, requested),\n );\n if (!lib) {\n return { contents: [] };\n }\n\n return {\n contents: lib.versions.map((v: { version: string }) => ({\n uri: new URL(v.version, uri).href,\n text: v.version,\n })),\n };\n },\n );\n\n // Job-related resources - only available when not in read-only mode\n if (!readOnly) {\n /**\n * Resource handler for listing pipeline jobs.\n * Supports filtering by status via a query parameter (e.g., ?status=running).\n * URI: docs://jobs[?status=<status>]\n */\n server.registerResource(\n \"jobs\",\n \"docs://jobs\",\n {\n description: \"List indexing jobs, optionally filtering by status.\",\n mimeType: \"application/json\",\n },\n async (uri: URL) => {\n const statusParam = uri.searchParams.get(\"status\");\n let statusFilter: PipelineJobStatus | undefined;\n\n // Validate status parameter if provided\n if (statusParam) {\n const validation = z.nativeEnum(PipelineJobStatus).safeParse(statusParam);\n if (validation.success) {\n statusFilter = validation.data;\n } else {\n // Handle invalid status - perhaps return an error or ignore?\n // For simplicity, let's ignore invalid status for now and return all jobs.\n // Alternatively, could throw an McpError or return specific error content.\n logger.warn(`⚠️ Invalid status parameter received: ${statusParam}`);\n }\n }\n\n // Fetch simplified jobs using the ListJobsTool\n const result = await tools.listJobs.execute({ status: statusFilter });\n\n return {\n contents: result.jobs.map((job) => ({\n uri: new URL(job.id, uri).href,\n mimeType: \"application/json\",\n text: JSON.stringify({\n id: job.id,\n library: job.library,\n version: job.version,\n status: job.status,\n error: job.error || undefined,\n }),\n })),\n };\n },\n );\n\n /**\n * Resource handler for retrieving a specific pipeline job by its ID.\n * URI Template: docs://jobs/{jobId}\n */\n server.registerResource(\n \"job\", // A distinct name for this specific resource type\n new ResourceTemplate(\"docs://jobs/{jobId}\", { list: undefined }),\n {\n description: \"Get details for a specific indexing job by ID.\",\n mimeType: \"application/json\",\n },\n async (uri: URL, { jobId }) => {\n // Validate jobId format if necessary (basic check)\n if (typeof jobId !== \"string\" || jobId.length === 0) {\n // Handle invalid jobId format - return empty or error\n logger.warn(`⚠️ Invalid jobId received in URI: ${jobId}`);\n return { contents: [] }; // Return empty content for invalid ID format\n }\n\n try {\n // Fetch the simplified job info using GetJobInfoTool\n const result = await tools.getJobInfo.execute({ jobId });\n\n // Tool now guarantees result.job is always present on success\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: \"application/json\",\n text: JSON.stringify({\n id: result.job.id,\n library: result.job.library,\n version: result.job.version,\n status: result.job.status,\n error: result.job.error || undefined,\n }),\n },\n ],\n };\n } catch (error) {\n if (error instanceof ToolError) {\n // Expected error (job not found, etc.)\n logger.warn(`⚠️ Job not found for resource request: ${jobId}`);\n } else {\n // Unexpected error\n logger.error(\n `❌ Unexpected error in job resource handler: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n return { contents: [] };\n }\n },\n );\n }\n\n return server;\n}\n","import type { IPipeline } from \"../pipeline/trpc/interfaces\";\nimport { PipelineJobStatus } from \"../pipeline/types\";\nimport { logger } from \"../utils/logger\";\nimport { ToolError, ValidationError } from \"./errors\";\n\n/**\n * Input parameters for the CancelJobTool.\n */\nexport interface CancelJobInput {\n /** The ID of the job to cancel. */\n jobId: string;\n}\n\n/**\n * Output result for the CancelJobTool.\n */\nexport interface CancelJobResult {\n /** A message indicating the outcome of the cancellation attempt. */\n message: string;\n /** The final status of the job after cancellation attempt. */\n finalStatus: string;\n}\n\n/**\n * Tool for attempting to cancel a pipeline job.\n */\nexport class CancelJobTool {\n private pipeline: IPipeline;\n\n /**\n * Creates an instance of CancelJobTool.\n * @param pipeline The pipeline instance.\n */\n constructor(pipeline: IPipeline) {\n this.pipeline = pipeline;\n }\n\n /**\n * Executes the tool to attempt cancellation of a specific job.\n * @param input - The input parameters, containing the jobId.\n * @returns A promise that resolves with the outcome message.\n * @throws {ValidationError} If the jobId is invalid.\n * @throws {ToolError} If the job is not found or cancellation fails.\n */\n async execute(input: CancelJobInput): Promise<CancelJobResult> {\n // Validate input\n if (!input.jobId || typeof input.jobId !== \"string\" || input.jobId.trim() === \"\") {\n throw new ValidationError(\n \"Job ID is required and must be a non-empty string.\",\n this.constructor.name,\n );\n }\n\n try {\n // Retrieve the job first to check its status before attempting cancellation\n const job = await this.pipeline.getJob(input.jobId);\n\n if (!job) {\n logger.warn(`❓ [CancelJobTool] Job not found: ${input.jobId}`);\n throw new ToolError(\n `Job with ID ${input.jobId} not found.`,\n this.constructor.name,\n );\n }\n\n // Check if the job is already in a final state\n if (\n job.status === PipelineJobStatus.COMPLETED || // Use enum member\n job.status === PipelineJobStatus.FAILED || // Use enum member\n job.status === PipelineJobStatus.CANCELLED // Use enum member\n ) {\n logger.debug(`Job ${input.jobId} is already in a final state: ${job.status}.`);\n return {\n message: `Job ${input.jobId} is already ${job.status}. No action taken.`,\n finalStatus: job.status,\n };\n }\n\n // Attempt cancellation\n await this.pipeline.cancelJob(input.jobId);\n\n // Re-fetch the job to confirm status change (or check status directly if cancelJob returned it)\n // PipelineManager.cancelJob doesn't return status, so re-fetch is needed for confirmation.\n const updatedJob = await this.pipeline.getJob(input.jobId);\n const finalStatus = updatedJob?.status ?? \"UNKNOWN (job disappeared?)\";\n\n logger.debug(\n `Cancellation requested for job ${input.jobId}. Current status: ${finalStatus}`,\n );\n return {\n message: `Cancellation requested for job ${input.jobId}. Current status: ${finalStatus}.`,\n finalStatus,\n };\n } catch (error) {\n logger.error(`❌ Error cancelling job ${input.jobId}: ${error}`);\n throw new ToolError(\n `Failed to cancel job ${input.jobId}: ${\n error instanceof Error ? error.message : String(error)\n }`,\n this.constructor.name,\n );\n }\n }\n}\n","import type { AutoDetectFetcher, RawContent } from \"../scraper/fetcher\";\nimport { PipelineFactory } from \"../scraper/pipelines/PipelineFactory\";\nimport type { ContentPipeline, PipelineResult } from \"../scraper/pipelines/types\";\nimport { ScrapeMode } from \"../scraper/types\";\nimport { convertToString } from \"../scraper/utils/buffer\";\nimport { resolveCharset } from \"../scraper/utils/charset\";\nimport type { AppConfig } from \"../utils/config\";\nimport { ChallengeError, RenderError } from \"../utils/errors\";\nimport { logger } from \"../utils/logger\";\nimport { ToolError, ValidationError } from \"./errors\";\n\nexport interface FetchUrlToolOptions {\n /**\n * The URL to fetch and convert to markdown.\n * Must be a valid HTTP/HTTPS URL or file:// URL.\n */\n url: string;\n\n /**\n * Whether to follow HTTP redirects.\n * @default true\n */\n followRedirects?: boolean;\n\n /**\n * Determines the HTML processing strategy.\n * - 'fetch': Use a simple DOM parser (faster, less JS support).\n * - 'playwright': Use a headless browser (slower, full JS support).\n * - 'auto': Automatically select the best strategy (currently defaults to 'playwright').\n * @default ScrapeMode.Auto\n */\n scrapeMode?: ScrapeMode;\n\n /**\n * Custom HTTP headers to send with the request (e.g., for authentication).\n * Keys are header names, values are header values.\n */\n headers?: Record<string, string>;\n}\n\n/**\n * Tool for fetching a single URL and converting its content to Markdown.\n * Unlike scrape_docs, this tool only processes one page without crawling\n * or storing the content.\n *\n * Supports both HTTP/HTTPS URLs and local file URLs (file://).\n */\nexport class FetchUrlTool {\n /**\n * AutoDetectFetcher handles all URL types and fallback logic automatically.\n */\n private readonly fetcher: AutoDetectFetcher;\n /**\n * Collection of pipelines that will be tried in order for processing content.\n * The first pipeline that can process the content type will be used.\n * Currently includes HtmlPipeline, MarkdownPipeline, and TextPipeline (as fallback).\n */\n private readonly pipelines: ContentPipeline[];\n\n constructor(fetcher: AutoDetectFetcher, config: AppConfig) {\n this.fetcher = fetcher;\n // Use the central factory to ensure consistent pipeline configuration across the system\n this.pipelines = PipelineFactory.createStandardPipelines(config);\n }\n\n /**\n * Fetches content from a URL and converts it to Markdown.\n * Supports both HTTP/HTTPS URLs and local file URLs (file://).\n * @returns The processed Markdown content\n * @throws {ToolError} If fetching or processing fails\n */\n async execute(options: FetchUrlToolOptions): Promise<string> {\n const { url, scrapeMode = ScrapeMode.Auto, headers } = options;\n\n if (!this.fetcher.canFetch(url)) {\n throw new ValidationError(\n `Invalid URL: ${url}. Must be an HTTP/HTTPS URL or a file:// URL.`,\n this.constructor.name,\n );\n }\n\n try {\n logger.info(`📡 Fetching ${url}...`);\n\n const fetchOptions = {\n followRedirects: options.followRedirects ?? true,\n maxRetries: 3,\n headers, // propagate custom headers\n };\n\n // AutoDetectFetcher handles all fallback logic automatically\n const rawContent: RawContent = await this.fetcher.fetch(url, fetchOptions);\n\n logger.info(\"🔄 Processing content...\");\n\n let processed: Awaited<PipelineResult> | undefined;\n for (const pipeline of this.pipelines) {\n if (pipeline.canProcess(rawContent.mimeType, rawContent.content)) {\n processed = await pipeline.process(\n rawContent,\n {\n url,\n library: \"\",\n version: \"\",\n maxDepth: 0,\n maxPages: 1,\n maxConcurrency: 1,\n scope: \"subpages\",\n followRedirects: options.followRedirects ?? true,\n excludeSelectors: undefined,\n ignoreErrors: false,\n scrapeMode,\n headers, // propagate custom headers\n },\n this.fetcher,\n );\n break;\n }\n }\n\n if (!processed) {\n logger.warn(\n `⚠️ Unsupported content type \"${rawContent.mimeType}\" for ${url}. Returning raw content.`,\n );\n // Use proper charset detection for unsupported content types\n const resolvedCharset = resolveCharset(\n rawContent.charset,\n rawContent.content,\n rawContent.mimeType,\n );\n const contentString = convertToString(rawContent.content, resolvedCharset);\n return contentString;\n }\n\n for (const err of processed.errors ?? []) {\n logger.warn(`⚠️ Processing error for ${url}: ${err.message}`);\n }\n\n if (typeof processed.textContent !== \"string\" || !processed.textContent.trim()) {\n throw new ToolError(\n `Processing resulted in empty content for ${url}`,\n this.constructor.name,\n );\n }\n\n logger.info(`✅ Successfully processed ${url}`);\n return processed.textContent;\n } catch (error) {\n // Preserve ToolError as it already has user-friendly messages, wrap others\n if (error instanceof ToolError) {\n throw error;\n }\n\n // The generic advice below would send the user checking a URL that is\n // fine; name the block instead.\n if (error instanceof ChallengeError) {\n throw new ToolError(\n `Unable to fetch the URL \"${url}\": the site answered with a ${error.challengeType} bot challenge instead of the page, which cannot be passed automatically.`,\n this.constructor.name,\n );\n }\n\n // The page was fetched; only the browser failed, so the URL is not the problem.\n if (error instanceof RenderError) {\n throw new ToolError(\n `${error.message}. Use scrape mode \"auto\" to read the page as fetched instead.`,\n this.constructor.name,\n );\n }\n\n throw new ToolError(\n `Unable to fetch or process the URL \"${url}\". Please verify the URL is correct and accessible.`,\n this.constructor.name,\n );\n } finally {\n // Cleanup all pipelines and fetcher to prevent resource leaks (e.g., browser instances)\n await Promise.allSettled([\n ...this.pipelines.map((pipeline) => pipeline.close()),\n this.fetcher.close(),\n ]);\n }\n }\n}\n","import type { IDocumentManagement } from \"../store/trpc/interfaces\";\nimport { ValidationError } from \"./errors\";\n\nexport interface FindVersionToolOptions {\n library: string;\n targetVersion?: string;\n}\n\nexport interface FindVersionToolResult {\n bestMatch: string | null;\n hasUnversioned: boolean;\n message: string;\n}\n\n/**\n * Tool for finding the best matching version of a library in the store.\n * Supports exact version matches and X-Range patterns (e.g., '5.x', '5.2.x').\n */\nexport class FindVersionTool {\n private docService: IDocumentManagement;\n\n constructor(docService: IDocumentManagement) {\n this.docService = docService;\n }\n\n /**\n * Executes the tool to find the best matching version and checks for unversioned docs.\n * @returns A structured object with the best match, unversioned status, and descriptive message.\n * @throws {ValidationError} If the library parameter is invalid.\n * @throws {VersionNotFoundInStoreError} If no matching versions or unversioned docs are found.\n */\n async execute(options: FindVersionToolOptions): Promise<FindVersionToolResult> {\n const { library, targetVersion } = options;\n\n // Validate input\n if (!library || typeof library !== \"string\" || library.trim() === \"\") {\n throw new ValidationError(\n \"Library name is required and must be a non-empty string.\",\n this.constructor.name,\n );\n }\n\n const libraryAndVersion = `${library}${targetVersion ? `@${targetVersion}` : \"\"}`;\n\n // Let VersionNotFoundInStoreError bubble up instead of catching it\n const { bestMatch, hasUnversioned } = await this.docService.findBestVersion(\n library,\n targetVersion,\n );\n\n let message = \"\";\n if (bestMatch) {\n message = `Best match: ${bestMatch}.`;\n if (hasUnversioned) {\n message += \" Unversioned docs also available.\";\n }\n } else if (hasUnversioned) {\n message = `No matching version found for ${libraryAndVersion}, but unversioned docs exist.`;\n } else {\n // This case should ideally be caught by VersionNotFoundInStoreError,\n // but added for completeness.\n message = `No matching version or unversioned documents found for ${libraryAndVersion}.`;\n }\n\n return {\n bestMatch,\n hasUnversioned,\n message,\n };\n }\n}\n","import type { IPipeline } from \"../pipeline/trpc/interfaces\";\nimport type { PipelineJobStatus } from \"../pipeline/types\";\nimport type { VersionStatus } from \"../store/types\";\nimport { ToolError, ValidationError } from \"./errors\";\n\n/**\n * Input parameters for the GetJobInfoTool.\n */\nexport interface GetJobInfoInput {\n /** The ID of the job to retrieve info for. */\n jobId: string;\n}\n\n/**\n * Simplified information about a pipeline job for external use.\n */\nexport interface JobInfo {\n id: string;\n library: string;\n version: string | null;\n status: PipelineJobStatus; // Pipeline status (for compatibility)\n dbStatus?: VersionStatus; // Database status (enhanced)\n createdAt: string;\n startedAt: string | null;\n finishedAt: string | null;\n error: string | null;\n // Progress information from database\n progress?: {\n pages: number;\n /** Pages that produced stored content. Null for jobs predating this counter. */\n pagesIndexed: number | null;\n totalPages: number;\n totalDiscovered: number;\n };\n // Additional database fields\n updatedAt?: string;\n errorMessage?: string; // Database error message\n}\n\n/**\n * Response structure for the GetJobInfoTool.\n */\nexport interface GetJobInfoToolResponse {\n job: JobInfo;\n}\n\n/**\n * Tool for retrieving simplified information about a specific pipeline job.\n */\nexport class GetJobInfoTool {\n private pipeline: IPipeline;\n\n /**\n * Creates an instance of GetJobInfoTool.\n * @param pipeline The pipeline instance.\n */\n constructor(pipeline: IPipeline) {\n this.pipeline = pipeline;\n }\n\n /**\n * Executes the tool to retrieve simplified info for a specific job using enhanced PipelineJob interface.\n * @param input - The input parameters, containing the jobId.\n * @returns A promise that resolves with the simplified job info.\n * @throws {ValidationError} If the jobId is invalid.\n * @throws {ToolError} If the job is not found.\n */\n async execute(input: GetJobInfoInput): Promise<GetJobInfoToolResponse> {\n // Validate input\n if (!input.jobId || typeof input.jobId !== \"string\" || input.jobId.trim() === \"\") {\n throw new ValidationError(\n \"Job ID is required and must be a non-empty string.\",\n this.constructor.name,\n );\n }\n\n const job = await this.pipeline.getJob(input.jobId);\n\n if (!job) {\n throw new ToolError(`Job with ID ${input.jobId} not found.`, this.constructor.name);\n }\n\n // Transform the job into a simplified object using enhanced PipelineJob interface\n const jobInfo: JobInfo = {\n id: job.id,\n library: job.library,\n version: job.version,\n status: job.status,\n dbStatus: job.versionStatus,\n createdAt: job.createdAt.toISOString(),\n startedAt: job.startedAt?.toISOString() ?? null,\n finishedAt: job.finishedAt?.toISOString() ?? null,\n error: job.error?.message ?? null,\n progress:\n job.progressMaxPages && job.progressMaxPages > 0\n ? {\n pages: job.progressPages || 0,\n pagesIndexed:\n job.progress?.pagesIndexed ?? job.progressPagesIndexed ?? null,\n totalPages: job.progressMaxPages,\n totalDiscovered: job.progress?.totalDiscovered || job.progressMaxPages,\n }\n : undefined,\n updatedAt: job.updatedAt?.toISOString(),\n errorMessage: job.errorMessage ?? undefined,\n };\n\n return { job: jobInfo };\n }\n}\n","import type { IPipeline } from \"../pipeline/trpc/interfaces\";\nimport type { PipelineJob, PipelineJobStatus } from \"../pipeline/types\";\nimport type { JobInfo } from \"./GetJobInfoTool\"; // Import JobInfo\n\n/**\n * Input parameters for the ListJobsTool.\n */\nexport interface ListJobsInput {\n /** Optional status to filter jobs by. */\n status?: PipelineJobStatus;\n}\n\n/**\n * Response structure for the ListJobsTool.\n */\nexport interface ListJobsToolResponse {\n jobs: JobInfo[];\n}\n\n/**\n * Tool for listing pipeline jobs managed by the pipeline.\n * Allows filtering jobs by their status.\n */\nexport class ListJobsTool {\n private pipeline: IPipeline;\n\n /**\n * Creates an instance of ListJobsTool.\n * @param pipeline The pipeline instance.\n */\n constructor(pipeline: IPipeline) {\n this.pipeline = pipeline;\n }\n\n /**\n * Executes the tool to retrieve a list of pipeline jobs using single source of truth.\n * @param input - The input parameters, optionally including a status filter.\n * @returns A promise that resolves with the list of simplified job objects.\n */\n async execute(input: ListJobsInput): Promise<ListJobsToolResponse> {\n const jobs = await this.pipeline.getJobs(input.status);\n\n // Transform jobs into simplified objects using enhanced PipelineJob interface\n const simplifiedJobs: JobInfo[] = jobs.map((job: PipelineJob): JobInfo => {\n return {\n id: job.id,\n library: job.library,\n version: job.version,\n status: job.status,\n dbStatus: job.versionStatus,\n createdAt: job.createdAt.toISOString(),\n startedAt: job.startedAt?.toISOString() ?? null,\n finishedAt: job.finishedAt?.toISOString() ?? null,\n error: job.error?.message ?? null,\n progress:\n job.progressMaxPages && job.progressMaxPages > 0\n ? {\n pages: job.progressPages || 0,\n pagesIndexed:\n job.progress?.pagesIndexed ?? job.progressPagesIndexed ?? null,\n totalPages: job.progressMaxPages,\n totalDiscovered: job.progress?.totalDiscovered || job.progressMaxPages,\n }\n : undefined,\n updatedAt: job.updatedAt?.toISOString(),\n errorMessage: job.errorMessage ?? undefined,\n };\n });\n\n return { jobs: simplifiedJobs };\n }\n}\n","import type { IDocumentManagement } from \"../store/trpc/interfaces\";\nimport type { VersionStatus, VersionSummary } from \"../store/types\";\n\n// Define the structure for the tool's output, using the detailed version info\nexport interface LibraryInfo {\n name: string;\n versions: Array<{\n id: number;\n version: string;\n documentCount: number;\n uniqueUrlCount: number;\n indexedAt: string | null;\n status: VersionStatus;\n // Progress is omitted for COMPLETED versions to reduce noise\n progress?: { pages: number; maxPages: number };\n sourceUrl?: string | null;\n preserveHashes?: boolean;\n }>;\n}\n\nexport interface ListLibrariesResult {\n libraries: LibraryInfo[];\n}\n\n/**\n * Tool for listing all available libraries and their indexed versions in the store.\n */\nexport class ListLibrariesTool {\n private docService: IDocumentManagement;\n\n constructor(docService: IDocumentManagement) {\n this.docService = docService;\n }\n\n async execute(_options?: Record<string, never>): Promise<ListLibrariesResult> {\n // docService.listLibraries() now returns the detailed structure directly\n const rawLibraries = await this.docService.listLibraries();\n\n // The structure returned by listLibraries already matches LibraryInfo[]\n // No complex mapping is needed here anymore, just ensure the names match\n const libraries: LibraryInfo[] = rawLibraries.map(({ library, versions }) => ({\n name: library,\n versions: versions.map((v: VersionSummary) => ({\n id: v.id,\n version: v.ref.version,\n documentCount: v.counts.documents,\n uniqueUrlCount: v.counts.uniqueUrls,\n indexedAt: v.indexedAt,\n status: v.status,\n ...(v.progress ? { progress: v.progress } : undefined),\n sourceUrl: v.sourceUrl,\n preserveHashes: v.preserveHashes,\n })),\n }));\n\n return { libraries };\n }\n}\n","import type { IDocumentManagement } from \"../store/trpc/interfaces\";\nimport type { ListPagesResult } from \"../store/types\";\nimport { ValidationError } from \"./errors\";\n\nexport interface ListPagesToolOptions {\n library: string;\n version?: string;\n contains?: string;\n limit?: number;\n offset?: number;\n}\n\nexport type ListPagesToolResult = ListPagesResult;\n\n/**\n * Tool for listing indexed pages and documentation sitemap for a library version.\n */\nexport class ListPagesTool {\n private docService: IDocumentManagement;\n\n constructor(docService: IDocumentManagement) {\n this.docService = docService;\n }\n\n async execute(options: ListPagesToolOptions): Promise<ListPagesToolResult> {\n const { library, version, contains, offset = 0 } = options;\n\n if (!library || typeof library !== \"string\" || library.trim() === \"\") {\n throw new ValidationError(\n \"Library name is required and must be a non-empty string.\",\n this.constructor.name,\n );\n }\n\n let limit = options.limit ?? 50;\n if (!Number.isFinite(limit) || limit <= 0) {\n limit = 50;\n } else if (limit > 200) {\n limit = 200;\n }\n\n const safeOffset =\n offset !== undefined && Number.isFinite(offset) && offset >= 0\n ? Math.floor(offset)\n : 0;\n\n return this.docService.listPages(library.trim(), version?.trim(), {\n contains: contains?.trim(),\n limit,\n offset: safeOffset,\n });\n }\n}\n","import type { IDocumentManagement } from \"../store/trpc/interfaces\";\nimport type { PageContentResult } from \"../store/types\";\nimport { ValidationError } from \"./errors\";\n\nexport interface ReadPageToolOptions {\n library: string;\n pathOrUrl: string;\n version?: string;\n startChunk?: number;\n maxChars?: number;\n}\n\nexport type ReadPageToolResult = PageContentResult;\n\n/**\n * Strips what agents tend to copy along with a link: the HTML-escaped `<…>`\n * wrapper, angle brackets and quotes, `./` and `../` prefixes, and Windows\n * backslashes. Percent-encoding is left as given.\n */\nfunction cleanPageInput(input: string): string {\n let value = input.trim();\n if (/^<.*>$/i.test(value)) {\n value = value.slice(4, -4).replace(/&/gi, \"&\");\n }\n return value\n .replace(/\\\\/g, \"/\")\n .replace(/^[<\"']+|[>\"']+$/g, \"\")\n .trim()\n .replace(/^(\\.\\.?\\/)+/, \"\");\n}\n\n/**\n * Tool for reading a stored documentation page without scraping it again.\n * Long pages are read in windows of whole chunks, continued with `startChunk`.\n */\nexport class ReadPageTool {\n private docService: IDocumentManagement;\n\n constructor(docService: IDocumentManagement) {\n this.docService = docService;\n }\n\n async execute(options: ReadPageToolOptions): Promise<ReadPageToolResult> {\n const { library, pathOrUrl, version, startChunk, maxChars } = options;\n\n if (!library || typeof library !== \"string\" || library.trim() === \"\") {\n throw new ValidationError(\n \"Library name is required and must be a non-empty string.\",\n this.constructor.name,\n );\n }\n\n const target = typeof pathOrUrl === \"string\" ? cleanPageInput(pathOrUrl) : \"\";\n if (!target) {\n throw new ValidationError(\n \"Path or URL is required and must be a non-empty string.\",\n this.constructor.name,\n );\n }\n\n if (maxChars !== undefined && (!Number.isFinite(maxChars) || maxChars <= 0)) {\n throw new ValidationError(\n \"maxChars must be a positive number if provided.\",\n this.constructor.name,\n );\n }\n\n if (startChunk !== undefined && (!Number.isInteger(startChunk) || startChunk < 0)) {\n throw new ValidationError(\n \"startChunk must be a non-negative integer if provided.\",\n this.constructor.name,\n );\n }\n\n return this.docService.getPageContent(library.trim(), version?.trim(), target, {\n startChunk,\n maxChars,\n });\n }\n}\n","import type { IPipeline } from \"../pipeline/trpc/interfaces\";\nimport { normalizeVersionLabel } from \"../store/types\";\nimport { logger } from \"../utils/logger\";\n\nexport interface RefreshVersionToolOptions {\n library: string;\n version?: string | null; // Make version optional\n preserveHashes?: boolean;\n /** If false, returns jobId immediately without waiting. Defaults to true. */\n waitForCompletion?: boolean;\n /** Called with the job's id once it is enqueued, before any waiting. */\n onJobEnqueued?: (jobId: string) => void;\n}\n\nexport interface RefreshResult {\n /** Indicates the number of pages refreshed if waitForCompletion was true and the job succeeded. May be 0 or inaccurate if job failed or waitForCompletion was false. */\n pagesRefreshed: number;\n}\n\n/** Return type for RefreshVersionTool.execute */\nexport type RefreshExecuteResult = RefreshResult | { jobId: string };\n\n/**\n * Tool for refreshing an existing library version by re-scraping all pages\n * and using ETag comparison to skip unchanged content.\n */\nexport class RefreshVersionTool {\n private pipeline: IPipeline;\n\n constructor(pipeline: IPipeline) {\n this.pipeline = pipeline;\n }\n\n async execute(options: RefreshVersionToolOptions): Promise<RefreshExecuteResult> {\n const {\n library,\n version,\n preserveHashes,\n waitForCompletion = true,\n onJobEnqueued,\n } = options;\n\n // Labels that are not semantic versions, such as \"stable\", are legitimate.\n const internalVersion = normalizeVersionLabel(version);\n\n // Use the injected pipeline instance\n const pipeline = this.pipeline;\n\n // Normalize pipeline version argument: use null for unversioned to be explicit cross-platform\n const refreshVersion: string | null = internalVersion === \"\" ? null : internalVersion;\n\n // Enqueue the refresh job using the injected pipeline\n const jobId = await pipeline.enqueueRefreshJob(library, refreshVersion, {\n preserveHashes,\n });\n onJobEnqueued?.(jobId);\n\n // Conditionally wait for completion\n if (waitForCompletion) {\n try {\n await pipeline.waitForJobCompletion(jobId);\n // Fetch final job state to get status and potentially final page count\n const finalJob = await pipeline.getJob(jobId);\n const finalPagesRefreshed = finalJob?.progress?.pagesScraped ?? 0; // Get count from final job state\n logger.debug(\n `Refresh job ${jobId} finished with status ${finalJob?.status}. Pages refreshed: ${finalPagesRefreshed}`,\n );\n return {\n pagesRefreshed: finalPagesRefreshed,\n };\n } catch (error) {\n logger.error(`❌ Refresh job ${jobId} failed or was cancelled: ${error}`);\n throw error; // Re-throw so the caller knows it failed\n }\n }\n\n // If not waiting, return the job ID immediately\n return { jobId };\n }\n}\n","import type { IPipeline } from \"../pipeline/trpc/interfaces\";\nimport type { IDocumentManagement } from \"../store/trpc/interfaces\";\nimport { logger } from \"../utils/logger\";\nimport { ToolError, ValidationError } from \"./errors\";\n\n/**\n * Represents the arguments for the remove_docs tool.\n * The MCP server should validate the input against RemoveToolInputSchema before calling execute.\n */\nexport interface RemoveToolArgs {\n library: string;\n version?: string;\n}\n\n/**\n * Tool to remove indexed documentation for a specific library version.\n * This class provides the core logic, intended to be called by the McpServer.\n */\nexport class RemoveTool {\n /**\n * @param documentManagementService Checks the library exists, and removes the\n * version when there is no pipeline.\n * @param pipeline Cancels its job for the version and removes it. Without one\n * nothing is cancelled here: a CLI process runs no jobs, and a remote store\n * has the worker cancel its own job when it removes the version.\n */\n constructor(\n private readonly documentManagementService: IDocumentManagement,\n private readonly pipeline: IPipeline | undefined,\n ) {}\n\n /**\n * Executes the tool to remove the specified library version completely.\n * Stops the version's jobs and waits until they have ended before deleting,\n * when there is a pipeline to see them.\n * Removes all documents, the version record, and the library if no other versions exist.\n */\n async execute(args: RemoveToolArgs): Promise<{ message: string }> {\n const { library, version } = args;\n\n // Validate input\n if (!library || typeof library !== \"string\" || library.trim() === \"\") {\n throw new ValidationError(\n \"Library name is required and must be a non-empty string.\",\n this.constructor.name,\n );\n }\n\n logger.info(`🗑️ Removing library: ${library}${version ? `@${version}` : \"\"}`);\n\n try {\n // Validate that the library exists before attempting removal\n await this.documentManagementService.validateLibraryExists(library);\n\n // The pipeline cancels its job for the version and removes it, locked\n // against an enqueue of the same version. Without one, this process runs\n // no jobs, and a remote store has the worker do the same.\n await (this.pipeline ?? this.documentManagementService).removeVersion(\n library,\n version,\n );\n\n const message = `Successfully removed ${library}${version ? `@${version}` : \"\"}.`;\n logger.info(`✅ ${message}`);\n // Return a simple success object, the McpServer will format the final response\n return { message };\n } catch (error) {\n // If it's already a ToolError or other known error types, re-throw as is\n if (error instanceof ToolError) {\n throw error;\n }\n\n const errorMessage = `Failed to remove ${library}${version ? `@${version}` : \"\"}: ${error instanceof Error ? error.message : String(error)}`;\n logger.error(`❌ Error removing library: ${errorMessage}`);\n // Re-throw the error for the McpServer to handle and format\n throw new ToolError(errorMessage, this.constructor.name);\n }\n }\n}\n","import type { EnqueueScrapeOptions, IPipeline } from \"../pipeline/trpc/interfaces\";\nimport { ScrapeMode } from \"../scraper/types\";\nimport { normalizeVersionLabel } from \"../store/types\";\nimport type { AppConfig } from \"../utils/config\";\nimport { logger } from \"../utils/logger\";\n\nexport interface ScrapeToolOptions {\n library: string;\n version?: string | null; // Make version optional\n url: string;\n options?: {\n maxPages?: number;\n maxDepth?: number;\n /**\n * Defines the allowed crawling boundary relative to the starting URL\n * - 'subpages': Only crawl URLs on the same hostname and within the same starting path (default)\n * - 'hostname': Crawl any URL on the same hostname, regardless of path\n * - 'domain': Crawl any URL on the same top-level domain, including subdomains\n */\n scope?: \"subpages\" | \"hostname\" | \"domain\";\n /**\n * Controls whether HTTP redirects (3xx responses) should be followed\n * - When true: Redirects are followed automatically (default)\n * - When false: A RedirectError is thrown when a 3xx response is received\n */\n followRedirects?: boolean;\n maxConcurrency?: number; // Note: Concurrency is now set when PipelineManager is created\n ignoreErrors?: boolean;\n /**\n * Determines the HTML processing strategy.\n * - 'fetch': Use a simple DOM parser (faster, less JS support).\n * - 'playwright': Use a headless browser (slower, full JS support).\n * - 'auto': Automatically select the best strategy (currently defaults to 'playwright').\n * @default ScrapeMode.Auto\n */\n scrapeMode?: ScrapeMode;\n /**\n * Patterns for including URLs during scraping. If not set, all are included by default.\n * Regex patterns must be wrapped in slashes, e.g. /pattern/.\n */\n includePatterns?: string[];\n /**\n * Patterns for excluding URLs during scraping. Exclude takes precedence over include.\n * If not specified, default patterns exclude common files (CHANGELOG.md, LICENSE, etc.)\n * and folders (archive, deprecated, i18n locales, etc.).\n * Regex patterns must be wrapped in slashes, e.g. /pattern/.\n */\n excludePatterns?: string[];\n /** Preserve URL hash fragments for hash-routed SPA documentation sites. */\n preserveHashes?: boolean;\n /**\n * Custom HTTP headers to send with each request (e.g., for authentication).\n * Keys are header names, values are header values.\n */\n headers?: Record<string, string>;\n /**\n * If true, clears existing documents for the library version before scraping.\n * If false, appends to the existing documents.\n * @default true\n */\n clean?: boolean;\n };\n /** If false, returns jobId immediately without waiting. Defaults to true. */\n waitForCompletion?: boolean;\n /** Called with the job's id once it is enqueued, before any waiting. */\n onJobEnqueued?: (jobId: string) => void;\n /**\n * Rebuild the version when it already exists. Without it, scraping an\n * existing library version is rejected rather than clearing it.\n * @default false\n */\n replace?: boolean;\n}\n\nexport interface ScrapeResult {\n /** Indicates the number of pages scraped if waitForCompletion was true and the job succeeded. May be 0 or inaccurate if job failed or waitForCompletion was false. */\n pagesScraped: number;\n}\n\n/** Return type for ScrapeTool.execute */\nexport type ScrapeExecuteResult = ScrapeResult | { jobId: string };\n\n/**\n * Tool for enqueuing documentation scraping jobs via the pipeline.\n */\nexport class ScrapeTool {\n private pipeline: IPipeline;\n private readonly scraperConfig: AppConfig[\"scraper\"];\n\n constructor(pipeline: IPipeline, config: AppConfig[\"scraper\"]) {\n this.pipeline = pipeline;\n this.scraperConfig = config;\n }\n\n async execute(options: ScrapeToolOptions): Promise<ScrapeExecuteResult> {\n const {\n library,\n version,\n url,\n options: scraperOptions,\n waitForCompletion = true,\n replace = false,\n onJobEnqueued,\n } = options;\n\n // Store initialization and manager start should happen externally\n\n // Labels that are not semantic versions, such as \"stable\", are legitimate.\n const internalVersion = normalizeVersionLabel(version);\n\n // Use the injected pipeline instance\n const pipeline = this.pipeline;\n\n // Normalize pipeline version argument: use null for unversioned to be explicit cross-platform\n const enqueueVersion: string | null = internalVersion === \"\" ? null : internalVersion;\n\n // Only an explicit replace is passed on; otherwise the pipeline applies its\n // own default (\"reject-version\"), so that default lives in one place.\n const enqueue: EnqueueScrapeOptions = { onExisting: replace ? \"replace\" : undefined };\n\n // Enqueue the job using the injected pipeline\n const jobId = await pipeline.enqueueScrapeJob(\n library,\n enqueueVersion,\n {\n url: url,\n library: library,\n version: internalVersion,\n scope: scraperOptions?.scope ?? \"subpages\",\n followRedirects: scraperOptions?.followRedirects ?? true,\n maxPages: scraperOptions?.maxPages ?? this.scraperConfig.maxPages,\n maxDepth: scraperOptions?.maxDepth ?? this.scraperConfig.maxDepth,\n maxConcurrency:\n scraperOptions?.maxConcurrency ?? this.scraperConfig.maxConcurrency,\n ignoreErrors: scraperOptions?.ignoreErrors ?? true,\n scrapeMode: scraperOptions?.scrapeMode ?? ScrapeMode.Auto, // Pass scrapeMode enum\n includePatterns: scraperOptions?.includePatterns,\n excludePatterns: scraperOptions?.excludePatterns,\n preserveHashes: scraperOptions?.preserveHashes,\n headers: scraperOptions?.headers, // <-- propagate headers\n clean: scraperOptions?.clean, // <-- propagate clean option\n },\n enqueue,\n );\n onJobEnqueued?.(jobId);\n\n // Conditionally wait for completion\n if (waitForCompletion) {\n try {\n await pipeline.waitForJobCompletion(jobId);\n // Fetch final job state to get status and potentially final page count\n const finalJob = await pipeline.getJob(jobId);\n const finalPagesScraped = finalJob?.progress?.pagesScraped ?? 0; // Get count from final job state\n logger.debug(\n `Job ${jobId} finished with status ${finalJob?.status}. Pages scraped: ${finalPagesScraped}`,\n );\n return {\n pagesScraped: finalPagesScraped,\n };\n } catch (error) {\n logger.error(`❌ Job ${jobId} failed or was cancelled: ${error}`);\n throw error; // Re-throw so the caller knows it failed\n }\n // No finally block needed to stop pipeline, as it's managed externally\n }\n\n // If not waiting, return the job ID immediately\n return { jobId };\n }\n}\n","import { VersionNotFoundInStoreError } from \"../store\";\nimport type { IDocumentManagement } from \"../store/trpc/interfaces\";\nimport { libraryNamesMatch, type StoreSearchResult } from \"../store/types\";\nimport { logger } from \"../utils/logger\";\nimport { ValidationError } from \"./errors\";\n\nexport interface SearchToolOptions {\n library: string;\n version?: string;\n query: string;\n limit?: number;\n exactMatch?: boolean;\n}\n\nexport interface SearchToolResultError {\n message: string;\n availableVersions?: Array<{\n version: string;\n documentCount: number;\n uniqueUrlCount: number;\n indexedAt: string | null;\n }>;\n suggestions?: string[]; // Specific to LibraryNotFoundInStoreError\n}\n\nexport interface SearchToolResult {\n results: StoreSearchResult[];\n}\n\n/**\n * Tool for searching indexed documentation.\n * Supports exact version matches and version range patterns.\n * Returns available versions when requested version is not found.\n */\nexport class SearchTool {\n private docService: IDocumentManagement;\n\n constructor(docService: IDocumentManagement) {\n this.docService = docService;\n }\n\n async execute(options: SearchToolOptions): Promise<SearchToolResult> {\n const { library, version, query, limit = 5, exactMatch = false } = options;\n\n // Validate required inputs\n if (!library || typeof library !== \"string\" || library.trim() === \"\") {\n throw new ValidationError(\n \"Library name is required and must be a non-empty string.\",\n this.constructor.name,\n );\n }\n\n if (!query || typeof query !== \"string\" || query.trim() === \"\") {\n throw new ValidationError(\n \"Query is required and must be a non-empty string.\",\n this.constructor.name,\n );\n }\n\n if (limit !== undefined && (typeof limit !== \"number\" || limit < 1 || limit > 100)) {\n throw new ValidationError(\n \"Limit must be a number between 1 and 100.\",\n this.constructor.name,\n );\n }\n\n // When exactMatch is true, version must be specified and not 'latest'\n if (exactMatch && (!version || version === \"latest\")) {\n // Get available *detailed* versions for error message\n await this.docService.validateLibraryExists(library);\n // Fetch detailed versions using listLibraries and find the specific library\n const allLibraries = await this.docService.listLibraries();\n const libraryInfo = allLibraries.find((lib) =>\n libraryNamesMatch(lib.library, library),\n );\n const availableVersions = libraryInfo\n ? libraryInfo.versions.map((v) => v.ref.version)\n : [];\n // Name the library as it is stored, not as the caller typed it\n throw new VersionNotFoundInStoreError(\n libraryInfo?.library ?? library,\n version ?? \"latest\",\n availableVersions,\n );\n }\n\n // Only for the log line and the exactMatch path; resolution takes `version`\n // as given so an omitted version stays distinct from a literal \"latest\".\n const resolvedVersion = version || \"latest\";\n\n logger.info(\n `🔍 Searching ${library}@${resolvedVersion} for: ${query}${exactMatch ? \" (exact match)\" : \"\"}`,\n );\n\n try {\n // 1. Validate library exists first\n await this.docService.validateLibraryExists(library);\n\n // 2. Proceed with version finding and searching\n let versionToSearch: string | null | undefined = resolvedVersion;\n\n if (!exactMatch) {\n // Pass the request through untouched. Substituting \"latest\" here would\n // change the answer, not just the wording: since labels resolve\n // literally first, a library holding a bucket named \"latest\" would\n // match that tag instead of its newest version, and search_docs would\n // disagree with find_version for the same request.\n const versionResult = await this.docService.findBestVersion(library, version);\n // bestMatch is null only when nothing resolved and unversioned content\n // exists; searchStore normalizes null to \"\" and searches that bucket.\n versionToSearch = versionResult.bestMatch;\n }\n // If exactMatch is true, versionToSearch remains the originally provided version.\n\n // Note: versionToSearch can be string | null | undefined here.\n // searchStore handles null/undefined by normalizing to \"\".\n const results = await this.docService.searchStore(\n library,\n versionToSearch,\n query,\n limit,\n );\n logger.info(`✅ Found ${results.length} matching results`);\n\n return { results };\n } catch (error) {\n logger.error(\n `❌ Search failed: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n throw error;\n }\n }\n}\n","/**\n * Helper utilities for constructing MCP tools with shared dependencies. Tools\n * are created with the resolved configuration supplied by the entrypoint to\n * avoid internal config loading.\n */\nimport type { IPipeline } from \"../pipeline/trpc/interfaces\";\nimport { AutoDetectFetcher } from \"../scraper/fetcher\";\nimport type { IDocumentManagement } from \"../store/trpc/interfaces\";\nimport {\n CancelJobTool,\n FetchUrlTool,\n FindVersionTool,\n GetJobInfoTool,\n ListJobsTool,\n ListLibrariesTool,\n ListPagesTool,\n ReadPageTool,\n RefreshVersionTool,\n RemoveTool,\n ScrapeTool,\n SearchTool,\n} from \"../tools\";\nimport type { AppConfig } from \"../utils/config\";\n\n/**\n * Interface for the shared tool instances.\n */\nexport interface McpServerTools {\n listLibraries: ListLibrariesTool;\n listPages: ListPagesTool;\n readPage: ReadPageTool;\n findVersion: FindVersionTool;\n scrape: ScrapeTool;\n refresh: RefreshVersionTool;\n search: SearchTool;\n listJobs: ListJobsTool;\n getJobInfo: GetJobInfoTool;\n cancelJob: CancelJobTool;\n remove: RemoveTool;\n fetchUrl: FetchUrlTool;\n}\n\n/**\n * Initializes and returns the shared tool instances.\n * This should be called after initializeServices has completed.\n * @param docService The initialized DocumentManagementService instance.\n * @param pipeline The initialized pipeline instance.\n * @param config The resolved configuration provided by the entrypoint.\n * @returns An object containing all instantiated tool instances.\n */\nexport async function initializeTools(\n docService: IDocumentManagement,\n pipeline: IPipeline,\n config: AppConfig,\n): Promise<McpServerTools> {\n const tools: McpServerTools = {\n listLibraries: new ListLibrariesTool(docService),\n listPages: new ListPagesTool(docService),\n readPage: new ReadPageTool(docService),\n findVersion: new FindVersionTool(docService),\n scrape: new ScrapeTool(pipeline, config.scraper),\n refresh: new RefreshVersionTool(pipeline),\n search: new SearchTool(docService),\n listJobs: new ListJobsTool(pipeline),\n getJobInfo: new GetJobInfoTool(pipeline),\n cancelJob: new CancelJobTool(pipeline),\n remove: new RemoveTool(docService, pipeline),\n fetchUrl: new FetchUrlTool(new AutoDetectFetcher(config.scraper), config),\n };\n\n return tools;\n}\n","/**\n * MCP service: registers the Streamable HTTP MCP endpoint on the application's\n * Fastify instance. It serves protocol revision 2026-07-28, and serves clients\n * on earlier, handshake-based revisions statelessly: each request is answered\n * by a fresh server instance, without a session, as the endpoint always has.\n *\n * Every request passes the same checks in a fixed order, and the first that\n * fails answers:\n *\n * 1. `Origin` (403), required by the transport spec to stop DNS rebinding;\n * 2. a CORS preflight, answered here and never authenticated, because\n * browsers send no credentials with it;\n * 3. the HTTP method (405 with `Allow: POST`);\n * 4. authentication, when enabled (401 with a discovery challenge);\n * 5. MCP processing, by the SDK's per-request handler.\n *\n * While authentication is off, it also serves the deprecated HTTP+SSE\n * transport (`GET /sse`, `POST /messages`) for handshake-era clients.\n */\n\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { toNodeHandler } from \"@modelcontextprotocol/node\";\nimport {\n type AuthInfo,\n bearerAuthChallengeResponse,\n createMcpHandler,\n type OAuthTokenVerifier,\n verifyBearerToken,\n} from \"@modelcontextprotocol/server\";\nimport { SSEServerTransport } from \"@modelcontextprotocol/server-legacy/sse\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport {\n type OriginPolicy,\n type OriginVerdict,\n setCorsPreflightHeaders,\n setCorsResponseHeaders,\n} from \"../app/originPolicy\";\nimport { missingTokenChallenge } from \"../auth/protectedResourceMetadata\";\nimport { createMcpServerFactory } from \"../mcp/mcpServer\";\nimport { initializeTools } from \"../mcp/tools\";\nimport type { IPipeline } from \"../pipeline/trpc/interfaces\";\nimport type { IDocumentManagement } from \"../store/trpc/interfaces\";\nimport type { AppConfig } from \"../utils/config\";\nimport { logger } from \"../utils/logger\";\nimport type { PublicLocation } from \"../utils/serverOrigin\";\n\n/** Path of the MCP endpoint, relative to the public URL. */\nexport const MCP_ENDPOINT_PATH = \"/mcp\";\n\n/** Path of the deprecated HTTP+SSE transport's event stream, relative to the public URL. */\nexport const LEGACY_SSE_PATH = \"/sse\";\n\n/** Authentication for the MCP endpoint. */\nexport interface McpEndpointAuth {\n /** Verifies bearer tokens; throws `OAuthError` for any rejection. */\n verifier: OAuthTokenVerifier;\n /** Metadata URL advertised in every challenge. */\n resourceMetadataUrl: string;\n}\n\n/** Everything the MCP endpoint needs from the application. */\nexport interface McpServiceDeps {\n docService: IDocumentManagement;\n pipeline: IPipeline;\n config: AppConfig;\n originPolicy: OriginPolicy;\n /** Where clients reach the server; the SSE message URL carries its base path. */\n location: PublicLocation;\n}\n\n/** Legacy SSE streams open at once; more connections get 503. */\nexport const LEGACY_SSE_MAX_SESSIONS = 100;\n\nfunction jsonRpcError(message: string) {\n return { jsonrpc: \"2.0\", error: { code: -32000, message }, id: null };\n}\n\n/** End a hijacked response with a JSON-RPC 500, or just end it once headers went out. */\nfunction endWithServerError(res: ServerResponse): void {\n if (res.headersSent) {\n res.end();\n return;\n }\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(jsonRpcError(\"Internal server error.\")));\n}\n\n/**\n * Answer 403 for a denied origin. For an allowed one, set the CORS headers.\n * @returns The verdict; the reply has been sent when it is `\"denied\"`.\n */\nfunction applyOriginPolicy(\n originPolicy: OriginPolicy,\n request: FastifyRequest,\n reply: FastifyReply,\n): OriginVerdict {\n const origin = request.headers.origin;\n const verdict = originPolicy.check(origin);\n if (verdict === \"denied\") {\n reply.code(403).send(jsonRpcError(\"Forbidden: origin not allowed.\"));\n } else if (verdict === \"allowed\" && origin !== undefined) {\n setCorsResponseHeaders(reply.raw, origin);\n }\n return verdict;\n}\n\n/** An `onRequest` hook that applies only the origin policy. */\nfunction createOriginCheck(originPolicy: OriginPolicy) {\n return async (request: FastifyRequest, reply: FastifyReply) => {\n applyOriginPolicy(originPolicy, request, reply);\n };\n}\n\n/**\n * Checks that run before the body is parsed: origin, preflight, method.\n * Answering from `onRequest` keeps the order independent of Fastify's body\n * parsing, which would otherwise reject some requests first.\n */\nfunction createPreflightChecks(originPolicy: OriginPolicy) {\n return async (request: FastifyRequest, reply: FastifyReply) => {\n const verdict = applyOriginPolicy(originPolicy, request, reply);\n if (verdict === \"denied\") {\n return reply;\n }\n\n const origin = request.headers.origin;\n if (\n request.method === \"OPTIONS\" &&\n verdict === \"allowed\" &&\n origin !== undefined &&\n request.headers[\"access-control-request-method\"] !== undefined\n ) {\n setCorsPreflightHeaders(reply.raw, {\n origin,\n methods: \"POST\",\n requestedHeaders: request.headers[\"access-control-request-headers\"],\n });\n return reply.code(204).send();\n }\n\n if (request.method !== \"POST\") {\n return reply\n .code(405)\n .header(\"Allow\", \"POST\")\n .send(jsonRpcError(\"Method not allowed.\"));\n }\n };\n}\n\n/**\n * Register the MCP endpoint on a Fastify server.\n *\n * @param server - The Fastify instance.\n * @param deps - Services and policy the endpoint needs.\n * @param auth - Authentication for the endpoint; omit to serve it without authentication.\n */\nexport async function registerMcpService(\n server: FastifyInstance,\n deps: McpServiceDeps,\n auth?: McpEndpointAuth,\n): Promise<void> {\n const tools = await initializeTools(deps.docService, deps.pipeline, deps.config);\n const createServer = createMcpServerFactory(tools, deps.config);\n const onerror = (error: Error) => logger.error(`❌ Error in MCP endpoint: ${error}`);\n const handleMcpRequest = toNodeHandler(\n createMcpHandler(createServer, { legacy: \"stateless\", onerror }),\n { onerror },\n );\n\n server.all(\n MCP_ENDPOINT_PATH,\n { onRequest: createPreflightChecks(deps.originPolicy) },\n async (request, reply) => {\n let authInfo: AuthInfo | undefined;\n if (auth) {\n const authorization = request.headers.authorization;\n if (!authorization || !/^Bearer\\s+\\S/i.test(authorization)) {\n return reply\n .code(401)\n .header(\"WWW-Authenticate\", missingTokenChallenge(auth.resourceMetadataUrl))\n .send({ error_description: \"A bearer token is required.\" });\n }\n try {\n authInfo = await verifyBearerToken(authorization, auth);\n } catch (error) {\n logger.debug(`MCP request rejected by token verification: ${error}`);\n return reply.send(bearerAuthChallengeResponse(error, auth));\n }\n }\n\n reply.hijack();\n const raw = request.raw as IncomingMessage & { auth?: AuthInfo };\n if (authInfo) {\n raw.auth = authInfo;\n }\n // The adapter answers 500 itself and reports the failure to `onerror`.\n await handleMcpRequest(raw, reply.raw, request.body);\n },\n );\n\n if (!auth) {\n registerLegacySseTransport(server, deps, createServer);\n }\n}\n\n/**\n * Register the deprecated HTTP+SSE transport: `GET /sse` opens an event stream\n * whose `endpoint` event names `<basePath>/messages?sessionId=…`, and clients\n * POST their messages there. Each stream gets its own MCP server instance.\n * Only registered while authentication is off: the transport has no way to\n * carry the challenge flow, and `/messages` would bypass it.\n */\nfunction registerLegacySseTransport(\n server: FastifyInstance,\n deps: McpServiceDeps,\n createServer: ReturnType<typeof createMcpServerFactory>,\n): void {\n const sessions = new Map<string, SSEServerTransport>();\n const messagesPath = `${deps.location.basePath}/messages`;\n let warned = false;\n let capWarned = false;\n\n server.get(\n LEGACY_SSE_PATH,\n { onRequest: createOriginCheck(deps.originPolicy) },\n async (request, reply) => {\n // Each stream holds an MCP server instance until the client leaves, so\n // cap them rather than let one client exhaust the process.\n if (sessions.size >= LEGACY_SSE_MAX_SESSIONS) {\n if (!capWarned) {\n capWarned = true;\n logger.warn(\n `⚠️ Refusing legacy SSE connections: ${LEGACY_SSE_MAX_SESSIONS} streams are already open.`,\n );\n }\n return reply\n .code(503)\n .header(\"Retry-After\", \"30\")\n .send(jsonRpcError(\"Too many open SSE streams.\"));\n }\n if (!warned) {\n warned = true;\n logger.warn(\n `⚠️ A client connected over the deprecated HTTP+SSE transport (/sse). It will be removed in a future major release; connect clients to ${deps.location.url}${MCP_ENDPOINT_PATH} instead.`,\n );\n }\n\n reply.hijack();\n const res = reply.raw;\n res.setHeader(\"X-Accel-Buffering\", \"no\");\n const transport = new SSEServerTransport(messagesPath, res);\n const mcpServer = createServer();\n sessions.set(transport.sessionId, transport);\n\n const keepAlive = setInterval(() => {\n if (!res.writableEnded) {\n res.write(\": keepalive\\n\\n\");\n }\n }, deps.config.server.heartbeatMs);\n res.on(\"close\", () => {\n clearInterval(keepAlive);\n sessions.delete(transport.sessionId);\n mcpServer.close().catch((error) => {\n logger.debug(`Closing legacy SSE session failed: ${error}`);\n });\n });\n\n try {\n await mcpServer.connect(transport);\n logger.debug(`Legacy SSE session opened: ${transport.sessionId} (${request.ip})`);\n } catch (error) {\n logger.error(`❌ Error opening legacy SSE stream: ${error}`);\n endWithServerError(res);\n }\n },\n );\n\n server.route({\n method: [\"POST\", \"OPTIONS\"],\n url: \"/messages\",\n onRequest: createPreflightChecks(deps.originPolicy),\n handler: async (request, reply) => {\n const { sessionId } = request.query as { sessionId?: string };\n const transport = sessionId ? sessions.get(sessionId) : undefined;\n if (!transport) {\n return reply.code(404).send(jsonRpcError(\"Unknown session.\"));\n }\n reply.hijack();\n try {\n await transport.handlePostMessage(request.raw, reply.raw, request.body);\n } catch (error) {\n logger.error(`❌ Error in legacy SSE message endpoint: ${error}`);\n endWithServerError(reply.raw);\n }\n },\n });\n\n // Open streams never finish on their own, so end them before Fastify waits\n // for in-flight requests on shutdown.\n server.addHook(\"preClose\", async () => {\n await Promise.all([...sessions.values()].map((transport) => transport.close()));\n });\n}\n","/**\n * Distilled, serializable snapshot of how the server process was started.\n *\n * `SystemInfo` is derived once from {@link AppServerConfig} (service\n * composition/runtime wiring) and {@link AppConfig} (resolved env/YAML/CLI\n * configuration) when the tRPC service is registered. It intentionally\n * contains no measured/live state — the goal is an honest reflection of the\n * running configuration, not a health probe. Live state (e.g. whether a\n * remote worker is currently connected) is threaded through the tRPC context\n * separately; see {@link ./appRouter}.\n */\nimport type { AppServerConfig } from \"../app/AppServerConfig\";\nimport type { AppConfig } from \"../utils/config\";\nimport { LEGACY_SSE_PATH, MCP_ENDPOINT_PATH } from \"./mcpService\";\n\n/** Which top-level services this process was started with. */\nexport interface SystemInfoServices {\n web: boolean;\n mcp: boolean;\n api: boolean;\n worker: boolean;\n}\n\n/**\n * How the pipeline worker is wired: embedded in this process, or delegated\n * to a remote worker reachable over HTTP/WebSocket.\n */\nexport type SystemInfoWorker =\n | { mode: \"embedded\"; maxConcurrency: number }\n | { mode: \"remote\"; url: string };\n\n/**\n * MCP protocol exposure. `endpoints` lists the paths the MCP server answers\n * on, relative to the public URL; `url` is the advertised MCP endpoint URL\n * clients connect to.\n */\nexport type SystemInfoMcp =\n | { enabled: true; endpoints: string[]; url: string }\n | { enabled: false; endpoints: string[] };\n\n/** OAuth2/OIDC authentication configuration. */\nexport interface SystemInfoAuth {\n enabled: boolean;\n /** The OIDC issuer URL, present only when auth is enabled and configured. */\n issuer?: string;\n}\n\n/** Scrape limits used when a job leaves these options unspecified. */\nexport interface SystemInfoScraper {\n maxPages: number;\n maxDepth: number;\n}\n\n/**\n * Distilled, serializable snapshot of the server's startup configuration.\n * Safe to assemble a single time at service-registration and share across\n * every tRPC request (HTTP and WebSocket alike).\n */\nexport interface SystemInfo {\n version: string;\n readOnly: boolean;\n telemetryEnabled: boolean;\n services: SystemInfoServices;\n worker: SystemInfoWorker;\n mcp: SystemInfoMcp;\n auth: SystemInfoAuth;\n scraper: SystemInfoScraper;\n}\n\n/**\n * Assembles the {@link SystemInfo} snapshot from server + app configuration.\n * @param serverConfig - Service composition/runtime wiring for this process.\n * @param appConfig - Resolved application configuration (env/YAML/CLI merged).\n * @param mcpEndpointUrl - The advertised public URL of the MCP endpoint.\n * @param workerUrl - The remote worker's API URL; jobs run in this process without it.\n * @returns The distilled system info to thread through the tRPC context.\n */\nexport function buildSystemInfo(\n serverConfig: AppServerConfig,\n appConfig: AppConfig,\n mcpEndpointUrl: string,\n workerUrl: string | undefined,\n): SystemInfo {\n const mcpEnabled = Boolean(serverConfig.enableMcpServer);\n const authEnabled = Boolean(appConfig.auth.enabled);\n\n return {\n version: __APP_VERSION__,\n readOnly: Boolean(appConfig.app.readOnly),\n telemetryEnabled: Boolean(appConfig.app.telemetryEnabled),\n services: {\n web: Boolean(serverConfig.enableWebInterface),\n mcp: mcpEnabled,\n api: Boolean(serverConfig.enableApiServer),\n worker: !workerUrl,\n },\n worker: workerUrl\n ? { mode: \"remote\", url: workerUrl }\n : { mode: \"embedded\", maxConcurrency: appConfig.scraper.maxConcurrency },\n // The deprecated SSE transport is served only while authentication is off.\n mcp: mcpEnabled\n ? {\n enabled: true,\n endpoints: authEnabled\n ? [MCP_ENDPOINT_PATH]\n : [MCP_ENDPOINT_PATH, LEGACY_SSE_PATH],\n url: mcpEndpointUrl,\n }\n : { enabled: false, endpoints: [] },\n auth: {\n enabled: authEnabled,\n issuer:\n authEnabled && appConfig.auth.issuerUrl ? appConfig.auth.issuerUrl : undefined,\n },\n scraper: {\n maxPages: appConfig.scraper.maxPages,\n maxDepth: appConfig.scraper.maxDepth,\n },\n };\n}\n","/**\n * tRPC router for event subscriptions.\n * Allows remote processes to subscribe to application events via tRPC.\n */\n\nimport { initTRPC } from \"@trpc/server\";\nimport { observable } from \"@trpc/server/observable\";\nimport superjson from \"superjson\";\nimport { z } from \"zod\";\nimport type { EventBusService } from \"../EventBusService\";\nimport { EventType } from \"../types\";\n\n// Context carries the event bus instance\nexport interface EventsTrpcContext {\n eventBus: EventBusService;\n}\n\nconst t = initTRPC.context<EventsTrpcContext>().create({\n transformer: superjson,\n});\n\n/**\n * Factory to create an events router from any t instance whose context contains `eventBus`.\n */\nexport function createEventsRouter(trpc: unknown) {\n const tt = trpc as typeof t;\n\n return tt.router({\n /**\n * Subscribe to all application events.\n * Clients receive a stream of events as they occur.\n */\n subscribe: tt.procedure\n .input(\n z\n .object({\n events: z.array(z.nativeEnum(EventType)).optional(),\n })\n .optional(),\n )\n .subscription(({ ctx, input }) => {\n // Determine which events to subscribe to (default: all)\n const eventTypes = input?.events ?? Object.values(EventType);\n\n return observable<{\n type: EventType;\n payload: unknown;\n }>((emit) => {\n const unsubscribers: Array<() => void> = [];\n\n // Subscribe to each requested event type\n for (const eventType of eventTypes) {\n const unsubscribe = ctx.eventBus.on(eventType, (payload) => {\n // EventBus already emits public types (PipelineJob), no conversion needed\n emit.next({\n type: eventType,\n payload,\n });\n });\n\n unsubscribers.push(unsubscribe);\n }\n\n // Cleanup function called when client disconnects\n return () => {\n for (const unsubscribe of unsubscribers) {\n unsubscribe();\n }\n };\n });\n }),\n });\n}\n\n// Default router for standalone usage\nexport const eventsRouter = createEventsRouter(t);\nexport type EventsRouter = typeof eventsRouter;\n","/**\n * tRPC router exposing pipeline procedures for external workers.\n * Provides a minimal RPC surface to replace legacy REST endpoints.\n *\n * This module now exports a factory to build the router from a provided t instance,\n * allowing us to compose multiple routers under a single /api endpoint.\n */\n\nimport { initTRPC, TRPCError } from \"@trpc/server\";\nimport superjson from \"superjson\";\nimport { z } from \"zod\";\nimport type { ScraperOptions } from \"../../scraper/types\";\nimport {\n InvalidLibraryNameError,\n LibraryAlreadyExistsError,\n LibraryNotFoundInStoreError,\n VersionAlreadyExistsError,\n VersionNotFoundInStoreError,\n} from \"../../store/errors\";\nimport { EXISTING_TARGET_POLICIES } from \"../../store/types\";\nimport { PipelineJobStatus } from \"../types\";\nimport type { IPipeline, RelayedEnqueueErrorCode } from \"./interfaces\";\n\n// Context carries the pipeline instance\nexport interface PipelineTrpcContext {\n pipeline: IPipeline;\n}\n\nconst t = initTRPC.context<PipelineTrpcContext>().create({\n transformer: superjson,\n});\n\n// Schemas\nconst nonEmptyTrimmed = z\n .string()\n .transform((s) => s.trim())\n .refine((s) => s.length > 0, \"must not be empty\");\n\n// Optional library version. An empty or whitespace-only string is the domain's\n// representation of \"unversioned\" (see VersionRef), so it is coerced to\n// undefined rather than rejected — callers (CLI, web UI) can pass \"\" for an\n// unversioned library and the pipeline treats it the same as omitting it.\nconst optionalTrimmed = z.preprocess((v) => {\n if (typeof v !== \"string\") return v;\n const trimmed = v.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}, z.string().min(1).optional().nullable());\n\nconst enqueueScrapeInput = z.object({\n library: nonEmptyTrimmed,\n version: optionalTrimmed,\n options: z.custom<ScraperOptions>(),\n // Omitted means \"reject-version\"; the default is applied by the pipeline.\n onExisting: z.enum(EXISTING_TARGET_POLICIES).optional(),\n});\n\n/**\n * The tRPC code for an enqueue error a caller can act on (409, 400, 404 over\n * HTTP), or `null` for any other failure. Typed against the codes\n * `PipelineClient` relays, so the two lists cannot drift apart.\n */\nfunction enqueueErrorCode(error: unknown): RelayedEnqueueErrorCode | null {\n if (\n error instanceof LibraryAlreadyExistsError ||\n error instanceof VersionAlreadyExistsError\n ) {\n return \"CONFLICT\";\n }\n if (error instanceof InvalidLibraryNameError) {\n return \"BAD_REQUEST\";\n }\n if (\n error instanceof LibraryNotFoundInStoreError ||\n error instanceof VersionNotFoundInStoreError\n ) {\n return \"NOT_FOUND\";\n }\n return null;\n}\n\n/**\n * Maps an enqueue error a caller can act on to its tRPC code, keeping the\n * message. Anything else, including a `TRPCError` relayed from a remote worker,\n * passes through unchanged.\n */\nfunction toEnqueueError(error: unknown): unknown {\n const code = enqueueErrorCode(error);\n return code && error instanceof Error\n ? new TRPCError({ code, message: error.message, cause: error })\n : error;\n}\n\nconst enqueueRefreshInput = z.object({\n library: nonEmptyTrimmed,\n version: optionalTrimmed,\n options: z\n .object({\n preserveHashes: z.boolean().optional(),\n })\n .optional(),\n});\n\nconst jobIdInput = z.object({ id: z.string().min(1) });\n\nconst getJobsInput = z.object({\n status: z.nativeEnum(PipelineJobStatus).optional(),\n});\n\n// Factory to create a pipeline router from any t instance whose context contains `pipeline`\nexport function createPipelineRouter(trpc: unknown) {\n const tt = trpc as typeof t;\n return tt.router({\n ping: tt.procedure.query(async () => ({ status: \"ok\", ts: Date.now() })),\n\n enqueueScrapeJob: tt.procedure\n .input(enqueueScrapeInput)\n .mutation(\n async ({\n ctx,\n input,\n }: {\n ctx: PipelineTrpcContext;\n input: z.infer<typeof enqueueScrapeInput>;\n }) => {\n try {\n const jobId = await ctx.pipeline.enqueueScrapeJob(\n input.library,\n input.version ?? null,\n input.options,\n { onExisting: input.onExisting },\n );\n return { jobId };\n } catch (error) {\n throw toEnqueueError(error);\n }\n },\n ),\n\n enqueueRefreshJob: tt.procedure\n .input(enqueueRefreshInput)\n .mutation(\n async ({\n ctx,\n input,\n }: {\n ctx: PipelineTrpcContext;\n input: z.infer<typeof enqueueRefreshInput>;\n }) => {\n try {\n const jobId = await ctx.pipeline.enqueueRefreshJob(\n input.library,\n input.version ?? null,\n input.options,\n );\n return { jobId };\n } catch (error) {\n throw toEnqueueError(error);\n }\n },\n ),\n\n getJob: tt.procedure\n .input(jobIdInput)\n .query(\n async ({\n ctx,\n input,\n }: {\n ctx: PipelineTrpcContext;\n input: z.infer<typeof jobIdInput>;\n }) => {\n return ctx.pipeline.getJob(input.id);\n },\n ),\n\n getJobs: tt.procedure\n .input(getJobsInput.optional())\n .query(\n async ({\n ctx,\n input,\n }: {\n ctx: PipelineTrpcContext;\n input: z.infer<typeof getJobsInput> | undefined;\n }) => {\n const jobs = await ctx.pipeline.getJobs(input?.status);\n return { jobs };\n },\n ),\n\n cancelJob: tt.procedure\n .input(jobIdInput)\n .mutation(\n async ({\n ctx,\n input,\n }: {\n ctx: PipelineTrpcContext;\n input: z.infer<typeof jobIdInput>;\n }) => {\n await ctx.pipeline.cancelJob(input.id);\n return { success: true } as const;\n },\n ),\n\n clearCompletedJobs: tt.procedure.mutation(\n async ({ ctx }: { ctx: PipelineTrpcContext }) => {\n const count = await ctx.pipeline.clearCompletedJobs();\n return { count };\n },\n ),\n });\n}\n\n// Default router for standalone usage (keeps existing imports working)\nexport const pipelineRouter = createPipelineRouter(t);\n\nexport type PipelineRouter = typeof pipelineRouter;\n","/**\n * tRPC router exposing document data store operations via the worker API.\n * Only procedures actually used externally are included to keep surface minimal.\n */\nimport { initTRPC } from \"@trpc/server\";\nimport superjson from \"superjson\";\nimport { z } from \"zod\";\nimport type {\n DbVersionWithLibrary,\n EmbeddingConfigInfo,\n FindVersionResult,\n ListPagesOptions,\n PageContentOptions,\n StoreSearchResult,\n VersionStatus,\n} from \"../types\";\nimport type { IDocumentManagement } from \"./interfaces\";\n\n// Context carries the document management API\nexport interface DataTrpcContext {\n docService: IDocumentManagement;\n}\n\nconst t = initTRPC.context<DataTrpcContext>().create({\n transformer: superjson,\n});\n\n// Common schemas\n/** A required name, trimmed. */\nexport const nonEmpty = z.string().trim().min(1);\n/** An optional version label, trimmed; empty means unversioned. */\nexport const optionalVersion = z\n .string()\n .optional()\n .nullable()\n .transform((v) => (typeof v === \"string\" ? v.trim() : v));\n\nexport function createDataRouter(trpc: unknown) {\n const tt = trpc as typeof t;\n return tt.router({\n ping: tt.procedure.query(async () => ({ status: \"ok\", ts: Date.now() })),\n\n listLibraries: tt.procedure.query(async ({ ctx }: { ctx: DataTrpcContext }) => {\n return await ctx.docService.listLibraries(); // LibrarySummary[]\n }),\n\n findBestVersion: tt.procedure\n .input(z.object({ library: nonEmpty, targetVersion: z.string().optional() }))\n .query(\n async ({\n ctx,\n input,\n }: {\n ctx: DataTrpcContext;\n input: { library: string; targetVersion?: string };\n }) => {\n const result = await ctx.docService.findBestVersion(\n input.library,\n input.targetVersion,\n );\n return result as FindVersionResult;\n },\n ),\n\n validateLibraryExists: tt.procedure\n .input(z.object({ library: nonEmpty }))\n .mutation(\n async ({ ctx, input }: { ctx: DataTrpcContext; input: { library: string } }) => {\n await ctx.docService.validateLibraryExists(input.library);\n return { ok: true } as const;\n },\n ),\n\n // Searches the given version bucket as is, with \"\" meaning unversioned.\n // Remote clients send it versions that are already resolved, so CLI\n // `--exact-match` keeps working; the web UI uses `searchDocs` instead.\n search: tt.procedure\n .input(\n z.object({\n library: nonEmpty,\n version: optionalVersion,\n query: nonEmpty,\n limit: z.number().int().positive().max(50).optional(),\n }),\n )\n .query(\n async ({\n ctx,\n input,\n }: {\n ctx: DataTrpcContext;\n input: {\n library: string;\n version: string | null | undefined;\n query: string;\n limit?: number;\n };\n }) => {\n const results = await ctx.docService.searchStore(\n input.library,\n input.version ?? null,\n input.query,\n input.limit ?? 5,\n );\n\n return results as StoreSearchResult[];\n },\n ),\n\n getPageContent: tt.procedure\n .input(\n z.object({\n library: nonEmpty,\n version: optionalVersion,\n pathOrUrl: nonEmpty,\n options: z\n .object({\n startChunk: z.number().int().nonnegative().optional(),\n maxChars: z.number().positive().optional(),\n })\n .optional(),\n }),\n )\n .query(\n async ({\n ctx,\n input,\n }: {\n ctx: DataTrpcContext;\n input: {\n library: string;\n version: string | null | undefined;\n pathOrUrl: string;\n options?: PageContentOptions;\n };\n }) => {\n return await ctx.docService.getPageContent(\n input.library,\n input.version ?? null,\n input.pathOrUrl,\n input.options,\n );\n },\n ),\n\n listPages: tt.procedure\n .input(\n z.object({\n library: nonEmpty,\n version: optionalVersion,\n options: z\n .object({\n contains: z.string().optional(),\n limit: z.number().int().positive().max(200).optional(),\n offset: z.number().int().nonnegative().optional(),\n })\n .optional(),\n }),\n )\n .query(\n async ({\n ctx,\n input,\n }: {\n ctx: DataTrpcContext;\n input: {\n library: string;\n version: string | null | undefined;\n options?: ListPagesOptions;\n };\n }) => {\n return await ctx.docService.listPages(\n input.library,\n input.version ?? null,\n input.options,\n );\n },\n ),\n\n compact: tt.procedure\n .input(\n z\n .object({ force: z.boolean().optional(), vacuum: z.boolean().optional() })\n .optional(),\n )\n .mutation(\n async ({\n ctx,\n input,\n }: {\n ctx: DataTrpcContext;\n input: { force?: boolean; vacuum?: boolean } | undefined;\n }) => {\n return await ctx.docService.compact(input);\n },\n ),\n\n // Status and version helpers\n\n getVersionsByStatus: tt.procedure\n .input(z.object({ statuses: z.array(z.string()) }))\n .query(\n async ({\n ctx,\n input,\n }: {\n ctx: DataTrpcContext;\n input: { statuses: string[] };\n }) => {\n // Cast trusting caller to pass valid VersionStatus strings\n const statuses = input.statuses as unknown as VersionStatus[];\n return (await ctx.docService.getVersionsByStatus(\n statuses,\n )) as DbVersionWithLibrary[];\n },\n ),\n\n findVersionsBySourceUrl: tt.procedure\n .input(z.object({ url: nonEmpty }))\n .query(async ({ ctx, input }: { ctx: DataTrpcContext; input: { url: string } }) => {\n return (await ctx.docService.findVersionsBySourceUrl(\n input.url,\n )) as DbVersionWithLibrary[];\n }),\n\n getScraperOptions: tt.procedure\n .input(z.object({ versionId: z.number().int().positive() }))\n .query(\n async ({\n ctx,\n input,\n }: {\n ctx: DataTrpcContext;\n input: { versionId: number };\n }) => {\n return await ctx.docService.getScraperOptions(input.versionId);\n },\n ),\n\n updateVersionStatus: tt.procedure\n .input(\n z.object({\n versionId: z.number().int().positive(),\n status: z.string(),\n errorMessage: z.string().optional().nullable(),\n }),\n )\n .mutation(\n async ({\n ctx,\n input,\n }: {\n ctx: DataTrpcContext;\n input: { versionId: number; status: string; errorMessage?: string | null };\n }) => {\n await ctx.docService.updateVersionStatus(\n input.versionId,\n input.status as VersionStatus,\n input.errorMessage ?? undefined,\n );\n return { ok: true } as const;\n },\n ),\n\n updateVersionProgress: tt.procedure\n .input(\n z.object({\n versionId: z.number().int().positive(),\n pages: z.number().int().nonnegative(),\n maxPages: z.number().int().positive(),\n }),\n )\n .mutation(\n async ({\n ctx,\n input,\n }: {\n ctx: DataTrpcContext;\n input: { versionId: number; pages: number; maxPages: number };\n }) => {\n await ctx.docService.updateVersionProgress(\n input.versionId,\n input.pages,\n input.maxPages,\n );\n return { ok: true } as const;\n },\n ),\n\n storeScraperOptions: tt.procedure\n .input(\n z.object({\n versionId: z.number().int().positive(),\n options: z.unknown(),\n }),\n )\n .mutation(\n async ({\n ctx,\n input,\n }: {\n ctx: DataTrpcContext;\n input: { versionId: number; options: unknown };\n }) => {\n // options conforms to ScraperOptions at the caller; keep as unknown here\n await ctx.docService.storeScraperOptions(\n input.versionId,\n input.options as unknown as Parameters<\n IDocumentManagement[\"storeScraperOptions\"]\n >[1],\n );\n return { ok: true } as const;\n },\n ),\n\n // Chunk explorer support (admin UI)\n\n listVersionChunks: tt.procedure\n .input(\n z.object({\n library: nonEmpty,\n version: optionalVersion,\n limit: z.number().int().positive().max(200).optional(),\n offset: z.number().int().nonnegative().optional(),\n filter: z.string().optional(),\n }),\n )\n .query(\n async ({\n ctx,\n input,\n }: {\n ctx: DataTrpcContext;\n input: {\n library: string;\n version: string | null | undefined;\n limit?: number;\n offset?: number;\n filter?: string;\n };\n }) => {\n return await ctx.docService.listVersionChunks(\n { library: input.library, version: input.version ?? \"\" },\n { limit: input.limit ?? 50, offset: input.offset, filter: input.filter },\n );\n },\n ),\n\n getVersionStats: tt.procedure\n .input(z.object({ library: nonEmpty, version: optionalVersion }))\n .query(\n async ({\n ctx,\n input,\n }: {\n ctx: DataTrpcContext;\n input: { library: string; version: string | null | undefined };\n }) => {\n return await ctx.docService.getVersionStats({\n library: input.library,\n version: input.version ?? \"\",\n });\n },\n ),\n\n getActivityHistory: tt.procedure\n .input(z.object({ days: z.number().int().min(1).max(366).optional() }).optional())\n .query(\n async ({\n ctx,\n input,\n }: {\n ctx: DataTrpcContext;\n input: { days?: number } | undefined;\n }) => {\n return await ctx.docService.getActivityHistory(input?.days);\n },\n ),\n\n getVersionComposition: tt.procedure\n .input(z.object({ library: nonEmpty, version: optionalVersion }))\n .query(\n async ({\n ctx,\n input,\n }: {\n ctx: DataTrpcContext;\n input: { library: string; version: string | null | undefined };\n }) => {\n return await ctx.docService.getVersionComposition({\n library: input.library,\n version: input.version ?? \"\",\n });\n },\n ),\n\n // Lets a web process report its remote worker's embedding config in the\n // system-health snapshot (the worker, not the web process, holds it).\n getEmbeddingConfig: tt.procedure.query(\n async ({ ctx }: { ctx: DataTrpcContext }): Promise<EmbeddingConfigInfo | null> => {\n return ctx.docService.getEmbeddingConfigInfo();\n },\n ),\n });\n}\n\n// Default router for standalone usage\nexport const dataRouter = createDataRouter(t);\nexport type DataRouter = typeof dataRouter;\n","/**\n * tRPC router exposing a single `getSystemHealth` query that composes the\n * server's startup {@link SystemInfo} snapshot with the small amount of\n * cheaply-available live state (active embedding config, remote worker\n * connectivity). Powers the dashboard's system-health panel, sidebar status\n * footer, and Settings screen.\n */\nimport { initTRPC } from \"@trpc/server\";\nimport superjson from \"superjson\";\nimport type { IDocumentManagement } from \"../store/trpc/interfaces\";\nimport { logger } from \"../utils/logger\";\nimport type { SystemInfo } from \"./systemInfo\";\n\n/**\n * Context required by the system-health router: the startup snapshot, the\n * document service (for the active embedding config), and an optional cheap\n * connectivity check — only meaningful (and only ever provided) when the\n * worker is remote.\n */\nexport interface SystemHealthTrpcContext {\n systemInfo: SystemInfo;\n docService: IDocumentManagement;\n /** Cheap, synchronous check for whether the remote worker is currently connected. */\n isWorkerConnected?: () => boolean;\n}\n\nconst t = initTRPC.context<SystemHealthTrpcContext>().create({\n transformer: superjson,\n});\n\n/** Worker wiring as reported by `getSystemHealth`. */\nexport type SystemHealthWorker =\n | { mode: \"embedded\"; maxConcurrency: number }\n | { mode: \"remote\"; url: string; connected: boolean };\n\n/** Active embedding configuration, or `null` when running in full-text-search-only mode. */\nexport interface SystemHealthEmbeddings {\n provider: string;\n model: string;\n /** `null` when the model's vector dimension isn't known (never fabricated). */\n dimensions: number | null;\n}\n\n/** Shape returned by the `getSystemHealth` query. */\nexport interface SystemHealth {\n version: string;\n readOnly: boolean;\n telemetryEnabled: boolean;\n services: SystemInfo[\"services\"];\n worker: SystemHealthWorker;\n embeddings: SystemHealthEmbeddings | null;\n mcp: SystemInfo[\"mcp\"];\n auth: SystemInfo[\"auth\"];\n scraper: SystemInfo[\"scraper\"];\n}\n\n/**\n * Factory to create the system-health router from any `t` instance whose\n * context satisfies {@link SystemHealthTrpcContext}.\n */\nexport function createSystemHealthRouter(trpc: unknown) {\n const tt = trpc as typeof t;\n\n return tt.router({\n /**\n * Returns an honest snapshot of the running server's configuration:\n * which services were started, how the worker is wired, the active\n * embedding provider (if any), MCP/auth exposure, and app version.\n * Derived from startup config, not measured — nothing here is fabricated.\n */\n getSystemHealth: tt.procedure.query(\n async ({ ctx }: { ctx: SystemHealthTrpcContext }): Promise<SystemHealth> => {\n const { systemInfo } = ctx;\n\n const worker: SystemHealthWorker =\n systemInfo.worker.mode === \"remote\"\n ? {\n mode: \"remote\",\n url: systemInfo.worker.url,\n connected: ctx.isWorkerConnected?.() ?? false,\n }\n : { mode: \"embedded\", maxConcurrency: systemInfo.worker.maxConcurrency };\n\n // Async so a remote worker's embedding config is fetched over the wire;\n // the local config is null for a remote worker and would misreport it.\n // An unreachable worker must not hide the rest of the report, which is\n // what says the worker is disconnected.\n let embeddings: SystemHealthEmbeddings | null = null;\n try {\n embeddings = await ctx.docService.getEmbeddingConfigInfo();\n } catch (error) {\n logger.debug(`Embedding config unavailable for the health report: ${error}`);\n }\n\n return {\n version: systemInfo.version,\n readOnly: systemInfo.readOnly,\n telemetryEnabled: systemInfo.telemetryEnabled,\n services: systemInfo.services,\n worker,\n embeddings,\n mcp: systemInfo.mcp,\n auth: systemInfo.auth,\n scraper: systemInfo.scraper,\n };\n },\n ),\n });\n}\n\n// Default router for standalone usage\nexport const systemHealthRouter = createSystemHealthRouter(t);\nexport type SystemHealthRouter = typeof systemHealthRouter;\n","/**\n * Canonical tRPC router builder for the merged application API.\n * Combines the health check, pipeline, data store, and events routers into a\n * single router shape. Both the Fastify HTTP mount point and the WebSocket\n * subscription handler in {@link ./trpcService} import from this module so the\n * two transports always expose identical procedures and typing.\n */\n\nimport { initTRPC } from \"@trpc/server\";\nimport superjson from \"superjson\";\nimport { z } from \"zod\";\nimport type { EventBusService } from \"../events\";\nimport { createEventsRouter, type EventsTrpcContext } from \"../events/trpc/router\";\nimport type { IPipeline } from \"../pipeline/trpc/interfaces\";\nimport { createPipelineRouter, type PipelineTrpcContext } from \"../pipeline/trpc/router\";\nimport type { IDocumentManagement } from \"../store/trpc/interfaces\";\nimport {\n createDataRouter,\n type DataTrpcContext,\n nonEmpty,\n optionalVersion,\n} from \"../store/trpc/router\";\nimport { RemoveTool } from \"../tools/RemoveTool\";\nimport { SearchTool } from \"../tools/SearchTool\";\nimport {\n createSystemHealthRouter,\n type SystemHealthTrpcContext,\n} from \"./systemHealthRouter\";\nimport type { SystemInfo } from \"./systemInfo\";\n\n/**\n * Combined tRPC context required by the merged application router.\n * Satisfied by the unified server (pipeline + document store + event bus all\n * available in a single process) as well as any future adapter that can supply\n * the same dependencies.\n */\nexport type AppRouterContext = PipelineTrpcContext &\n DataTrpcContext &\n EventsTrpcContext &\n SystemHealthTrpcContext;\n\n/** Shape of the values a caller must provide to create a request context. */\nexport interface AppRouterContextDeps {\n pipeline: IPipeline;\n docService: IDocumentManagement;\n eventBus: EventBusService;\n /** Distilled, serializable snapshot of the server's startup configuration. */\n systemInfo: SystemInfo;\n /** Cheap, synchronous check for remote worker connectivity (remote worker mode only). */\n isWorkerConnected?: () => boolean;\n}\n\nconst t = initTRPC.context<AppRouterContext>().create({\n transformer: superjson,\n});\n\n/**\n * Builds the merged application tRPC router (health + pipeline + data + events).\n * Kept as a factory (rather than only exporting a singleton) so future\n * transports can construct a fresh router instance if ever needed, while the\n * `appRouter` singleton below remains the single instance shared by the\n * current HTTP and WebSocket mount points.\n * @returns The merged tRPC router.\n */\nexport function buildAppRouter() {\n // Define a single root-level health check to avoid duplicate keys from feature routers\n const healthRouter = t.router({\n ping: t.procedure.query(async () => ({ status: \"ok\", ts: Date.now() })),\n });\n\n // Needs both the pipeline and the store, so it lives with neither router\n const removalRouter = t.router({\n /**\n * Removes a library version as every entry point does: a queued or running\n * job for it is cancelled first, then the version goes, and the library with\n * its last version.\n */\n removeDocs: t.procedure\n .input(z.object({ library: nonEmpty, version: optionalVersion }))\n .mutation(({ ctx, input }) =>\n new RemoveTool(ctx.docService, ctx.pipeline).execute({\n library: input.library,\n version: input.version ?? undefined,\n }),\n ),\n });\n\n // Runs the MCP search tool, so the web UI gets what an MCP client gets\n const searchRouter = t.router({\n /**\n * Searches a library as `search_docs` does: the version resolves to the\n * best stored match first, and an omitted or empty one to the newest. The\n * data router's `search` stays literal, since remote clients send it a\n * version the tool has already resolved.\n */\n searchDocs: t.procedure\n .input(\n z.object({\n library: nonEmpty,\n version: optionalVersion,\n query: nonEmpty,\n limit: z.number().int().positive().max(50).optional(),\n }),\n )\n .query(({ ctx, input }) =>\n new SearchTool(ctx.docService).execute({\n library: input.library,\n version: input.version ?? undefined,\n query: input.query,\n limit: input.limit,\n }),\n ),\n });\n\n return t.router({\n ...healthRouter._def.procedures,\n ...createPipelineRouter(t)._def.procedures,\n ...createDataRouter(t)._def.procedures,\n ...removalRouter._def.procedures,\n ...searchRouter._def.procedures,\n ...createSystemHealthRouter(t)._def.procedures,\n events: createEventsRouter(t),\n });\n}\n\n/** The canonical merged application router instance, shared by all transports. */\nexport const appRouter = buildAppRouter();\n\n/** Type of the merged application router, used for end-to-end client typing. */\nexport type AppRouter = typeof appRouter;\n\n/**\n * Creates the request context shared by both the HTTP and WebSocket transports.\n * @param deps - The pipeline, document store, event bus, and system info backing this request.\n * @returns The context object passed to every procedure resolver.\n */\nexport function createAppRouterContext(deps: AppRouterContextDeps): AppRouterContext {\n return {\n pipeline: deps.pipeline,\n docService: deps.docService,\n eventBus: deps.eventBus,\n systemInfo: deps.systemInfo,\n isWorkerConnected: deps.isWorkerConnected,\n };\n}\n","/**\n * Fastify service to register unified tRPC API at /api.\n * Merges pipeline, data store, and events routers under a single endpoint.\n * Also provides WebSocket support for subscriptions.\n * Both mount points delegate to the single canonical router built in\n * {@link ../services/appRouter}, keeping HTTP and WebSocket behavior identical.\n */\n\nimport { fastifyTRPCPlugin } from \"@trpc/server/adapters/fastify\";\nimport { applyWSSHandler } from \"@trpc/server/adapters/ws\";\nimport type { FastifyInstance } from \"fastify\";\nimport type { WebSocketServer } from \"ws\";\nimport type { EventBusService } from \"../events\";\nimport type { IPipeline } from \"../pipeline/trpc/interfaces\";\nimport type { IDocumentManagement } from \"../store/trpc/interfaces\";\nimport { appRouter, createAppRouterContext } from \"./appRouter\";\nimport type { SystemInfo } from \"./systemInfo\";\n\n/**\n * Registers the merged tRPC router on a Fastify instance under the `/api` prefix.\n * @param server - The Fastify instance to register the plugin on.\n * @param pipeline - The pipeline instance backing pipeline procedures.\n * @param docService - The document management service backing data procedures.\n * @param eventBus - The event bus backing the events subscription router.\n * @param systemInfo - Distilled, serializable snapshot of the server's startup configuration.\n * @param isWorkerConnected - Cheap connectivity check, provided only when the worker is remote.\n */\nexport async function registerTrpcService(\n server: FastifyInstance,\n pipeline: IPipeline,\n docService: IDocumentManagement,\n eventBus: EventBusService,\n systemInfo: SystemInfo,\n isWorkerConnected?: () => boolean,\n): Promise<void> {\n await server.register(fastifyTRPCPlugin, {\n prefix: \"/api\",\n trpcOptions: {\n router: appRouter,\n createContext: async () =>\n createAppRouterContext({\n pipeline,\n docService,\n eventBus,\n systemInfo,\n isWorkerConnected,\n }),\n },\n });\n}\n\n/**\n * Applies the tRPC WebSocket handler to a WebSocketServer for subscriptions.\n * @param wss - The WebSocket server to attach the tRPC handler to.\n * @param pipeline - The pipeline instance backing pipeline procedures.\n * @param docService - The document management service backing data procedures.\n * @param eventBus - The event bus backing the events subscription router.\n * @param systemInfo - Distilled, serializable snapshot of the server's startup configuration.\n * @param isWorkerConnected - Cheap connectivity check, provided only when the worker is remote.\n * @returns The tRPC WebSocket handler returned by `applyWSSHandler`.\n */\nexport function applyTrpcWebSocketHandler(\n wss: WebSocketServer,\n pipeline: IPipeline,\n docService: IDocumentManagement,\n eventBus: EventBusService,\n systemInfo: SystemInfo,\n isWorkerConnected?: () => boolean,\n) {\n return applyWSSHandler({\n wss,\n router: appRouter,\n createContext: () =>\n createAppRouterContext({\n pipeline,\n docService,\n eventBus,\n systemInfo,\n isWorkerConnected,\n }),\n });\n}\n","/**\n * ASCII art banner for console startup display.\n * Uses ANSI colors: gray (dim) top line, bright white bottom line.\n */\nexport const BANNER = [\n \"\\x1b[90m █▀▀ █▀█ █▀█ █ █ █▄ █ █▀▄ █▀▀ █▀▄ █▀▄ █▀█ █▀▀ █▀▀\\x1b[0m\",\n \"\\x1b[97m █▄█ █▀▄ █▄█ █▄█ █ ▀█ █▄▀ ██▄ █▄▀ █▄▀ █▄█ █▄▄ ▄▄█\\x1b[0m\",\n].join(\"\\n\");\n\n/**\n * Prints the startup banner to console.\n * Only call this for HTTP server startup, not stdio mode.\n */\nexport function printBanner(): void {\n console.log(); // Blank line before banner\n console.log(BANNER);\n console.log(); // Blank line after banner\n}\n","/**\n * Helpers for serving the application under the path of its public URL, e.g.\n * `https://example.com/docs`, behind proxies that either forward or strip that\n * prefix.\n */\n\nimport { RESERVED_ROOT_SEGMENTS } from \"../utils/serverOrigin\";\nimport { escapeHtml } from \"../utils/string\";\n\n/**\n * Remove the base path from a request URL, so a single set of root-mounted\n * routes serves both proxy styles. The match is segment-aware: `/docs` and\n * `/docs/…` are stripped, `/docs-old` is not.\n * @param url - The request URL (path plus optional query).\n * @param basePath - `\"\"` or a path without a trailing slash, e.g. `/docs`.\n * @returns The URL relative to the base path, always starting with `/`.\n */\nexport function stripBasePath(url: string, basePath: string): string {\n if (!basePath || !url.startsWith(basePath)) {\n return url;\n }\n const rest = url.slice(basePath.length);\n if (rest === \"\") {\n return \"/\";\n }\n if (rest.startsWith(\"/\")) {\n return rest;\n }\n if (rest.startsWith(\"?\")) {\n return `/${rest}`;\n }\n return url;\n}\n\n/**\n * Insert `<base href=\"{basePath}/\">` as the first child of `<head>`. The web UI\n * is built with relative asset URLs, so the base element makes them resolve\n * under the base path, including on deep links, and at the root when there is\n * no base path.\n * @param html - The SPA shell.\n * @param basePath - `\"\"` or a path without a trailing slash.\n * @returns The shell with the base element.\n */\nexport function injectBaseHref(html: string, basePath: string): string {\n const baseElement = `<base href=\"${escapeHtml(basePath)}/\">`;\n const headTag = /<head(\\s[^>]*)?>/i;\n if (headTag.test(html)) {\n return html.replace(headTag, (match) => `${match}${baseElement}`);\n }\n return `${baseElement}${html}`;\n}\n\n/**\n * Whether a path is `prefix` itself or lies below it: `/api` and `/api/x`\n * match `/api`, `/apix` does not.\n * @param pathname - A request path without query string.\n * @param prefix - A path without a trailing slash.\n * @returns `true` when the path is under the prefix.\n */\nexport function isUnderPath(pathname: string, prefix: string): boolean {\n return pathname === prefix || pathname.startsWith(`${prefix}/`);\n}\n\n/** Paths that never fall back to the web UI; see {@link RESERVED_ROOT_SEGMENTS}. */\nconst NON_SPA_PREFIXES = RESERVED_ROOT_SEGMENTS.map((segment) => `/${segment}`);\n\n/**\n * Whether an unmatched request should get the web UI shell, so client-side\n * routes and deep links load. Everything else gets a JSON 404.\n * @param method - The HTTP method.\n * @param url - The request URL, after the base path has been stripped.\n * @returns `true` for GET/HEAD requests outside the API, MCP, metadata and asset paths.\n */\nexport function servesSpaShell(method: string, url: string): boolean {\n if (method !== \"GET\" && method !== \"HEAD\") {\n return false;\n }\n const pathname = url.split(\"?\")[0];\n return !NON_SPA_PREFIXES.some((prefix) => isUnderPath(pathname, prefix));\n}\n\n/**\n * Whether a WebSocket upgrade targets the API's live-update socket: `/api`,\n * where the web UI and coordinators connect, or the root, where coordinators\n * of earlier releases connect. The MCP endpoint and every other path are\n * refused, so a proxy that signs in the web UI and `/api` but leaves `/mcp` to\n * bearer tokens also covers the socket.\n * @param url - The upgrade request's URL, with or without the base path.\n * @param basePath - `\"\"` or a path without a trailing slash.\n * @returns `true` when the upgrade may reach the API's socket.\n */\nexport function isApiSocketPath(url: string, basePath: string): boolean {\n const pathname = stripBasePath(url, basePath).split(\"?\")[0];\n return pathname === \"/\" || isUnderPath(pathname, \"/api\");\n}\n","/**\n * Central application server that can be configured to run different combinations of services.\n * This replaces the separate server implementations with a single, modular approach.\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport type { IncomingHttpHeaders } from \"node:http\";\nimport path from \"node:path\";\nimport type { Duplex } from \"node:stream\";\nimport fastifyStatic from \"@fastify/static\";\nimport Fastify, {\n type FastifyError,\n type FastifyInstance,\n type FastifyReply,\n type FastifyRequest,\n} from \"fastify\";\nimport { WebSocketServer } from \"ws\";\nimport { JwtAccessTokenVerifier } from \"../auth/JwtAccessTokenVerifier\";\nimport {\n buildProtectedResourceMetadata,\n protectedResourceMetadataPaths,\n protectedResourceMetadataUrl,\n} from \"../auth/protectedResourceMetadata\";\nimport type { JobsBackend } from \"../services/backend\";\nimport {\n MCP_ENDPOINT_PATH,\n type McpEndpointAuth,\n registerMcpService,\n} from \"../services/mcpService\";\nimport { buildSystemInfo, type SystemInfo } from \"../services/systemInfo\";\nimport { applyTrpcWebSocketHandler, registerTrpcService } from \"../services/trpcService\";\nimport { TelemetryEvent, telemetry } from \"../telemetry\";\nimport { shouldEnableTelemetry } from \"../telemetry/TelemetryConfig\";\nimport { printBanner } from \"../utils/banner\";\nimport type { AppConfig } from \"../utils/config\";\nimport { logger } from \"../utils/logger\";\nimport { getProjectRoot } from \"../utils/paths\";\nimport {\n describePublicLocationWarnings,\n type PublicLocation,\n resolvePublicLocation,\n} from \"../utils/serverOrigin\";\nimport type { AppServerConfig } from \"./AppServerConfig\";\nimport {\n injectBaseHref,\n isApiSocketPath,\n isUnderPath,\n servesSpaShell,\n stripBasePath,\n} from \"./basePath\";\nimport {\n createHostPolicy,\n createOriginPolicy,\n type HostPolicy,\n isLoopbackBindHost,\n type OriginPolicy,\n setCorsPreflightHeaders,\n} from \"./originPolicy\";\n\n/** Distinct refused host names that get a warning; later ones are only refused. */\nconst MAX_REFUSED_HOST_WARNINGS = 20;\n\n/**\n * Central application server that provides modular service composition.\n */\nexport class AppServer {\n private server: FastifyInstance;\n /** Authentication for the MCP endpoint; set only when auth is enabled and MCP is served. */\n private mcpAuth: McpEndpointAuth | undefined;\n private readonly originPolicy: OriginPolicy;\n private readonly hostPolicy: HostPolicy;\n private readonly refusedHosts = new Set<string>();\n /**\n * On a loopback bind no reverse proxy stands in front of the API, so it is\n * shielded from foreign web pages the same way as the MCP endpoint.\n */\n private readonly shieldsApi: boolean;\n private serverConfig: AppServerConfig;\n private readonly appConfig: AppConfig;\n private readonly systemInfo: SystemInfo;\n private wss: WebSocketServer | null = null;\n /** Where clients reach this server; every advertised URL derives from it. */\n private readonly location: PublicLocation;\n /** Public URL of the MCP endpoint: the resource identifier and default token audience. */\n private readonly mcpEndpointUrl: string;\n\n /**\n * @param backend The services to serve. Whoever opened them closes them;\n * the server neither starts nor stops the pipeline.\n * @param serverConfig Which services to run and the port to bind.\n * @param appConfig The application configuration.\n */\n constructor(\n private readonly backend: JobsBackend,\n serverConfig: AppServerConfig,\n appConfig: AppConfig,\n ) {\n this.serverConfig = serverConfig;\n this.appConfig = appConfig;\n this.location = resolvePublicLocation(appConfig, serverConfig.port);\n for (const warning of describePublicLocationWarnings(appConfig)) {\n logger.warn(`⚠️ ${warning}`);\n }\n this.mcpEndpointUrl = `${this.location.url}${MCP_ENDPOINT_PATH}`;\n const browserPolicy = {\n publicOrigin: this.location.configured ? this.location.origin : undefined,\n allowedOrigins: appConfig.server.allowedOrigins,\n };\n this.originPolicy = createOriginPolicy(browserPolicy);\n this.hostPolicy = createHostPolicy(browserPolicy);\n this.shieldsApi = isLoopbackBindHost(appConfig.server.host);\n this.systemInfo = buildSystemInfo(\n serverConfig,\n appConfig,\n this.mcpEndpointUrl,\n backend.workerUrl,\n );\n const basePath = this.location.basePath;\n this.server = Fastify({\n logger: false, // Use our own logger\n // One set of root-mounted routes serves proxies that forward the base\n // path and proxies that strip it.\n rewriteUrl: (request) => stripBasePath(request.url ?? \"/\", basePath),\n });\n }\n\n /** Whether jobs run in this process rather than on a remote worker. */\n private get runsJobs(): boolean {\n return this.backend.workerUrl === undefined;\n }\n\n /**\n * Whether a request's `Host` header may be served, warning once per refused\n * name so an operator reaching the server under an unknown name sees why.\n */\n private acceptsHost(host: string | undefined): boolean {\n if (this.hostPolicy.isAllowed(host)) {\n return true;\n }\n const name = JSON.stringify(String(host).slice(0, 100));\n if (\n !this.refusedHosts.has(name) &&\n this.refusedHosts.size < MAX_REFUSED_HOST_WARNINGS\n ) {\n this.refusedHosts.add(name);\n logger.warn(\n `⚠️ Refused a request for host ${name}. If clients reach the server under this name, set server.publicUrl to it or add its origin to server.allowedOrigins.`,\n );\n }\n return false;\n }\n\n /**\n * Why a request or WebSocket upgrade is refused before routing, if it is:\n * an unknown host name (DNS rebinding), or a foreign origin calling the API\n * on a loopback bind.\n * @param headers - The request headers.\n * @param reachesApi - Whether the request targets the API or its WebSocket.\n * @returns The refusal message, or `undefined` when the request may proceed.\n */\n private refusal(headers: IncomingHttpHeaders, reachesApi: boolean): string | undefined {\n if (!this.acceptsHost(headers.host)) {\n return \"Forbidden: host not allowed.\";\n }\n if (\n reachesApi &&\n this.shieldsApi &&\n this.originPolicy.check(headers.origin) === \"denied\"\n ) {\n return \"Forbidden: origin not allowed.\";\n }\n return undefined;\n }\n\n /**\n * Start the application server with the configured services.\n */\n async start(): Promise<FastifyInstance> {\n // Get embedding configuration from the document service (source of truth)\n const embeddingConfig = this.backend.docService.getActiveEmbeddingConfig();\n\n // Initialize telemetry if enabled\n if (this.appConfig.app.telemetryEnabled && shouldEnableTelemetry()) {\n try {\n // Set global application context that will be included in all events\n if (telemetry.isEnabled()) {\n telemetry.setGlobalContext({\n appVersion: __APP_VERSION__,\n appPlatform: process.platform,\n appNodeVersion: process.version,\n appServicesEnabled: this.getActiveServicesList(),\n appAuthEnabled: Boolean(this.appConfig.auth.enabled),\n appReadOnly: Boolean(this.appConfig.app.readOnly),\n // Add embedding configuration to global context\n ...(embeddingConfig && {\n aiEmbeddingProvider: embeddingConfig.provider,\n aiEmbeddingModel: embeddingConfig.model,\n aiEmbeddingDimensions: embeddingConfig.dimensions,\n }),\n });\n\n // Track app start at the very beginning\n telemetry.track(TelemetryEvent.APP_STARTED, {\n services: this.getActiveServicesList(),\n port: this.serverConfig.port,\n externalWorker: Boolean(this.backend.workerUrl),\n // Include startup context when available\n ...(this.serverConfig.startupContext?.cliCommand && {\n cliCommand: this.serverConfig.startupContext.cliCommand,\n }),\n ...(this.serverConfig.startupContext?.mcpProtocol && {\n mcpProtocol: this.serverConfig.startupContext.mcpProtocol,\n }),\n ...(this.serverConfig.startupContext?.mcpTransport && {\n mcpTransport: this.serverConfig.startupContext.mcpTransport,\n }),\n });\n }\n } catch (error) {\n logger.debug(`Failed to initialize telemetry: ${error}`);\n }\n }\n\n await this.setupServer();\n\n try {\n await this.server.listen({\n port: this.serverConfig.port,\n host: this.appConfig.server.host,\n });\n\n // Setup WebSocket server for tRPC subscriptions if API server is enabled\n if (this.serverConfig.enableApiServer) {\n this.setupWebSocketServer();\n }\n\n this.logStartupInfo(this.location.url);\n return this.server;\n } catch (error) {\n logger.error(`❌ Failed to start AppServer: ${error}`);\n await this.server.close();\n throw error;\n }\n }\n\n /**\n * Stop the application server and cleanup all services.\n */\n async stop(): Promise<void> {\n try {\n // Close WebSocket server if it exists\n if (this.wss) {\n // Forcibly close all active client connections before closing the server\n for (const client of this.wss.clients) {\n client.terminate();\n }\n\n await new Promise<void>((resolve, reject) => {\n this.wss?.close((err) => {\n if (err) {\n logger.error(`❌ Failed to close WebSocket server: ${err}`);\n reject(err);\n } else {\n logger.debug(\"WebSocket server closed\");\n resolve();\n }\n });\n });\n }\n\n // Track app shutdown\n if (telemetry.isEnabled()) {\n telemetry.track(TelemetryEvent.APP_SHUTDOWN, {\n graceful: true,\n });\n }\n\n // Shutdown telemetry service (this will flush remaining events)\n await telemetry.shutdown();\n\n // Force close all connections to ensure immediate shutdown\n if (this.server.server) {\n this.server.server.closeAllConnections();\n }\n\n // Close Fastify server\n await this.server.close();\n logger.info(\"🛑 AppServer stopped\");\n } catch (error) {\n logger.error(`❌ Failed to stop AppServer gracefully: ${error}`);\n\n // Track ungraceful shutdown\n if (telemetry.isEnabled()) {\n telemetry.track(TelemetryEvent.APP_SHUTDOWN, {\n graceful: false,\n error: error instanceof Error ? error.constructor.name : \"UnknownError\",\n });\n await telemetry.shutdown();\n }\n\n throw error;\n }\n }\n\n /**\n * Setup global error handling for telemetry\n */\n private setupErrorHandling(): void {\n // Only add listeners if they haven't been added yet (prevent duplicate listeners in tests)\n if (!process.listenerCount(\"unhandledRejection\")) {\n // Catch unhandled promise rejections\n process.on(\"unhandledRejection\", (reason) => {\n logger.error(`Unhandled Promise Rejection: ${reason}`);\n if (telemetry.isEnabled()) {\n // Create an Error object from the rejection reason for better tracking\n const error = reason instanceof Error ? reason : new Error(String(reason));\n telemetry.captureException(error, {\n error_category: \"system\",\n component: AppServer.constructor.name,\n context: \"process_unhandled_rejection\",\n });\n }\n });\n }\n\n if (!process.listenerCount(\"uncaughtException\")) {\n // Catch uncaught exceptions\n process.on(\"uncaughtException\", (error) => {\n logger.error(`Uncaught Exception: ${error.message}`);\n if (telemetry.isEnabled()) {\n telemetry.captureException(error, {\n error_category: \"system\",\n component: AppServer.constructor.name,\n context: \"process_uncaught_exception\",\n });\n }\n // Don't exit immediately, let the app attempt graceful shutdown\n });\n }\n\n // Setup Fastify error handler (if method exists - for testing compatibility)\n if (typeof this.server.setErrorHandler === \"function\") {\n this.server.setErrorHandler<FastifyError>(async (error, request, reply) => {\n if (telemetry.isEnabled()) {\n telemetry.captureException(error, {\n errorCategory: \"http\",\n component: \"FastifyServer\",\n statusCode: error.statusCode || 500,\n method: request.method,\n // The route pattern, never the request URL with its parameters\n route: request.routeOptions?.url ?? \"unmatched\",\n context: \"http_request_error\",\n });\n }\n\n logger.error(`HTTP Error on ${request.method} ${request.url}: ${error.message}`);\n\n // Send appropriate error response\n const statusCode = error.statusCode || 500;\n reply.status(statusCode).send({\n error: \"Internal Server Error\",\n statusCode,\n message: statusCode < 500 ? error.message : \"An unexpected error occurred\",\n });\n });\n }\n }\n\n /**\n * Get list of currently active services for telemetry\n */\n private getActiveServicesList(): string[] {\n const services: string[] = [];\n if (this.serverConfig.enableMcpServer) services.push(\"mcp\");\n if (this.serverConfig.enableWebInterface) services.push(\"web\");\n if (this.serverConfig.enableApiServer) services.push(\"api\");\n if (this.runsJobs) services.push(\"worker\");\n return services;\n }\n\n /**\n * Setup the server with plugins and conditionally enabled services.\n */\n private async setupServer(): Promise<void> {\n // Setup global error handling for telemetry\n this.setupErrorHandling();\n\n // Refuse host names that could belong to an attacker's page (a DNS-rebound\n // page sends same-origin GET requests without an Origin header, so origin\n // checks alone cannot recognize it), and shield the API on a loopback bind.\n this.server.addHook(\"onRequest\", async (request, reply) => {\n const reachesApi = isUnderPath(request.url.split(\"?\")[0], \"/api\");\n const refusal = this.refusal(request.headers, reachesApi);\n if (refusal) {\n return reply.code(403).send({ error: refusal });\n }\n });\n\n // Authentication covers the MCP endpoint only; set it up before the\n // endpoint registers so every request goes through the same checks.\n await this.setupAuthentication();\n\n // Conditionally enable services based on configuration\n if (this.serverConfig.enableMcpServer) {\n await this.enableMcpServer();\n }\n\n if (this.serverConfig.enableApiServer) {\n await this.enableTrpcApi();\n }\n\n // Enable the web interface (must be last): the React SPA is served as a\n // static asset with a catch-all fallback for client-side routing, so\n // \"enabling\" it just means registering the static file handler after\n // every other route is in place. See setupStaticFiles/setNotFoundHandler.\n if (this.serverConfig.enableWebInterface) {\n await this.setupStaticFiles();\n }\n }\n\n /**\n * Enable MCP server service.\n */\n private async enableMcpServer(): Promise<void> {\n await registerMcpService(\n this.server,\n {\n docService: this.backend.docService,\n pipeline: this.backend.pipeline,\n config: this.appConfig,\n originPolicy: this.originPolicy,\n location: this.location,\n },\n this.mcpAuth,\n );\n logger.debug(\"MCP server service enabled\");\n }\n\n /**\n * Enable Pipeline RPC (tRPC) service.\n */\n private async enableTrpcApi(): Promise<void> {\n await registerTrpcService(\n this.server,\n this.backend.pipeline,\n this.backend.docService,\n this.backend.eventBus,\n this.systemInfo,\n this.backend.isWorkerConnected,\n );\n logger.debug(\"API server (tRPC) enabled\");\n }\n\n /**\n * Setup WebSocket server for tRPC subscriptions.\n * This is called after the HTTP server is listening.\n */\n private setupWebSocketServer(): void {\n // Ensure the underlying HTTP server is available\n if (!this.server.server) {\n throw new Error(\n \"Cannot setup WebSocket server: HTTP server not available. \" +\n \"This method must be called after server.listen() completes.\",\n );\n }\n\n // Create WebSocket server attached to the HTTP server\n this.wss = new WebSocketServer({\n noServer: true,\n });\n\n // Handle HTTP upgrade requests for WebSocket connections\n this.server.server.on(\"upgrade\", (request, socket, head) => {\n // Upgrades bypass Fastify routing, so the same admission check runs here:\n // a foreign page must not open the live-update stream, which is the only\n // WebSocket the server serves.\n if (this.refusal(request.headers, true)) {\n refuseUpgrade(socket, \"403 Forbidden\");\n return;\n }\n if (!isApiSocketPath(request.url ?? \"/\", this.location.basePath)) {\n refuseUpgrade(socket, \"404 Not Found\");\n return;\n }\n this.wss?.handleUpgrade(request, socket, head, (ws) => {\n this.wss?.emit(\"connection\", ws, request);\n });\n });\n\n // Apply tRPC WebSocket handler to enable subscriptions\n applyTrpcWebSocketHandler(\n this.wss,\n this.backend.pipeline,\n this.backend.docService,\n this.backend.eventBus,\n this.systemInfo,\n this.backend.isWorkerConnected,\n );\n\n logger.debug(\"WebSocket server initialized for tRPC subscriptions\");\n }\n\n /**\n * Setup static file serving with root prefix as fallback, plus a SPA\n * fallback so client-side routing works for the React admin dashboard.\n */\n private async setupStaticFiles(): Promise<void> {\n const publicRoot = path.join(getProjectRoot(), \"public\");\n const indexHtmlPath = path.join(publicRoot, \"index.html\");\n const serveSpaShell = this.createSpaShellHandler(indexHtmlPath);\n\n await this.server.register(fastifyStatic, {\n root: publicRoot,\n prefix: \"/\",\n index: false,\n });\n\n // @fastify/static's wildcard route treats an exact \"/\" request as a\n // directory listing attempt and answers 403 (not 404) when index is\n // disabled, so it never reaches setNotFoundHandler below. Register an\n // explicit literal route for \"/\" - Fastify's router always prefers a\n // literal match over the plugin's \"/*\" wildcard, so this takes priority\n // without conflicting with it.\n this.server.get(\"/\", serveSpaShell);\n // The shell must always carry its <base> element, so it is never served\n // raw by the static handler either.\n this.server.get(\"/index.html\", serveSpaShell);\n\n // SPA fallback: serve the shell for any other unmatched GET request\n // (client-side routes like /libraries or /jobs) so deep links and page\n // refreshes work. API, MCP, metadata and asset paths get a JSON 404.\n this.server.setNotFoundHandler(async (request, reply) => {\n if (!servesSpaShell(request.method, request.url)) {\n reply.code(404).send({ error: \"Not Found\" });\n return;\n }\n\n await serveSpaShell(request, reply);\n });\n }\n\n /**\n * Creates a request handler that responds with the built SPA's\n * `index.html`, with a `<base>` element for the public URL's path, falling\n * back to a 404 if the file cannot be read (e.g. the frontend has not been\n * built yet).\n */\n private createSpaShellHandler(\n indexHtmlPath: string,\n ): (request: FastifyRequest, reply: FastifyReply) => Promise<void> {\n // Cache the built index.html after the first successful read — it never\n // changes while the server is running, so re-reading it from disk on every\n // deep-link/refresh is wasted I/O.\n let cachedHtml: string | null = null;\n return async (_request, reply) => {\n try {\n if (cachedHtml === null) {\n cachedHtml = injectBaseHref(\n await readFile(indexHtmlPath, \"utf-8\"),\n this.location.basePath,\n );\n }\n reply.type(\"text/html\").send(cachedHtml);\n } catch (error) {\n logger.error(`❌ Failed to serve SPA shell from ${indexHtmlPath}: ${error}`);\n reply.code(404).send({ error: \"Not Found\" });\n }\n };\n }\n\n /**\n * Set up authentication for the MCP endpoint: this server is an OAuth 2.0\n * resource server that verifies tokens the configured issuer issued for it,\n * and publishes protected resource metadata so clients can find that issuer.\n *\n * @throws Error when authentication is enabled for the MCP endpoint without\n * an issuer or a public URL, or when the issuer can't be discovered.\n */\n private async setupAuthentication(): Promise<void> {\n if (!this.appConfig.auth.enabled) {\n return;\n }\n if (!this.serverConfig.enableMcpServer) {\n logger.warn(\n \"⚠️ Authentication is enabled, but this process serves no MCP endpoint, so it protects nothing here. The web UI and API are never protected by authentication.\",\n );\n return;\n }\n\n const issuerUrl = this.appConfig.auth.issuerUrl?.trim();\n if (!issuerUrl) {\n throw new Error(\n \"Authentication is enabled but auth.issuerUrl is not set. Set it to your identity provider's issuer URL.\",\n );\n }\n if (!this.location.configured) {\n throw new Error(\n \"Authentication is enabled but no public URL is configured. Set server.publicUrl (or --public-url) to the URL clients use to reach this server.\",\n );\n }\n\n const verifier = await JwtAccessTokenVerifier.create({\n issuerUrl,\n audience: this.appConfig.auth.audience?.trim() || this.mcpEndpointUrl,\n });\n\n const document = buildProtectedResourceMetadata({\n mcpEndpointUrl: this.mcpEndpointUrl,\n issuerUrl,\n server: this.appConfig.server,\n });\n for (const metadataPath of protectedResourceMetadataPaths(\n this.location.basePath,\n MCP_ENDPOINT_PATH,\n )) {\n this.server.route({\n method: [\"GET\", \"HEAD\"],\n url: metadataPath,\n handler: async (_request, reply) =>\n reply\n .header(\"Access-Control-Allow-Origin\", \"*\")\n .type(\"application/json\")\n .send(document),\n });\n this.server.options(metadataPath, async (request, reply) => {\n setCorsPreflightHeaders(reply.raw, {\n origin: \"*\",\n methods: \"GET\",\n requestedHeaders: request.headers[\"access-control-request-headers\"],\n });\n return reply.code(204).send();\n });\n }\n\n this.mcpAuth = {\n verifier,\n resourceMetadataUrl: protectedResourceMetadataUrl(\n this.location.url,\n MCP_ENDPOINT_PATH,\n ),\n };\n logger.debug(`Protected resource metadata served for ${this.mcpEndpointUrl}`);\n }\n\n /**\n * Log startup information showing which services are enabled.\n */\n private logStartupInfo(address: string): void {\n // Print the ASCII art banner if enabled\n if (this.serverConfig.showLogo !== false) {\n printBanner();\n }\n\n // Determine the service mode\n const isWorkerOnly =\n this.runsJobs &&\n !this.serverConfig.enableWebInterface &&\n !this.serverConfig.enableMcpServer;\n const isWebOnly =\n this.serverConfig.enableWebInterface &&\n !this.runsJobs &&\n !this.serverConfig.enableMcpServer;\n const isMcpOnly =\n this.serverConfig.enableMcpServer &&\n !this.serverConfig.enableWebInterface &&\n !this.runsJobs;\n\n // Determine the main service name\n if (isWorkerOnly) {\n // Advertise the tRPC API endpoint (mounted under /api, see trpcService),\n // not the bare origin, so it can be pasted straight into another\n // instance's `web --server-url`.\n logger.info(`🚀 Worker available at ${address}/api`);\n } else if (isWebOnly) {\n logger.info(`🚀 Web interface available at ${address}`);\n } else if (isMcpOnly) {\n logger.info(`🚀 MCP server available at ${address}`);\n } else {\n logger.info(`🚀 Grounded Docs available at ${address}`);\n }\n\n const isCombined = !isWorkerOnly && !isWebOnly && !isMcpOnly;\n\n const enabledServices: string[] = [];\n\n // Web interface: only show if combined mode\n if (this.serverConfig.enableWebInterface && isCombined) {\n enabledServices.push(`Web interface: ${address}`);\n }\n\n // MCP endpoint: always show if enabled\n if (this.serverConfig.enableMcpServer) {\n enabledServices.push(`MCP endpoint: ${this.mcpEndpointUrl}`);\n }\n\n // Authentication boundary: say exactly what is and isn't protected\n if (this.mcpAuth) {\n enabledServices.push(\n `Authentication: protects ${this.mcpEndpointUrl} only; the web UI and API are not protected`,\n );\n }\n\n // Worker: only show external worker URL (internal is implied)\n if (this.backend.workerUrl) {\n enabledServices.push(`Worker: ${this.backend.workerUrl}`);\n }\n\n // Embeddings: only show if worker is enabled\n if (this.runsJobs) {\n const embeddingConfig = this.backend.docService.getActiveEmbeddingConfig();\n if (embeddingConfig) {\n enabledServices.push(\n `Embeddings: ${embeddingConfig.provider}:${embeddingConfig.model}`,\n );\n } else {\n enabledServices.push(`Embeddings: disabled (full text search only)`);\n }\n }\n\n for (const service of enabledServices) {\n logger.info(` • ${service}`);\n }\n }\n}\n\n/**\n * Answer a WebSocket upgrade with an HTTP error and close the connection once\n * the answer is sent. Node no longer watches an upgraded socket, so a client\n * that resets the connection must not raise an unhandled error.\n * @param socket - The upgrade request's socket.\n * @param status - Status code and reason, e.g. `404 Not Found`.\n */\nfunction refuseUpgrade(socket: Duplex, status: string): void {\n socket.on(\"error\", () => socket.destroy());\n socket.once(\"finish\", () => socket.destroy());\n socket.end(`HTTP/1.1 ${status}\\r\\nConnection: close\\r\\nContent-Length: 0\\r\\n\\r\\n`);\n}\n","/**\n * App module exports for the central application server architecture.\n */\n\n/**\n * Application server module exports.\n * Provides AppServer and configuration types, plus convenience functions for CLI integration.\n */\n\nexport { AppServer } from \"./AppServer\";\nexport type { AppServerConfig } from \"./AppServerConfig\";\n\nimport type { JobsBackend } from \"../services/backend\";\nimport type { AppConfig } from \"../utils/config\";\nimport { AppServer } from \"./AppServer\";\nimport type { AppServerConfig } from \"./AppServerConfig\";\n\n/**\n * Starts an AppServer that serves `backend` with the given configuration.\n * Convenience function for CLI integration.\n *\n * @param backend The services to serve; the caller closes them after stopping the server.\n * @param serverConfig Which services to run and the port to bind.\n * @param appConfig The application configuration.\n * @returns The started server.\n */\nexport async function startAppServer(\n backend: JobsBackend,\n serverConfig: AppServerConfig,\n appConfig: AppConfig,\n): Promise<AppServer> {\n const appServer = new AppServer(backend, serverConfig, appConfig);\n await appServer.start();\n return appServer;\n}\n","import { type StdioServerHandle, serveStdio } from \"@modelcontextprotocol/server/stdio\";\nimport type { AppConfig } from \"../utils/config\";\nimport { logger } from \"../utils/logger\";\nimport { createMcpServerFactory } from \"./mcpServer\";\nimport type { McpServerTools } from \"./tools\";\n\n/**\n * Starts the MCP server on the process's stdio.\n *\n * Serves clients on the current protocol revision as well as clients that open\n * with an earlier revision's `initialize` handshake. Each connection gets a\n * server instance from the shared factory.\n *\n * @param tools The shared tool instances.\n * @param config The application configuration.\n * @returns The handle that closes the stdio connection on shutdown.\n */\nexport async function startStdioServer(\n tools: McpServerTools,\n config: AppConfig,\n): Promise<StdioServerHandle> {\n const handle = serveStdio(createMcpServerFactory(tools, config), {\n legacy: \"serve\",\n onerror: (error) => logger.error(`❌ MCP stdio transport error: ${error.message}`),\n });\n logger.info(\"🤖 MCP server listening on stdio\");\n return handle;\n}\n","/**\n * Option groups that several commands share. Options that map onto a\n * configuration setting declare no yargs `default`, so an omitted flag leaves\n * the setting to the environment, the config file or the built-in default.\n */\n\nimport type { Argv } from \"yargs\";\n\n/**\n * Declare `--public-url` and its deprecated alias `--public-origin`.\n * @param yargs - The command's builder.\n * @returns The builder, for chaining.\n */\nexport function withPublicUrlOptions<T>(yargs: Argv<T>) {\n return yargs\n .option(\"public-url\", {\n type: \"string\",\n description:\n \"Public URL clients use to reach the server, optionally with a path (e.g., https://example.com/docs)\",\n alias: \"publicUrl\",\n })\n .option(\"public-origin\", {\n type: \"string\",\n description: \"Deprecated: use --public-url\",\n alias: \"publicOrigin\",\n });\n}\n\n/**\n * Declare the options that configure authentication for the MCP endpoint.\n * @param yargs - The command's builder.\n * @returns The builder, for chaining.\n */\nexport function withAuthOptions<T>(yargs: Argv<T>) {\n return yargs\n .option(\"auth-enabled\", {\n type: \"boolean\",\n description: \"Require a bearer token on the MCP endpoint over HTTP\",\n defaultDescription: \"false\",\n alias: \"authEnabled\",\n })\n .option(\"auth-issuer-url\", {\n type: \"string\",\n description:\n \"Issuer URL of the OAuth2/OIDC provider; must match the issuer it publishes exactly\",\n alias: \"authIssuerUrl\",\n })\n .option(\"auth-audience\", {\n type: \"string\",\n description: \"Audience tokens must carry; defaults to <public URL>/mcp\",\n alias: \"authAudience\",\n });\n}\n\n/**\n * Declare the options that set how the server identifies itself to MCP\n * clients: name, title and instructions.\n * @param yargs - The command's builder.\n * @returns The builder, for chaining.\n */\nexport function withServerIdentityOptions<T>(yargs: Argv<T>) {\n return yargs\n .option(\"server-name\", {\n type: \"string\",\n description: \"Server name reported to MCP clients (default: docs-mcp-server)\",\n alias: \"serverName\",\n })\n .option(\"server-title\", {\n type: \"string\",\n description: \"Human-readable server title shown by MCP clients\",\n alias: \"serverTitle\",\n })\n .option(\"server-instructions\", {\n type: \"string\",\n description: \"Instructions text sent to MCP clients during initialization\",\n alias: \"serverInstructions\",\n })\n .option(\"server-instructions-file\", {\n type: \"string\",\n description:\n \"Path to a file whose contents are sent to MCP clients as instructions (mutually exclusive with server.instructions; setting both fails startup)\",\n alias: \"serverInstructionsFile\",\n });\n}\n\n/**\n * Declare `--accept-model-change`, which confirms a changed embedding model\n * without a prompt. Without the flag, `DOCS_MCP_ACCEPT_MODEL_CHANGE` decides.\n * @param yargs - The command's builder.\n * @returns The builder, for chaining.\n */\nexport function withModelChangeOptions<T>(yargs: Argv<T>) {\n return yargs.option(\"accept-model-change\", {\n type: \"boolean\",\n description:\n \"Confirm a changed embedding model without a prompt; deletes all stored vectors\",\n defaultDescription: \"false\",\n alias: \"acceptModelChange\",\n });\n}\n","import type { StdioServerHandle } from \"@modelcontextprotocol/server/stdio\";\nimport type { AppServer } from \"../app\";\nimport type { Backend } from \"../services/backend\";\n\n// Module-level variables for active services\nlet activeAppServer: AppServer | null = null;\nlet activeMcpStdioServer: StdioServerHandle | null = null;\nlet activeBackend: Backend | null = null;\n\nexport interface GlobalServices {\n appServer?: AppServer;\n mcpStdioServer?: StdioServerHandle;\n /** The backend a long-running server serves; closed after the server stops. */\n backend?: Backend;\n}\n\n/**\n * Registers global services for shutdown handling\n */\nexport function registerGlobalServices(services: GlobalServices): void {\n if (services.appServer) activeAppServer = services.appServer;\n if (services.mcpStdioServer) activeMcpStdioServer = services.mcpStdioServer;\n if (services.backend) activeBackend = services.backend;\n}\n\nexport function getActiveAppServer(): AppServer | null {\n return activeAppServer;\n}\n\nexport function setActiveAppServer(server: AppServer | null): void {\n activeAppServer = server;\n}\n\nexport function getActiveMcpStdioServer(): StdioServerHandle | null {\n return activeMcpStdioServer;\n}\n\nexport function setActiveMcpStdioServer(server: StdioServerHandle | null): void {\n activeMcpStdioServer = server;\n}\n\n/**\n * Closes the registered backend, if any, and forgets it. Call it after the\n * servers that use the backend have stopped.\n */\nexport async function closeActiveBackend(): Promise<void> {\n const backend = activeBackend;\n activeBackend = null;\n await backend?.close();\n}\n","/**\n * Default command - Starts unified server when no subcommand is specified.\n */\n\nimport type { Argv } from \"yargs\";\nimport { startAppServer } from \"../../app\";\nimport { startStdioServer } from \"../../mcp/startStdioServer\";\nimport { initializeTools } from \"../../mcp/tools\";\nimport { openBackend } from \"../../services/backend\";\nimport { TelemetryEvent, telemetry } from \"../../telemetry\";\nimport { loadConfig } from \"../../utils/config\";\nimport { LogLevel, logger, setLogLevel } from \"../../utils/logger\";\nimport {\n withAuthOptions,\n withModelChangeOptions,\n withPublicUrlOptions,\n withServerIdentityOptions,\n} from \"../options\";\nimport { applyGlobalCliOutputMode } from \"../output\";\nimport { registerGlobalServices } from \"../services\";\nimport {\n type CliContext,\n checkAuthForProtocol,\n createAppServerConfig,\n ensurePlaywrightBrowsersInstalled,\n getEventBus,\n handleEmbeddingModelChange,\n resolveProtocol,\n} from \"../utils\";\n\nexport function createDefaultAction(cli: Argv) {\n cli.command(\n [\"$0\", \"server\"],\n \"Starts the Docs MCP server (Unified Mode)\",\n (yargs) =>\n withAuthOptions(\n withServerIdentityOptions(\n withPublicUrlOptions(\n withModelChangeOptions(yargs)\n .option(\"protocol\", {\n type: \"string\",\n description: \"Protocol for MCP server\",\n choices: [\"auto\", \"stdio\", \"http\"],\n defaultDescription: \"auto\",\n })\n .option(\"port\", {\n type: \"string\", // Keep as string to match old behavior/validation, or number? Using string allows environment variable mapping via loadConfig if strict number parsing isn't desired immediately. Actually validation logic expects string often. But Yargs can parse number.\n description: \"Port for the server\",\n })\n .option(\"host\", {\n type: \"string\",\n description: \"Host to bind the server to\",\n }),\n ),\n )\n .option(\"embedding-model\", {\n type: \"string\",\n description:\n \"Embedding model configuration (e.g., 'openai:text-embedding-3-small')\",\n alias: \"embeddingModel\",\n })\n .option(\"resume\", {\n type: \"boolean\",\n description: \"Resume interrupted jobs on startup\",\n default: false,\n })\n .option(\"read-only\", {\n type: \"boolean\",\n description:\n \"Run in read-only mode (only expose read tools, disable write/job tools)\",\n defaultDescription: \"false\",\n alias: \"readOnly\",\n }),\n ),\n async (argv) => {\n // Options the user did not pass are absent from argv, so the protocol,\n // read-only mode and auth come from env, config file or defaults here.\n // The logger writes to stderr, so loading before the stdio log level is\n // set cannot corrupt the protocol stream on stdout.\n const appConfig = loadConfig(argv, {\n configPath: argv.config as string,\n searchDir: argv.storePath as string,\n });\n\n await telemetry.track(TelemetryEvent.CLI_COMMAND, {\n command: \"default\",\n protocol: appConfig.server.protocol,\n port: argv.port,\n host: argv.host,\n resume: argv.resume,\n readOnly: appConfig.app.readOnly,\n authEnabled: appConfig.auth.enabled,\n });\n\n const resolvedProtocol = resolveProtocol(appConfig.server.protocol);\n if (resolvedProtocol === \"stdio\") {\n setLogLevel(LogLevel.ERROR);\n } else {\n applyGlobalCliOutputMode({\n verbose: argv.verbose as boolean,\n quiet: argv.quiet as boolean,\n });\n }\n\n logger.debug(\"No subcommand specified, starting unified server by default...\");\n\n checkAuthForProtocol(\n appConfig.auth,\n resolvedProtocol,\n appConfig.server.ports.default,\n );\n\n ensurePlaywrightBrowsersInstalled();\n\n const eventBus = getEventBus(argv as CliContext);\n\n const backend = await openBackend({\n appConfig,\n eventBus,\n // A read-only server runs no jobs, so it leaves interrupted ones to the\n // process that does\n jobs: {\n interruptedJobs: appConfig.app.readOnly\n ? \"leave\"\n : argv.resume\n ? \"recover\"\n : \"fail\",\n },\n onEmbeddingModelChange: (error, service) =>\n handleEmbeddingModelChange(\n error,\n service,\n argv.acceptModelChange as boolean | undefined,\n ),\n });\n // Registered first, so shutdown closes it even when a server fails to start\n registerGlobalServices({ backend });\n\n if (resolvedProtocol === \"stdio\") {\n logger.debug(`Auto-detected stdio protocol (no TTY)`);\n const mcpTools = await initializeTools(\n backend.docService,\n backend.pipeline,\n appConfig,\n );\n const mcpServer = await startStdioServer(mcpTools, appConfig);\n\n registerGlobalServices({ mcpStdioServer: mcpServer });\n\n await new Promise(() => {});\n } else {\n logger.debug(`Auto-detected http protocol (TTY available)`);\n const config = createAppServerConfig({\n enableWebInterface: true,\n enableMcpServer: true,\n enableApiServer: true,\n port: appConfig.server.ports.default,\n showLogo: argv.logo as boolean,\n startupContext: {\n cliCommand: \"default\",\n mcpProtocol: \"http\",\n },\n });\n\n const appServer = await startAppServer(backend, config, appConfig);\n\n registerGlobalServices({ appServer });\n\n await new Promise(() => {}); // Keep running\n }\n },\n );\n}\n","/**\n * Fetch URL command - Fetches a URL and converts its content to Markdown.\n */\n\nimport type { Argv } from \"yargs\";\nimport { AutoDetectFetcher } from \"../../scraper/fetcher\";\nimport { ScrapeMode } from \"../../scraper/types\";\nimport {\n extractHostname,\n extractProtocol,\n TelemetryEvent,\n telemetry,\n} from \"../../telemetry\";\nimport { FetchUrlTool } from \"../../tools\";\nimport { loadConfig } from \"../../utils/config\";\nimport { renderTextOutput } from \"../output\";\nimport { ensurePlaywrightBrowsersInstalled, parseHeaders } from \"../utils\";\n\nexport function createFetchUrlCommand(cli: Argv) {\n cli.command(\n \"fetch-url <url>\",\n \"Fetch a URL and transform it into Markdown format\",\n (yargs) => {\n return yargs\n .positional(\"url\", {\n type: \"string\",\n description: \"URL to fetch\",\n demandOption: true,\n })\n .option(\"follow-redirects\", {\n type: \"boolean\",\n description: \"Follow HTTP redirects\",\n default: true,\n })\n .option(\"no-follow-redirects\", {\n type: \"boolean\",\n description: \"Disable following HTTP redirects\",\n hidden: true,\n })\n .option(\"scrape-mode\", {\n choices: Object.values(ScrapeMode),\n description: \"HTML processing strategy\",\n default: ScrapeMode.Auto,\n alias: \"scrapeMode\",\n })\n .option(\"header\", {\n type: \"string\",\n array: true,\n description:\n \"Custom HTTP header to send with the request (can be specified multiple times)\",\n default: [] as string[],\n });\n },\n async (argv) => {\n await telemetry.track(TelemetryEvent.CLI_COMMAND, {\n command: \"fetch-url\",\n url: extractHostname(argv.url as string), // Host only, never the full URL\n urlProtocol: extractProtocol(argv.url as string),\n scrapeMode: argv.scrapeMode,\n followRedirects: argv.followRedirects,\n hasHeaders: (argv.header as string[])?.length > 0,\n });\n\n const url = argv.url as string;\n // parseHeaders expects string[]. Yargs array option gives string[] | undefined (if not default)\n // We set default: [] above.\n const headers = parseHeaders((argv.header as string[]) || []);\n\n const appConfig = loadConfig(argv, {\n configPath: argv.config as string,\n searchDir: argv.storePath as string, // resolved globally\n });\n\n ensurePlaywrightBrowsersInstalled();\n\n const fetchUrlTool = new FetchUrlTool(\n new AutoDetectFetcher(appConfig.scraper),\n appConfig,\n );\n\n const content = await fetchUrlTool.execute({\n url,\n followRedirects: argv.followRedirects as boolean,\n scrapeMode: argv.scrapeMode as ScrapeMode,\n headers: Object.keys(headers).length > 0 ? headers : undefined,\n });\n\n renderTextOutput(content);\n },\n );\n}\n","/**\n * Find version command - Finds the best matching version for a library.\n */\n\nimport type { Argv } from \"yargs\";\nimport { openBackend } from \"../../services/backend\";\nimport { TelemetryEvent, telemetry } from \"../../telemetry\";\nimport { FindVersionTool } from \"../../tools\";\nimport { loadConfig } from \"../../utils/config\";\nimport { renderStructuredOutput } from \"../output\";\nimport { type CliContext, getEventBus } from \"../utils\";\n\nexport function createFindVersionCommand(cli: Argv) {\n cli.command(\n \"find-version <library>\",\n \"Resolve and display the best matching documentation version for a library\",\n (yargs) => {\n return yargs\n .version(false)\n .positional(\"library\", {\n type: \"string\",\n description: \"Library name\",\n demandOption: true,\n })\n .option(\"version\", {\n type: \"string\",\n description: \"Pattern to match (optional, supports ranges)\",\n alias: \"v\",\n })\n .option(\"server-url\", {\n type: \"string\",\n description:\n \"URL of external pipeline worker RPC (e.g., http://localhost:8080/api)\",\n alias: \"serverUrl\",\n });\n },\n async (argv) => {\n await telemetry.track(TelemetryEvent.CLI_COMMAND, {\n command: \"find-version\",\n library: argv.library,\n version: argv.version,\n useServerUrl: !!argv.serverUrl,\n });\n\n const library = argv.library as string;\n const version = argv.version as string | undefined;\n const serverUrl = argv.serverUrl as string | undefined;\n\n const appConfig = loadConfig(argv, {\n configPath: argv.config as string,\n searchDir: argv.storePath as string, // resolved globally\n });\n\n const eventBus = getEventBus(argv as CliContext);\n\n const backend = await openBackend({\n serverUrl,\n eventBus,\n appConfig: appConfig,\n });\n const { docService } = backend;\n try {\n const findVersionTool = new FindVersionTool(docService);\n\n // Call the tool directly - tracking is now handled inside the tool\n const versionInfo = await findVersionTool.execute({\n library,\n targetVersion: version,\n });\n\n if (!versionInfo) throw new Error(\"Failed to get version information\");\n renderStructuredOutput(versionInfo, argv);\n } finally {\n await backend.close();\n }\n },\n );\n}\n","/**\n * List command - Lists all available libraries and their versions.\n */\n\nimport type { Argv } from \"yargs\";\nimport { openBackend } from \"../../services/backend\";\nimport { TelemetryEvent, telemetry } from \"../../telemetry\";\nimport { ListLibrariesTool } from \"../../tools\";\nimport { loadConfig } from \"../../utils/config\";\nimport { renderStructuredOutput } from \"../output\";\nimport { type CliContext, getEventBus } from \"../utils\";\n\nexport function createListCommand(cli: Argv) {\n cli.command(\n \"list\",\n \"List all indexed libraries and their available versions\",\n (yargs) => {\n return yargs.option(\"server-url\", {\n type: \"string\",\n description:\n \"URL of external pipeline worker RPC (e.g., http://localhost:8080/api)\",\n alias: \"serverUrl\",\n });\n },\n async (argv) => {\n await telemetry.track(TelemetryEvent.CLI_COMMAND, {\n command: \"list\",\n useServerUrl: !!argv.serverUrl,\n });\n\n const serverUrl = argv.serverUrl as string | undefined;\n const appConfig = loadConfig(argv, {\n configPath: argv.config as string,\n searchDir: argv.storePath as string, // resolved globally in index.ts middleware\n });\n\n const eventBus = getEventBus(argv as CliContext);\n\n const backend = await openBackend({\n eventBus,\n serverUrl,\n appConfig: appConfig,\n });\n const { docService } = backend;\n try {\n const listLibrariesTool = new ListLibrariesTool(docService);\n\n // Call the tool directly - tracking is now handled inside the tool\n const result = await listLibrariesTool.execute();\n\n renderStructuredOutput(result.libraries, argv);\n } finally {\n await backend.close();\n }\n },\n );\n}\n","/**\n * MCP command - Starts MCP server only.\n */\n\nimport type { Argv } from \"yargs\";\nimport { startAppServer } from \"../../app\";\nimport { startStdioServer } from \"../../mcp/startStdioServer\";\nimport { initializeTools } from \"../../mcp/tools\";\nimport { openBackend } from \"../../services/backend\";\nimport { TelemetryEvent, telemetry } from \"../../telemetry\";\nimport { loadConfig } from \"../../utils/config\";\nimport { LogLevel, logger, setLogLevel } from \"../../utils/logger\";\nimport {\n withAuthOptions,\n withModelChangeOptions,\n withPublicUrlOptions,\n withServerIdentityOptions,\n} from \"../options\";\nimport { applyGlobalCliOutputMode } from \"../output\";\nimport { registerGlobalServices } from \"../services\";\nimport {\n type CliContext,\n checkAuthForProtocol,\n createAppServerConfig,\n ensurePlaywrightBrowsersInstalled,\n getEventBus,\n handleEmbeddingModelChange,\n resolveProtocol,\n validatePort,\n} from \"../utils\";\n\nexport function createMcpCommand(cli: Argv) {\n cli.command(\n \"mcp\",\n \"Start the MCP server (Standalone Mode)\",\n (yargs) =>\n withAuthOptions(\n withServerIdentityOptions(\n withPublicUrlOptions(\n withModelChangeOptions(yargs)\n .option(\"protocol\", {\n type: \"string\",\n description: \"Protocol for MCP server\",\n choices: [\"auto\", \"stdio\", \"http\"],\n defaultDescription: \"auto\",\n })\n .option(\"port\", {\n type: \"string\",\n description: \"Port for the MCP server\",\n })\n .option(\"host\", {\n type: \"string\",\n description: \"Host to bind the MCP server to\",\n }),\n ),\n )\n .option(\"embedding-model\", {\n type: \"string\",\n description:\n \"Embedding model configuration (e.g., 'openai:text-embedding-3-small')\",\n alias: \"embeddingModel\",\n })\n .option(\"server-url\", {\n type: \"string\",\n description:\n \"URL of external pipeline worker RPC (e.g., http://localhost:8080/api)\",\n alias: \"serverUrl\",\n })\n .option(\"read-only\", {\n type: \"boolean\",\n description:\n \"Run in read-only mode (only expose read tools, disable write/job tools)\",\n defaultDescription: \"false\",\n alias: \"readOnly\",\n }),\n ),\n async (argv) => {\n // Reject a malformed --port before anything starts.\n validatePort((argv.port as string) || \"6280\");\n // Options the user did not pass are absent from argv, so the protocol,\n // read-only mode and auth come from env, config file or defaults here.\n // The logger writes to stderr, so loading before the stdio log level is\n // set cannot corrupt the protocol stream on stdout.\n const appConfig = loadConfig(argv, {\n configPath: argv.config as string,\n searchDir: argv.storePath as string, // resolvedStorePath passed via argv by middleware\n });\n\n await telemetry.track(TelemetryEvent.CLI_COMMAND, {\n command: \"mcp\",\n protocol: appConfig.server.protocol,\n port: argv.port,\n host: argv.host,\n useServerUrl: !!argv.serverUrl,\n readOnly: appConfig.app.readOnly,\n authEnabled: appConfig.auth.enabled,\n });\n\n const resolvedProtocol = resolveProtocol(appConfig.server.protocol);\n if (resolvedProtocol === \"stdio\") {\n setLogLevel(LogLevel.ERROR);\n } else {\n applyGlobalCliOutputMode({\n verbose: argv.verbose as boolean,\n quiet: argv.quiet as boolean,\n });\n }\n\n checkAuthForProtocol(appConfig.auth, resolvedProtocol, appConfig.server.ports.mcp);\n\n // The fetch_url tool renders pages here, even when jobs run on a server\n ensurePlaywrightBrowsersInstalled();\n\n try {\n const serverUrl = argv.serverUrl as string | undefined;\n\n const eventBus = getEventBus(argv as CliContext);\n\n const backend = await openBackend({\n appConfig,\n eventBus,\n serverUrl,\n // No job recovery here; a read-only server runs no jobs, so it leaves\n // interrupted ones to the process that does\n jobs: { interruptedJobs: appConfig.app.readOnly ? \"leave\" : \"fail\" },\n onEmbeddingModelChange: (error, service) =>\n handleEmbeddingModelChange(\n error,\n service,\n argv.acceptModelChange as boolean | undefined,\n ),\n });\n // Registered first, so shutdown closes it even when a server fails to start\n registerGlobalServices({ backend });\n\n if (resolvedProtocol === \"stdio\") {\n logger.debug(`Auto-detected stdio protocol (no TTY)`);\n const mcpTools = await initializeTools(\n backend.docService,\n backend.pipeline,\n appConfig,\n );\n const mcpServer = await startStdioServer(mcpTools, appConfig);\n\n registerGlobalServices({ mcpStdioServer: mcpServer });\n\n await new Promise(() => {});\n } else {\n logger.debug(`Auto-detected http protocol (TTY available)`);\n const config = createAppServerConfig({\n enableWebInterface: false,\n enableMcpServer: true,\n enableApiServer: false,\n port: appConfig.server.ports.mcp,\n showLogo: argv.logo as boolean,\n startupContext: {\n cliCommand: \"mcp\",\n mcpProtocol: \"http\",\n },\n });\n\n const appServer = await startAppServer(backend, config, appConfig);\n\n registerGlobalServices({ appServer });\n\n await new Promise(() => {});\n }\n } catch (error) {\n logger.error(`❌ Failed to start MCP server: ${error}`);\n process.exit(1);\n }\n },\n );\n}\n","/**\n * Narrows the job events on a bus to the one job a CLI command submitted.\n */\n\nimport type { EventBusService } from \"../events/EventBusService\";\nimport { EventType } from \"../events/types\";\nimport { type PipelineJob, PipelineJobStatus } from \"../pipeline/types\";\nimport type { ScraperProgressEvent } from \"../scraper/types\";\nimport { logger } from \"../utils/logger\";\n\n/** What a command does with the events of its own job. */\nexport interface JobOutputHandlers {\n onStatus(job: PipelineJob): void;\n onProgress(job: PipelineJob, progress: ScraperProgressEvent): void;\n}\n\n/**\n * Passes a command the status and progress events of the job it submitted, and\n * no others. A shared worker runs jobs for several clients, and a job can start\n * and report before the command learns its id, so the follower subscribes\n * before the job is submitted, buffers what arrives, and replays that job's\n * events once {@link follow} names it.\n */\nexport class JobOutputFollower {\n /** Events received before {@link follow} named the job, ready to hand on. */\n private buffered: Array<{ jobId: string; deliver: () => void }> = [];\n private jobId: string | null = null;\n private readonly unsubscribers: Array<() => void>;\n\n /**\n * Subscribes right away; create it before submitting the job.\n *\n * @param eventBus The bus the job's events arrive on.\n * @param handlers What to do with the followed job's events.\n */\n constructor(eventBus: EventBusService, handlers: JobOutputHandlers) {\n this.unsubscribers = [\n eventBus.on(EventType.JOB_STATUS_CHANGE, (job) =>\n this.receive(job.id, () => handlers.onStatus(job)),\n ),\n eventBus.on(EventType.JOB_PROGRESS, ({ job, progress }) =>\n this.receive(job.id, () => handlers.onProgress(job, progress)),\n ),\n ];\n }\n\n /**\n * Follows `jobId`: replays its buffered events in order, drops the rest, and\n * passes on its events from now on.\n *\n * @param jobId The id of the job the command submitted.\n */\n follow(jobId: string): void {\n this.jobId = jobId;\n for (const event of this.buffered.splice(0)) {\n this.receive(event.jobId, event.deliver);\n }\n }\n\n /** Stops listening. Safe to call more than once. */\n dispose(): void {\n for (const unsubscribe of this.unsubscribers.splice(0)) {\n unsubscribe();\n }\n this.buffered = [];\n }\n\n private receive(jobId: string, deliver: () => void): void {\n if (this.jobId === null) {\n this.buffered.push({ jobId, deliver });\n } else if (jobId === this.jobId) {\n deliver();\n }\n }\n}\n\n/**\n * Follows a command's job and logs its start and progress the way `scrape` and\n * `refresh` report them, e.g. `🚀 Scraping react v18...` and\n * `📄 Scraping react v18: 3/10 pages`.\n *\n * @param eventBus The bus the job's events arrive on.\n * @param verb The activity the lines name.\n * @returns The follower; call `follow()` with the job's id and `dispose()` when done.\n */\nexport function followJobLogs(\n eventBus: EventBusService,\n verb: \"Scraping\" | \"Refreshing\",\n): JobOutputFollower {\n const label = (job: PipelineJob) =>\n `${job.library}${job.version ? ` v${job.version}` : \"\"}`;\n return new JobOutputFollower(eventBus, {\n onStatus: (job) => {\n if (job.status === PipelineJobStatus.RUNNING) {\n logger.info(`🚀 ${verb} ${label(job)}...`);\n }\n },\n onProgress: (job, progress) => {\n logger.info(\n `📄 ${verb} ${label(job)}: ${progress.pagesScraped}/${progress.totalPages} pages`,\n );\n },\n });\n}\n","/**\n * Refresh command - Re-scrapes an existing library version using ETags to skip unchanged pages.\n */\n\nimport type { Argv } from \"yargs\";\nimport { openBackend } from \"../../services/backend\";\nimport { TelemetryEvent, telemetry } from \"../../telemetry\";\nimport { RefreshVersionTool } from \"../../tools/RefreshVersionTool\";\nimport { loadConfig } from \"../../utils/config\";\nimport { logger } from \"../../utils/logger\";\nimport { followJobLogs } from \"../JobOutputFollower\";\nimport { renderTextOutput } from \"../output\";\nimport { registerGlobalServices } from \"../services\";\nimport {\n type CliContext,\n ensurePlaywrightBrowsersInstalled,\n getEventBus,\n} from \"../utils\";\n\nexport function createRefreshCommand(cli: Argv) {\n cli.command(\n \"refresh <library>\",\n \"Update an existing library version by re-scraping changed pages\",\n (yargs) => {\n return yargs\n .version(false)\n .positional(\"library\", {\n type: \"string\",\n description: \"Library name to refresh\",\n demandOption: true,\n })\n .option(\"version\", {\n type: \"string\",\n description: \"Version of the library (optional)\",\n alias: \"v\",\n })\n .option(\"preserve-hashes\", {\n type: \"boolean\",\n description: \"Override the stored hash-route setting for this refresh job\",\n alias: \"preserveHashes\",\n })\n .option(\"embedding-model\", {\n type: \"string\",\n description:\n \"Embedding model configuration (e.g., 'openai:text-embedding-3-small')\",\n alias: \"embeddingModel\",\n })\n .option(\"server-url\", {\n type: \"string\",\n description:\n \"URL of external pipeline worker RPC (e.g., http://localhost:8080/api)\",\n alias: \"serverUrl\",\n })\n .usage(\n \"$0 refresh <library> [options]\\n\\n\" +\n \"Uses HTTP ETags to efficiently skip unchanged pages and only re-process\\n\" +\n \"content that has been modified or deleted since the last scrape.\\n\\n\" +\n \"Examples:\\n\" +\n \" refresh react --version 18.0.0\\n\" +\n \" refresh mylib\\n\" +\n \"\\nNote: The library and version must already be indexed. Use 'scrape' to index a new library/version.\",\n );\n },\n async (argv) => {\n await telemetry.track(TelemetryEvent.CLI_COMMAND, {\n command: \"refresh\",\n library: argv.library,\n version: argv.version,\n preserveHashes: argv.preserveHashes,\n useServerUrl: !!argv.serverUrl,\n });\n\n const library = argv.library as string;\n const version = argv.version as string | undefined;\n const serverUrl = argv.serverUrl as string | undefined;\n\n const appConfig = loadConfig(argv, {\n configPath: argv.config as string,\n searchDir: argv.storePath as string,\n });\n\n // With a server URL, the server runs the job and its browser\n if (!serverUrl) {\n ensurePlaywrightBrowsersInstalled();\n }\n\n const eventBus = getEventBus(argv as CliContext);\n\n const backend = await openBackend({\n serverUrl,\n eventBus,\n appConfig,\n // Runs only its own job; the process hosting the store handles the rest\n jobs: { interruptedJobs: \"leave\" },\n });\n\n // Display initial status\n logger.info(\"⏳ Initializing refresh job...\");\n\n registerGlobalServices({ backend });\n\n // Report this command's own job; a shared worker also runs other clients' jobs\n const follower = followJobLogs(backend.eventBus, \"Refreshing\");\n\n try {\n const refreshTool = new RefreshVersionTool(backend.pipeline);\n\n // Call the tool directly - tracking is now handled inside the tool\n const result = await refreshTool.execute({\n onJobEnqueued: (jobId) => follower.follow(jobId),\n library,\n version,\n preserveHashes: argv.preserveHashes as boolean | undefined,\n waitForCompletion: true, // Always wait for completion in CLI\n });\n\n if (\"pagesRefreshed\" in result) {\n renderTextOutput(`Successfully refreshed ${result.pagesRefreshed} pages`);\n } else {\n renderTextOutput(`Refresh job started with ID: ${result.jobId}`);\n }\n } catch (error) {\n logger.error(\n `❌ Refresh failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n throw error;\n } finally {\n follower.dispose();\n\n await backend.close();\n }\n },\n );\n}\n","/**\n * Remove command - Removes a library version, and the library with its last version.\n */\n\nimport type { Argv } from \"yargs\";\nimport { openBackend } from \"../../services/backend\";\nimport { TelemetryEvent, telemetry } from \"../../telemetry\";\nimport { RemoveTool } from \"../../tools/RemoveTool\";\nimport { loadConfig } from \"../../utils/config\";\nimport { renderTextOutput } from \"../output\";\nimport { type CliContext, getEventBus } from \"../utils\";\n\nexport function createRemoveCommand(cli: Argv) {\n cli.command(\n \"remove <library>\",\n \"Remove a library version from the index, and the library with its last version\",\n (yargs) => {\n return yargs\n .version(false)\n .positional(\"library\", {\n type: \"string\",\n description: \"Library name to remove\",\n demandOption: true,\n })\n .option(\"version\", {\n type: \"string\",\n description:\n \"Version to remove; omit it to remove the unversioned documentation\",\n alias: \"v\",\n })\n .option(\"server-url\", {\n type: \"string\",\n description:\n \"URL of external pipeline worker RPC (e.g., http://localhost:8080/api)\",\n alias: \"serverUrl\",\n });\n },\n async (argv) => {\n await telemetry.track(TelemetryEvent.CLI_COMMAND, {\n command: \"remove\",\n library: argv.library,\n version: argv.version,\n useServerUrl: !!argv.serverUrl,\n });\n\n const library = argv.library as string;\n const version = argv.version as string | undefined;\n const serverUrl = argv.serverUrl as string | undefined;\n\n const appConfig = loadConfig(argv, {\n configPath: argv.config as string,\n searchDir: argv.storePath as string, // resolved globally\n });\n\n const eventBus = getEventBus(argv as CliContext);\n\n // The same removal as remove_docs. Against a worker, the worker cancels\n // its job for the version first; locally this process runs no jobs.\n const backend = await openBackend({ serverUrl, eventBus, appConfig });\n try {\n // RemoveTool logs its own failure, prefixed once\n const { message } = await new RemoveTool(\n backend.docService,\n backend.pipeline,\n ).execute({ library, version });\n renderTextOutput(message);\n } finally {\n await backend.close();\n }\n },\n );\n}\n","/**\n * Scrape command - Scrapes and indexes documentation from a URL or local folder.\n */\n\nimport type { Argv } from \"yargs\";\nimport { ScrapeMode } from \"../../scraper/types\";\nimport { openBackend } from \"../../services/backend\";\nimport {\n extractHostname,\n extractProtocol,\n TelemetryEvent,\n telemetry,\n} from \"../../telemetry\";\nimport { ScrapeTool } from \"../../tools\";\nimport { loadConfig } from \"../../utils/config\";\nimport { logger } from \"../../utils/logger\";\nimport { followJobLogs } from \"../JobOutputFollower\";\nimport { renderTextOutput } from \"../output\";\nimport { registerGlobalServices } from \"../services\";\nimport {\n type CliContext,\n ensurePlaywrightBrowsersInstalled,\n getEventBus,\n parseHeaders,\n} from \"../utils\";\n\nexport function createScrapeCommand(cli: Argv) {\n cli.command(\n \"scrape <library> <url>\",\n \"Download and index documentation from a URL or local directory\",\n (yargs) => {\n return yargs\n .version(false)\n .positional(\"library\", {\n type: \"string\",\n description: \"Library name\",\n demandOption: true,\n })\n .positional(\"url\", {\n type: \"string\",\n description: \"URL or file:// path to scrape\",\n demandOption: true,\n })\n .option(\"version\", {\n type: \"string\",\n description: \"Version of the library (optional)\",\n alias: \"v\",\n })\n .option(\"max-pages\", {\n type: \"number\",\n description: \"Maximum pages to scrape\",\n alias: [\"p\", \"maxPages\"],\n })\n .option(\"max-depth\", {\n type: \"number\",\n description: \"Maximum navigation depth\",\n alias: [\"d\", \"maxDepth\"],\n })\n .option(\"max-concurrency\", {\n type: \"number\",\n description: \"Maximum concurrent page requests\",\n alias: [\"c\", \"maxConcurrency\"],\n })\n .option(\"ignore-errors\", {\n type: \"boolean\",\n description: \"Ignore errors during scraping\",\n default: true,\n alias: \"ignoreErrors\",\n })\n .option(\"scope\", {\n choices: [\"subpages\", \"hostname\", \"domain\"],\n description: \"Crawling boundary\",\n default: \"subpages\",\n })\n .option(\"follow-redirects\", {\n type: \"boolean\",\n description: \"Follow HTTP redirects\",\n default: true,\n alias: \"followRedirects\",\n })\n .option(\"no-follow-redirects\", {\n type: \"boolean\",\n description: \"Disable following HTTP redirects\",\n hidden: true,\n })\n .option(\"scrape-mode\", {\n choices: Object.values(ScrapeMode),\n description: \"HTML processing strategy\",\n default: ScrapeMode.Auto,\n alias: \"scrapeMode\",\n })\n .option(\"preserve-hashes\", {\n type: \"boolean\",\n description:\n \"Preserve URL hash fragments for hash-routed SPA documentation sites\",\n alias: \"preserveHashes\",\n })\n .option(\"include-pattern\", {\n type: \"string\",\n array: true,\n description:\n \"Glob or regex pattern for URLs to include (can be specified multiple times). Regex patterns must be wrapped in slashes, e.g. /pattern/.\",\n alias: \"includePattern\",\n default: [] as string[],\n })\n .option(\"exclude-pattern\", {\n type: \"string\",\n array: true,\n description:\n \"Glob or regex pattern for URLs to exclude (can be specified multiple times, takes precedence over include). Regex patterns must be wrapped in slashes, e.g. /pattern/.\",\n alias: \"excludePattern\",\n default: [] as string[],\n })\n .option(\"header\", {\n type: \"string\",\n array: true,\n description:\n \"Custom HTTP header to send with each request (can be specified multiple times)\",\n default: [] as string[],\n })\n .option(\"embedding-model\", {\n type: \"string\",\n description:\n \"Embedding model configuration (e.g., 'openai:text-embedding-3-small')\",\n alias: \"embeddingModel\",\n })\n .option(\"server-url\", {\n type: \"string\",\n description:\n \"URL of external pipeline worker RPC (e.g., http://localhost:8080/api)\",\n alias: \"serverUrl\",\n })\n .option(\"clean\", {\n type: \"boolean\",\n description: \"Clear existing documents before scraping\",\n default: true,\n })\n .option(\"replace\", {\n type: \"boolean\",\n description:\n \"Rebuild the library version if it already exists (without it, an existing version is left untouched and the command fails)\",\n default: false,\n })\n .usage(\n \"$0 scrape <library> <url> [options]\\n\\n\" +\n \"Scrape and index documentation from a URL or local folder.\\n\\n\" +\n \"Scraping a library version that already exists fails unless --replace is given;\\n\" +\n \"use `refresh` to update it in place, or --no-clean to add to it.\\n\\n\" +\n \"To scrape local files or folders, use a file:// URL.\\n\" +\n \"Examples:\\n\" +\n \" scrape mylib https://react.dev/reference/react\\n\" +\n \" scrape mylib file:///Users/me/docs/index.html\\n\" +\n \" scrape mylib file:///Users/me/docs/my-library\\n\" +\n \"\\nNote: For local files/folders, you must use the file:// prefix. If running in Docker, mount the folder and use the container path. See README for details.\",\n );\n },\n async (argv) => {\n const library = argv.library as string;\n const url = argv.url as string;\n const serverUrl = argv.serverUrl as string | undefined;\n\n const appConfig = loadConfig(argv, {\n configPath: argv.config as string,\n searchDir: argv.storePath as string, // resolved globally\n });\n\n const maxPages = (argv.maxPages as number) ?? appConfig.scraper.maxPages;\n const maxDepth = (argv.maxDepth as number) ?? appConfig.scraper.maxDepth;\n const maxConcurrency =\n (argv.maxConcurrency as number) ?? appConfig.scraper.maxConcurrency;\n const preserveHashes =\n typeof argv.preserveHashes === \"boolean\"\n ? (argv.preserveHashes as boolean)\n : appConfig.scraper.preserveHashes;\n\n // Update appConfig with effective values\n appConfig.scraper.maxPages = maxPages;\n appConfig.scraper.maxDepth = maxDepth;\n appConfig.scraper.maxConcurrency = maxConcurrency;\n\n await telemetry.track(TelemetryEvent.CLI_COMMAND, {\n command: \"scrape\",\n library,\n version: argv.version,\n url: extractHostname(url), // Host only, never the full URL\n urlProtocol: extractProtocol(url),\n maxPages,\n maxDepth,\n maxConcurrency,\n scope: argv.scope,\n scrapeMode: argv.scrapeMode,\n preserveHashes,\n followRedirects: argv.followRedirects,\n hasHeaders: (argv.header as string[]).length > 0,\n hasIncludePatterns: (argv.includePattern as string[]).length > 0,\n hasExcludePatterns: (argv.excludePattern as string[]).length > 0,\n useServerUrl: !!serverUrl,\n });\n\n // With a server URL, the server runs the job and its browser\n if (!serverUrl) {\n ensurePlaywrightBrowsersInstalled();\n }\n\n const eventBus = getEventBus(argv as CliContext);\n\n const backend = await openBackend({\n serverUrl,\n eventBus,\n appConfig,\n // Runs only its own job; the process hosting the store handles the rest\n jobs: { interruptedJobs: \"leave\" },\n });\n\n // Display initial status\n logger.info(\"⏳ Initializing scraping job...\");\n\n registerGlobalServices({ backend });\n\n // Report this command's own job; a shared worker also runs other clients' jobs\n const follower = followJobLogs(backend.eventBus, \"Scraping\");\n\n try {\n const scrapeTool = new ScrapeTool(backend.pipeline, appConfig.scraper);\n\n const headers = parseHeaders((argv.header as string[]) || []);\n\n const result = await scrapeTool.execute({\n onJobEnqueued: (jobId) => follower.follow(jobId),\n url,\n library,\n version: argv.version as string | undefined,\n replace: argv.replace as boolean,\n options: {\n maxPages,\n maxDepth,\n maxConcurrency,\n ignoreErrors: argv.ignoreErrors as boolean,\n scope: argv.scope as \"subpages\" | \"hostname\" | \"domain\",\n followRedirects: argv.followRedirects as boolean,\n scrapeMode: argv.scrapeMode as ScrapeMode,\n preserveHashes,\n includePatterns:\n (argv.includePattern as string[])?.length > 0\n ? (argv.includePattern as string[])\n : undefined,\n excludePatterns:\n (argv.excludePattern as string[])?.length > 0\n ? (argv.excludePattern as string[])\n : undefined,\n headers: Object.keys(headers).length > 0 ? headers : undefined,\n clean: argv.clean as boolean,\n },\n });\n\n if (\"pagesScraped\" in result) {\n renderTextOutput(`Successfully scraped ${result.pagesScraped} pages`);\n } else {\n renderTextOutput(`Scraping job started with ID: ${result.jobId}`);\n }\n } catch (error) {\n logger.error(\n `❌ Scraping failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n throw error;\n } finally {\n follower.dispose();\n\n await backend.close();\n }\n },\n );\n}\n","/**\n * Search command - Searches documents in a library.\n */\n\nimport type { Argv } from \"yargs\";\nimport { openBackend } from \"../../services/backend\";\nimport { TelemetryEvent, telemetry } from \"../../telemetry\";\nimport { SearchTool } from \"../../tools\";\nimport { loadConfig } from \"../../utils/config\";\nimport { renderStructuredOutput } from \"../output\";\nimport { type CliContext, getEventBus } from \"../utils\";\n\nexport function createSearchCommand(cli: Argv) {\n cli.command(\n \"search <library> <query>\",\n \"Query the documentation index used by the MCP server\",\n (yargs) => {\n return yargs\n .version(false)\n .positional(\"library\", {\n type: \"string\",\n description: \"Library name\",\n demandOption: true,\n })\n .positional(\"query\", {\n type: \"string\",\n description: \"Search query\",\n demandOption: true,\n })\n .option(\"version\", {\n type: \"string\",\n description: \"Version of the library (optional, supports ranges)\",\n alias: \"v\",\n })\n .option(\"limit\", {\n type: \"number\",\n description: \"Maximum number of results\",\n alias: \"l\",\n default: 5,\n })\n .option(\"exact-match\", {\n type: \"boolean\",\n description: \"Only use exact version match\",\n default: false,\n alias: [\"e\", \"exactMatch\"],\n })\n .option(\"embedding-model\", {\n type: \"string\",\n description:\n \"Embedding model configuration (e.g., 'openai:text-embedding-3-small')\",\n alias: \"embeddingModel\",\n })\n .option(\"server-url\", {\n type: \"string\",\n description:\n \"URL of external pipeline worker RPC (e.g., http://localhost:8080/api)\",\n alias: \"serverUrl\",\n })\n .usage(\n \"$0 search <library> <query> [options]\\n\\n\" +\n \"Search documents in a library. Version matching examples:\\n\" +\n \" - search react --version 18.0.0 'hooks' -> matches docs for React 18.0.0 or earlier versions\\n\" +\n \" - search react --version 18.0.0 'hooks' --exact-match -> only matches React 18.0.0\\n\" +\n \" - search typescript --version 5.x 'types' -> matches any TypeScript 5.x.x version\\n\" +\n \" - search typescript --version 5.2.x 'types' -> matches any TypeScript 5.2.x version\",\n );\n },\n async (argv) => {\n await telemetry.track(TelemetryEvent.CLI_COMMAND, {\n command: \"search\",\n library: argv.library,\n version: argv.version,\n queryLength: (argv.query as string).length, // Never the query itself\n limit: argv.limit,\n exactMatch: argv.exactMatch,\n useServerUrl: !!argv.serverUrl,\n });\n\n const library = argv.library as string;\n const query = argv.query as string;\n const limit = argv.limit as number;\n const serverUrl = argv.serverUrl as string | undefined;\n\n const appConfig = loadConfig(argv, {\n configPath: argv.config as string,\n searchDir: argv.storePath as string, // resolved globally\n });\n\n const eventBus = getEventBus(argv as CliContext);\n\n const backend = await openBackend({\n serverUrl,\n eventBus,\n appConfig: appConfig,\n });\n const { docService } = backend;\n\n try {\n const searchTool = new SearchTool(docService);\n\n // Call the tool directly - tracking is now handled inside the tool\n const result = await searchTool.execute({\n library,\n version: argv.version as string | undefined,\n query,\n limit,\n exactMatch: argv.exactMatch as boolean,\n });\n\n renderStructuredOutput(result.results, argv);\n } finally {\n await backend.close();\n }\n },\n );\n}\n","/**\n * Web command - Starts web interface only.\n */\n\nimport type { Argv } from \"yargs\";\nimport { startAppServer } from \"../../app\";\nimport { openBackend } from \"../../services/backend\";\nimport { TelemetryEvent, telemetry } from \"../../telemetry\";\nimport { loadConfig } from \"../../utils/config\";\nimport { logger } from \"../../utils/logger\";\nimport { withPublicUrlOptions } from \"../options\";\nimport { registerGlobalServices } from \"../services\";\nimport {\n type CliContext,\n createAppServerConfig,\n ensurePlaywrightBrowsersInstalled,\n getEventBus,\n validateHost,\n validatePort,\n} from \"../utils\";\n\nexport function createWebCommand(cli: Argv) {\n cli.command(\n \"web\",\n \"Start the web dashboard (Standalone Mode)\",\n (yargs) => {\n return withPublicUrlOptions(\n yargs\n .option(\"port\", {\n type: \"string\",\n description: \"Port for the web interface\",\n })\n .option(\"host\", {\n type: \"string\",\n description: \"Host to bind the web interface to\",\n }),\n )\n .option(\"embedding-model\", {\n type: \"string\",\n description:\n \"Embedding model configuration (e.g., 'openai:text-embedding-3-small')\",\n alias: \"embeddingModel\",\n })\n .option(\"server-url\", {\n type: \"string\",\n description:\n \"URL of external pipeline worker RPC (e.g., http://localhost:8080/api)\",\n alias: \"serverUrl\",\n });\n },\n async (argv) => {\n await telemetry.track(TelemetryEvent.CLI_COMMAND, {\n command: \"web\",\n port: argv.port,\n host: argv.host,\n useServerUrl: !!argv.serverUrl,\n });\n\n const _port = validatePort((argv.port as string) || \"6281\"); // Fallback for validation, defaults via loadConfig\n const _host = validateHost((argv.host as string) || \"127.0.0.1\");\n const serverUrl = argv.serverUrl as string | undefined;\n\n const appConfig = loadConfig(argv, {\n configPath: argv.config as string,\n // searchDir resolved via globalStorePath in index.ts -> available in appConfig?\n // loadConfig needs options to find file.\n searchDir: argv.storePath as string,\n });\n\n // With a server URL, the server runs the jobs and their browser\n if (!serverUrl) {\n ensurePlaywrightBrowsersInstalled();\n }\n\n try {\n const eventBus = getEventBus(argv as CliContext);\n\n const backend = await openBackend({\n appConfig,\n eventBus,\n serverUrl,\n jobs: { interruptedJobs: \"fail\" }, // Web command doesn't support job recovery\n });\n // Registered first, so shutdown closes it even when a server fails to start\n registerGlobalServices({ backend });\n\n // Configure web-only server\n const config = createAppServerConfig({\n enableWebInterface: true,\n enableMcpServer: false,\n enableApiServer: true,\n port: appConfig.server.ports.web,\n showLogo: argv.logo as boolean,\n startupContext: {\n cliCommand: \"web\",\n },\n });\n\n const appServer = await startAppServer(backend, config, appConfig);\n\n registerGlobalServices({ appServer });\n\n await new Promise(() => {}); // Keep running forever\n } catch (error) {\n logger.error(`❌ Failed to start web interface: ${error}`);\n process.exit(1);\n }\n },\n );\n}\n","/**\n * Worker command - Starts external pipeline worker (HTTP API).\n */\n\nimport type { Argv } from \"yargs\";\nimport { startAppServer } from \"../../app\";\nimport { openBackend } from \"../../services/backend\";\nimport { TelemetryEvent, telemetry } from \"../../telemetry\";\nimport { loadConfig } from \"../../utils/config\";\nimport { logger } from \"../../utils/logger\";\nimport { withModelChangeOptions, withPublicUrlOptions } from \"../options\";\nimport { registerGlobalServices } from \"../services\";\nimport {\n type CliContext,\n createAppServerConfig,\n ensurePlaywrightBrowsersInstalled,\n getEventBus,\n handleEmbeddingModelChange,\n validateHost,\n validatePort,\n} from \"../utils\";\n\nexport function createWorkerCommand(cli: Argv) {\n cli.command(\n \"worker\",\n \"Start a background worker for processing scraping jobs\",\n (yargs) => {\n return withPublicUrlOptions(\n withModelChangeOptions(yargs)\n .option(\"port\", {\n type: \"string\",\n description: \"Port for worker API\",\n })\n .option(\"host\", {\n type: \"string\",\n description: \"Host to bind the worker API to\",\n }),\n )\n .option(\"embedding-model\", {\n type: \"string\",\n description:\n \"Embedding model configuration (e.g., 'openai:text-embedding-3-small')\",\n alias: \"embeddingModel\",\n })\n .option(\"resume\", {\n type: \"boolean\",\n description: \"Resume interrupted jobs on startup\",\n default: true,\n })\n .option(\"no-resume\", {\n type: \"boolean\",\n // Yargs handles boolean flags specially, --no-resume implies resume=false\n // But strict mode might complain if we don't define 'resume'\n // 'resume' defaulting to true handles --no-resume correctly in Yargs\n hidden: true,\n });\n },\n async (argv) => {\n await telemetry.track(TelemetryEvent.CLI_COMMAND, {\n command: \"worker\",\n port: argv.port,\n host: argv.host,\n resume: argv.resume,\n });\n\n const _port = validatePort((argv.port as string) || \"8080\");\n const _host = validateHost((argv.host as string) || \"127.0.0.1\");\n\n const appConfig = loadConfig(argv, {\n configPath: argv.config as string,\n searchDir: argv.storePath as string, // resolved globally in index.ts middleware\n });\n\n try {\n // Ensure browsers are installed for scraping\n ensurePlaywrightBrowsersInstalled();\n\n const eventBus = getEventBus(argv as CliContext);\n\n const backend = await openBackend({\n appConfig,\n eventBus,\n jobs: {\n interruptedJobs: ((argv.resume as boolean) ?? true) ? \"recover\" : \"fail\",\n },\n onEmbeddingModelChange: (error, service) =>\n handleEmbeddingModelChange(\n error,\n service,\n argv.acceptModelChange as boolean | undefined,\n ),\n });\n // Registered first, so shutdown closes it even when a server fails to start\n registerGlobalServices({ backend });\n\n // Configure worker-only server\n const config = createAppServerConfig({\n enableWebInterface: false,\n enableMcpServer: false,\n enableApiServer: true,\n port: appConfig.server.ports.worker,\n showLogo: argv.logo as boolean,\n startupContext: {\n cliCommand: \"worker\",\n },\n });\n\n const appServer = await startAppServer(backend, config, appConfig);\n\n registerGlobalServices({ appServer });\n\n await new Promise(() => {}); // Keep running forever\n } catch (error) {\n logger.error(`❌ Failed to start external pipeline worker: ${error}`);\n process.exit(1);\n }\n },\n );\n}\n","/**\n * Main CLI setup and command registration using Yargs.\n */\n\nimport yargs, { type Argv } from \"yargs\";\nimport { hideBin } from \"yargs/helpers\";\nimport { EventBusService } from \"../events\";\nimport { initTelemetry, shouldEnableTelemetry, telemetry } from \"../telemetry\";\nimport { loadConfig } from \"../utils/config\";\nimport { resolveStorePath } from \"../utils/paths\";\n// Commands\nimport { createCompactCommand } from \"./commands/compact\";\nimport { createConfigCommand } from \"./commands/config\";\nimport { createDefaultAction } from \"./commands/default\";\nimport { createFetchUrlCommand } from \"./commands/fetchUrl\";\nimport { createFindVersionCommand } from \"./commands/findVersion\";\nimport { createListCommand } from \"./commands/list\";\nimport { createMcpCommand } from \"./commands/mcp\";\nimport { createRefreshCommand } from \"./commands/refresh\";\nimport { createRemoveCommand } from \"./commands/remove\";\nimport { createScrapeCommand } from \"./commands/scrape\";\nimport { createSearchCommand } from \"./commands/search\";\nimport { createWebCommand } from \"./commands/web\";\nimport { createWorkerCommand } from \"./commands/worker\";\nimport { applyGlobalCliOutputMode, registerGlobalOutputOptions } from \"./output\";\n\n/**\n * A command line that does not parse, such as an unknown option or a missing\n * argument. The CLI has already printed the help and the reason when it throws\n * this.\n */\nexport class CliUsageError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CliUsageError\";\n }\n}\n\n/** Every command the CLI registers. */\nexport const COMMAND_FACTORIES: ReadonlyArray<(cli: Argv) => void> = [\n createCompactCommand,\n createConfigCommand,\n createDefaultAction,\n createFetchUrlCommand,\n createFindVersionCommand,\n createListCommand,\n createMcpCommand,\n createRefreshCommand,\n createRemoveCommand,\n createScrapeCommand,\n createSearchCommand,\n createWebCommand,\n createWorkerCommand,\n];\n\n/**\n * Declares the options that every command accepts.\n *\n * @param cli - The root yargs instance.\n * @returns The same instance, for chaining.\n */\nexport function registerGlobalOptions<T>(cli: Argv<T>) {\n return registerGlobalOutputOptions(cli)\n .option(\"verbose\", {\n type: \"boolean\",\n description: \"Enable verbose (debug) logging\",\n default: false,\n })\n .option(\"quiet\", {\n type: \"boolean\",\n description: \"Disable all logging except errors\",\n default: false,\n alias: [\"silent\"],\n })\n .option(\"telemetry\", {\n type: \"boolean\",\n description: \"Enable/disable telemetry collection\",\n // yargs handles boolean logic for --no-telemetry automatically if strictly typed\n // but we want tri-state or env var handling.\n // Yargs doesn't naturally do \"default: true, but respecting env var DOCS_MCP_TELEMETRY\"\n // without middleware overriding.\n default: undefined, // Let config loader handle defaults\n })\n .option(\"store-path\", {\n type: \"string\",\n description: \"Custom path for data storage directory\",\n alias: \"storePath\",\n })\n .option(\"config\", {\n type: \"string\",\n description: \"Path to configuration file\",\n })\n .option(\"logo\", {\n type: \"boolean\",\n description: \"Show ASCII art logo on startup\",\n default: true,\n });\n}\n\n/**\n * Creates and configures the main CLI program with all commands.\n */\nexport function createCli(argv: string[]): Argv {\n // Global service instances\n let globalEventBus: EventBusService | null = null;\n const commandStartTimes = new Map<string, number>();\n\n const cli = registerGlobalOptions(yargs(hideBin(argv)))\n .scriptName(\"docs-mcp-server\")\n .strict()\n .usage(\"Usage: $0 <command> [options]\")\n .version(__APP_VERSION__)\n // Middleware for Global Setup (similar to preAction)\n .middleware(async (argv) => {\n // 0. Validate Options\n if (argv.verbose && argv.quiet) {\n throw new Error(\"Arguments verbose and quiet are mutually exclusive\");\n }\n\n // 1. Setup Logging, first, so --verbose also covers a failure below\n applyGlobalCliOutputMode({\n verbose: argv.verbose as boolean,\n quiet: argv.quiet as boolean,\n });\n\n // 2. Load Config & Resolve Paths\n const rawStorePath = (argv.storePath as string) || process.env.DOCS_MCP_STORE_PATH;\n const resolvedStorePath = resolveStorePath(rawStorePath);\n\n // Mutate argv to use resolved path\n argv.storePath = resolvedStorePath;\n\n const appConfig = loadConfig(argv, {\n configPath: argv.config as string,\n searchDir: resolvedStorePath,\n });\n\n // Update options with config values if not set by CLI\n if (argv.telemetry === undefined) {\n argv.telemetry = appConfig.app.telemetryEnabled;\n }\n\n // 3. Init Telemetry\n initTelemetry({\n enabled: !!argv.telemetry,\n storePath: resolvedStorePath,\n });\n\n // 4. Init Services\n if (!globalEventBus) {\n globalEventBus = new EventBusService();\n }\n\n // 5. Attach to argv context\n // This makes global services available to all commands\n argv._eventBus = globalEventBus;\n\n // 6. Telemetry Context\n if (shouldEnableTelemetry() && telemetry.isEnabled()) {\n const commandName = argv._[0]?.toString() || \"default\";\n telemetry.setGlobalContext({\n appVersion: __APP_VERSION__,\n appPlatform: process.platform,\n appNodeVersion: process.version,\n appInterface: \"cli\",\n cliCommand: commandName,\n });\n\n const commandKey = `${commandName}-${Date.now()}`;\n commandStartTimes.set(commandKey, Date.now());\n argv._trackingKey = commandKey;\n }\n })\n // Post-command tracking is handled by yargs 'onFinishCommand' or similar?\n // Yargs doesn't have a direct 'postAction' hook for all commands easily.\n // We can handle it in the handler wrapper or use 'onFinishCommand' if available (it isn't).\n // An alternative is using middleware that runs after? No.\n // We will rely on explicit telemetry calls in command handlers or wrap usage.\n // However, existing `main.ts` handles cleanup.\n // We can add a global `finish` logic if needed.\n // For now, we'll keep the start time tracking here, but actual completion tracking might need to be in handlers.\n // BUT legacy code had `postAction` hook for `CLI_COMMAND` event.\n // We can simulate this by wrapping commands or using `cli.on('finish', ...)`?\n // Yargs doesn't emit finish events.\n // We might need to move the `CLI_COMMAND` tracking into `main.ts` or inside `createDefaultAction`.\n\n .alias(\"help\", \"h\")\n // yargs reports both a command line it cannot parse and an error a command\n // throws here. Only the first earns the help text; the second goes on to\n // runCli, which reports it once and shuts down.\n .fail((message, error, instance) => {\n if (error) throw error;\n instance.showHelp(\"error\");\n console.error(`\\n${message}`);\n throw new CliUsageError(message);\n });\n\n for (const registerCommand of COMMAND_FACTORIES) {\n registerCommand(cli);\n }\n\n return cli;\n}\n","/**\n * CLI main entry point with global shutdown and error handling.\n * Analytics is initialized immediately when imported for proper telemetry across all services.\n */\n\nimport {\n ModelConfigurationError,\n UnsupportedProviderError,\n} from \"../store/embeddings/EmbeddingFactory\";\nimport { telemetry } from \"../telemetry\";\nimport { logger } from \"../utils/logger\";\nimport { CliUsageError, createCli } from \"./index\";\nimport { reportCliError } from \"./output\";\n\n// Module-level variables are now in ./services.ts\nimport {\n closeActiveBackend,\n getActiveAppServer,\n getActiveMcpStdioServer,\n setActiveAppServer,\n setActiveMcpStdioServer,\n} from \"./services\";\n\nlet isShuttingDown = false;\n\n/**\n * Graceful shutdown handler for SIGINT\n */\nconst sigintHandler = async (): Promise<void> => {\n if (isShuttingDown) return;\n isShuttingDown = true;\n\n logger.debug(\"Received SIGINT. Shutting down gracefully...\");\n\n try {\n const appServer = getActiveAppServer();\n if (appServer) {\n logger.debug(\"SIGINT: Stopping AppServer...\");\n await appServer.stop();\n setActiveAppServer(null);\n logger.debug(\"SIGINT: AppServer stopped.\");\n }\n\n const mcpServer = getActiveMcpStdioServer();\n if (mcpServer) {\n logger.debug(\"SIGINT: Stopping MCP server...\");\n await mcpServer.close();\n setActiveMcpStdioServer(null);\n logger.debug(\"SIGINT: MCP server stopped.\");\n }\n\n // The servers have stopped, so nothing uses the backend any more\n await closeActiveBackend();\n\n // Analytics shutdown is handled by AppServer.stop() above\n // Only shutdown analytics if no AppServer was running\n if (!appServer && telemetry.isEnabled()) {\n await telemetry.shutdown();\n logger.debug(\"SIGINT: Analytics shut down.\");\n }\n\n logger.info(\"✅ Graceful shutdown completed\");\n process.exit(0);\n } catch (error) {\n logger.error(`❌ Error during graceful shutdown: ${error}`);\n process.exit(1);\n }\n};\n\n/**\n * Performs cleanup for CLI commands that don't start long-running services.\n * This ensures proper analytics shutdown and process exit to prevent hanging.\n */\nexport async function cleanupCliCommand(): Promise<void> {\n if (!isShuttingDown) {\n logger.debug(\"CLI command executed. Cleaning up...\");\n\n // Remove SIGINT handler since command completed successfully\n process.removeListener(\"SIGINT\", sigintHandler);\n\n // Shutdown analytics for non-server CLI commands to ensure clean exit\n await telemetry.shutdown();\n\n // Avoid hanging processes by explicitly exiting, with the exit code a\n // command sets for a failure it reports itself\n process.exit();\n }\n}\n\n/**\n * Main CLI execution function\n */\nexport async function runCli(): Promise<void> {\n let commandExecuted = false;\n\n // Reset shutdown state for new execution\n isShuttingDown = false;\n\n // Ensure only one SIGINT handler is active\n process.removeListener(\"SIGINT\", sigintHandler);\n process.on(\"SIGINT\", sigintHandler);\n\n try {\n const cli = createCli(process.argv);\n\n // Track if a command was executed?? Yargs doesn't have preAction hook on instance easily.\n // But middleware runs.\n // We can rely on middleware to set tracking data.\n // commandExecuted variable was used to trigger cleanupCliCommand at end.\n // Yargs .parse() resolves when command finishes.\n // If it resolves, command executed.\n commandExecuted = true;\n\n await cli.parse();\n } catch (error) {\n // A usage error has its help and reason printed already\n if (!(error instanceof CliUsageError)) {\n // Embedding configuration errors have properly formatted messages\n const preformatted =\n error instanceof ModelConfigurationError ||\n error instanceof UnsupportedProviderError;\n const message = error instanceof Error ? error.message : String(error);\n reportCliError(preformatted ? message : `❌ ${message}`);\n if (error instanceof Error && error.stack) {\n logger.debug(error.stack);\n }\n }\n\n if (!isShuttingDown) {\n isShuttingDown = true;\n\n // Shutdown active services on error\n const shutdownPromises: Promise<void>[] = [];\n\n const appServer = getActiveAppServer();\n if (appServer) {\n shutdownPromises.push(\n appServer\n .stop()\n .then(() => {\n setActiveAppServer(null);\n })\n .catch((e) => logger.error(`❌ Error stopping AppServer: ${e}`)),\n );\n }\n\n const mcpServer = getActiveMcpStdioServer();\n if (mcpServer) {\n shutdownPromises.push(\n mcpServer\n .close()\n .then(() => {\n setActiveMcpStdioServer(null);\n })\n .catch((e) => logger.error(`❌ Error stopping MCP server: ${e}`)),\n );\n }\n\n await Promise.allSettled(shutdownPromises);\n\n // Close the backend once the servers that use it have stopped\n await closeActiveBackend().catch((e) =>\n logger.error(`❌ Error closing backend: ${e}`),\n );\n }\n process.exit(1);\n }\n\n // This block handles cleanup for CLI commands that completed successfully\n // and were not long-running servers.\n const appServer = getActiveAppServer();\n if (commandExecuted && !appServer) {\n await cleanupCliCommand();\n }\n}\n\n// Handle HMR for vite-node --watch\nif (import.meta.hot) {\n import.meta.hot.on(\"vite:beforeFullReload\", async () => {\n logger.info(\"🔥 Hot reload detected\");\n process.removeListener(\"SIGINT\", sigintHandler);\n\n const wasAlreadyShuttingDown = isShuttingDown;\n isShuttingDown = true;\n\n try {\n const appServer = getActiveAppServer();\n if (appServer) {\n logger.debug(\"Shutting down AppServer...\");\n // A failed stop still closes the backend below\n await appServer.stop().then(\n () => {\n setActiveAppServer(null);\n logger.debug(\"AppServer shut down.\");\n },\n () => {},\n );\n }\n\n await closeActiveBackend();\n logger.debug(\"Active services shut down.\");\n } catch (hmrError) {\n logger.error(`❌ Error during HMR cleanup: ${hmrError}`);\n } finally {\n // Reset state for the next module instantiation\n setActiveAppServer(null);\n if (!wasAlreadyShuttingDown) {\n isShuttingDown = false;\n }\n }\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0GA,IAAY,gBAAL,yBAAA,eAAA;CACL,cAAA,iBAAA;CACA,cAAA,YAAA;CACA,cAAA,aAAA;CACA,cAAA,eAAA;CACA,cAAA,YAAA;CACA,cAAA,eAAA;CACA,cAAA,cAAA;;AACF,EAAA,CAAA,CAAA;;;;;;;;;;;;;AAqEA,SAAgB,sBAAsB,SAAiC;CACrE,QAAQ,WAAW,GAAA,CAAI,KAAK,CAAC,CAAC,YAAY;AAC5C;;;;;;;;;;;;;AAcA,SAAgB,qBAAqB,SAAyB;CAC5D,OAAO,QAAQ,KAAK,CAAC,CAAC,YAAY;AACpC;;;;;;;;;;AAWA,SAAgB,kBAAkB,GAAW,GAAoB;CAC/D,OAAO,qBAAqB,CAAC,MAAM,qBAAqB,CAAC;AAC3D;;;;;;;;;;AAWA,SAAgB,4BAA4B,SAAyB;CACnE,OAAO,QAAQ,KAAK;AACtB;;AAMA,IAAa,oBAAoB;;;;;;;;;;;AAYjC,SAAgB,2BAA2B,aAAoC;CAC7E,MAAM,OAAO,4BAA4B,WAAW;CACpD,IAAI,KAAK,WAAW,GAClB,OAAO;CAET,IAAI,kBAAkB,KAAK,IAAI,GAC7B,OAAO;CAET,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,SAAA,KACZ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,QAAQ;EAAK;CAC3C;AACF;;;;;;AAOA,SAAgB,uBACd,gBACA,eACA,aACA,QACA,WACwB;CACxB,IAAI,UAAU,EAAE,GAAG,eAAe;CAClC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,aAAa,GAAG;EACxD,IAAI,IAAI,YAAY,MAAM,mBAAmB,QAAQ,eAAe;EACpE,QAAQ,OAAO;CACjB;CACA,IAAI,eAAe,UAAU,cAAc,UAAU,CAAC,QAAQ,eAAe;EAC3E,MAAM,QAAQ,OAAO,KAAK,GAAG,YAAY,SAAS,GAAG,YAAY,UAAU,CAAC,CAAC,SAC3E,QACF;EACA,UAAU;GACR,GAAG;GACH,eAAe,SAAS;EAC1B;CACF;CACA,OAAO;AACT;;;;;;;;;;AC/yCA,IAAM,8BAA8B;;;;;;;AAQpC,IAAM,oBAAoB;;;;;;;;;;;AAY1B,SAAS,kBAAkB,MAAsB;CAC/C,OAAO,KAAK,QAAQ,QAAQ,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC;AAC1C;;;;;;;;;;;;;;;;AAyBA,IAAa,0BAAb,MAA2E;CAGzE,2BAA4C;EAC1C;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EAEA;EACA;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EAGA;EACA;EACA;EACA;EACA;EAEA;EACA;EAMA;EACA;EACA;EACA;EACA;EACA;EAGA;EAEA;EACA;EACA;EACA;EACA;EACA;EAEA;EACA;EACA;EACA;EACA;EACA;EAEA;EACA;EACA;EACA;EACA;EAGA;EACA;EACA;EACA;EAEA;EACA;EACA;EACA;EAGA;EACA;E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A;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CAEA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CAEA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CAEA;CACA;CAEA;CACA;CACA;CACA;CAEA;CACA;CAEA;AACF,CAAC;;AAGD,IAAM,sCAA2C,IAAI,IAAI;CACvD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,IAAM,oBAAuC;CAC3C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,IAAa,wBAAb,cAA2C,oBAAoB;CAC7D;CACA;CACA;CACA;CACA;CAEA,YAAY,QAAmB;EAC7B,MAAM,MAAM;EACZ,KAAK,cAAc,IAAI,YAAY,OAAO,OAAO;EACjD,KAAK,gBAAgB,IAAI,oBAAoB,MAAM;EACnD,KAAK,gBAAgB,IAAI,oBAAoB,MAAM;CACrD;;;;CAKA,eACE,KAC0D;EAC1D,MAAM,YAAY,IAAI,IAAI,GAAG;EAE7B,MAAM,QAAQ,UAAU,SAA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