@arabold/docs-mcp-server 3.3.0 → 3.4.1

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.
@@ -1,16 +1,16 @@
1
- import { t as normalizeEnvValue } from "./env-DONvEfR5.js";
2
- import { i as setLogLevel, n as getLogLevelFromEnv, r as logger, t as LogLevel } from "./logger-BBxstTD7.js";
3
- import { _ as splitModelSpec, d as validatePort, g as SUPPORTED_PROVIDERS, h as EmbeddingConfig, i as getEventBus, l as resolveProtocol, m as resolveStorePath, n as createAppServerConfig, o as handleEmbeddingModelChange, p as getProjectRoot, r as ensurePlaywrightBrowsersInstalled, s as parseHeaders, t as checkAuthForProtocol, u as validateHost } from "./utils-DXo1A54z.js";
4
- import { n as formatBytes, r as fullTrim, t as escapeHtml } from "./string-B3iUfzt2.js";
1
+ import { t as normalizeEnvValue } from "./env-DAfCMXx2.js";
2
+ import { i as setLogLevel, n as getLogLevelFromEnv, r as logger, t as LogLevel } from "./logger-DtB7mX3u.js";
3
+ import { n as formatBytes, r as fullTrim, t as escapeHtml } from "./string-n2Z12tl6.js";
4
+ import { createRequire } from "node:module";
5
5
  import { BedrockEmbeddings } from "@langchain/aws";
6
6
  import { GoogleGenerativeAIEmbeddings } from "@langchain/google-genai";
7
7
  import { VertexAIEmbeddings } from "@langchain/google-vertexai";
8
8
  import { AzureOpenAIEmbeddings, OpenAIEmbeddings } from "@langchain/openai";
9
9
  import { Embeddings } from "@langchain/core/embeddings";
10
10
  import crypto, { randomUUID } from "node:crypto";
11
- import fs, { statSync } from "node:fs";
11
+ import fs, { existsSync, statSync } from "node:fs";
12
12
  import path from "node:path";
13
- import { URL as URL$1 } from "node:url";
13
+ import { URL as URL$1, fileURLToPath } from "node:url";
14
14
  import envPaths from "env-paths";
15
15
  import { PostHog } from "posthog-node";
16
16
  import yargs from "yargs";
@@ -46,7 +46,7 @@ import iconv from "iconv-lite";
46
46
  import Parser from "tree-sitter";
47
47
  import Python from "tree-sitter-python";
48
48
  import TypeScript from "tree-sitter-typescript";
49
- import { exec } from "node:child_process";
49
+ import { exec, execFileSync } from "node:child_process";
50
50
  import { promisify } from "node:util";
51
51
  import { Readable } from "node:stream";
52
52
  import * as tar from "tar";
@@ -58,6 +58,7 @@ import * as sqliteVec from "sqlite-vec";
58
58
  import { createTRPCClient, createWSClient, httpBatchLink, splitLink, wsLink } from "@trpc/client";
59
59
  import superjson from "superjson";
60
60
  import { encode } from "@toon-format/toon";
61
+ import { createInterface } from "node:readline";
61
62
  import fastifyStatic from "@fastify/static";
62
63
  import Fastify from "fastify";
63
64
  import { WebSocketServer } from "ws";
@@ -69,7 +70,7 @@ import { fastifyTRPCPlugin } from "@trpc/server/adapters/fastify";
69
70
  import { applyWSSHandler } from "@trpc/server/adapters/ws";
70
71
  import { observable } from "@trpc/server/observable";
71
72
  import { serveStdio } from "@modelcontextprotocol/server/stdio";
72
- //#region src/store/types.ts
73
+ // src/store/types.ts
73
74
  /**
74
75
  * Represents the possible states of a version's indexing status.
75
76
  * These statuses are stored in the database and persist across server restarts.
@@ -210,8 +211,7 @@ function normalizeVersionName(name) {
210
211
  function denormalizeVersionName(name) {
211
212
  return name === "" ? "" : name;
212
213
  }
213
- //#endregion
214
- //#region src/store/errors.ts
214
+ // src/store/errors.ts
215
215
  /**
216
216
  * Base error class for all store-related errors.
217
217
  * Provides consistent error handling with optional cause tracking.
@@ -380,12 +380,27 @@ var DimensionError = class extends StoreError {
380
380
  */
381
381
  var ConnectionError = class extends StoreError {};
382
382
  /**
383
+ * Error thrown when the embedding provider fails to embed a page's chunks.
384
+ * Nothing of the page is written when this is thrown.
385
+ */
386
+ var EmbeddingError = class extends ConnectionError {};
387
+ /**
388
+ * Names an embedding model with its vector dimension for model-change messages.
389
+ * @param model - The model specification.
390
+ * @param dimension - The vector dimension, or null when it is not known.
391
+ * @returns The model, followed by its dimension when known.
392
+ */
393
+ function describeEmbeddingModel(model, dimension) {
394
+ return dimension === null ? model : `${model} (${dimension} dimensions)`;
395
+ }
396
+ /**
383
397
  * Error thrown when the configured embedding model or vector dimension differs from the
384
398
  * values stored in the database metadata. This indicates that existing vectors are
385
399
  * incompatible with the new configuration and must be invalidated before proceeding.
386
400
  *
387
- * The CLI layer catches this error to either prompt the user interactively (TTY) or
388
- * fail startup entirely (non-interactive/MCP/stdio mode).
401
+ * The CLI layer catches this error to accept the change when `--accept-model-change`
402
+ * is set, prompt the user interactively (TTY), or fail startup entirely
403
+ * (non-interactive/MCP/stdio mode). A dimension is null when it is not known.
389
404
  */
390
405
  var EmbeddingModelChangedError = class extends StoreError {
391
406
  previousModel;
@@ -393,7 +408,7 @@ var EmbeddingModelChangedError = class extends StoreError {
393
408
  currentModel;
394
409
  currentDimension;
395
410
  constructor(previousModel, previousDimension, currentModel, currentDimension) {
396
- super(`Embedding model change detected:\n Previous: ${previousModel} (${previousDimension} dimensions)\n Current: ${currentModel} (${currentDimension} dimensions)\n\nAll existing vectors are incompatible and must be invalidated.\nTo confirm this change, start the server interactively (with a TTY connected)\nand follow the prompts.`);
411
+ super(`Embedding model change detected:\n Previous: ${describeEmbeddingModel(previousModel, previousDimension)}\n Current: ${describeEmbeddingModel(currentModel, currentDimension)}\n\nAll existing vectors are incompatible and must be invalidated.\nTo confirm this change, start the server once with --accept-model-change\n(or DOCS_MCP_ACCEPT_MODEL_CHANGE=true), or start it in a terminal and answer the prompt.`);
397
412
  this.previousModel = previousModel;
398
413
  this.previousDimension = previousDimension;
399
414
  this.currentModel = currentModel;
@@ -411,8 +426,392 @@ var MissingCredentialsError = class extends StoreError {
411
426
  this.provider = provider;
412
427
  }
413
428
  };
414
- //#endregion
415
- //#region src/store/embeddings/FixedDimensionEmbeddings.ts
429
+ // src/store/embeddings/EmbeddingConfig.ts
430
+ /**
431
+ * Shared embedding model configuration service.
432
+ * Provides synchronous parsing of embedding model configuration and known dimensions lookup.
433
+ * Eliminates code duplication between DocumentStore and telemetry systems.
434
+ *
435
+ * All model lookups are case-insensitive to handle variations in model name capitalization.
436
+ * Uses class-based approach to avoid mutable global state and improve testability.
437
+ */
438
+ /**
439
+ * The complete set of provider prefixes recognized in a model specification.
440
+ * Anything else before the first colon is part of the model name itself.
441
+ *
442
+ * This list is normative rather than descriptive: it decides which prefixes claim
443
+ * the provider slot, so adding an entry changes how existing specifications parse.
444
+ * A model literally named `<new-provider>:<tag>` served by an OpenAI-compatible
445
+ * endpoint would start resolving to the new provider, breaking that configuration
446
+ * on upgrade. Call provider additions out in the release notes.
447
+ *
448
+ * `EmbeddingProvider` is derived from this array so the two cannot drift apart.
449
+ */
450
+ var SUPPORTED_PROVIDERS = [
451
+ "openai",
452
+ "vertex",
453
+ "gemini",
454
+ "aws",
455
+ "microsoft"
456
+ ];
457
+ /**
458
+ * Split a model specification into its provider prefix and model name.
459
+ *
460
+ * Only a prefix that names a supported provider is treated as a provider, matched
461
+ * case-insensitively and resolved to its canonical lowercase form. Every other
462
+ * specification is an OpenAI-compatible model name, which keeps names that carry a
463
+ * tag or quantization suffix intact (e.g. "nomic-embed-text:latest" or
464
+ * "second-state/jina-embeddings-v3-GGUF:Q4_K_M").
465
+ *
466
+ * @param spec The full model specification.
467
+ * @returns The resolved provider and model name.
468
+ */
469
+ function splitModelSpec(spec) {
470
+ const colonIndex = spec.indexOf(":");
471
+ const prefix = spec.substring(0, colonIndex).toLowerCase();
472
+ const provider = colonIndex === -1 ? void 0 : SUPPORTED_PROVIDERS.find((name) => name === prefix);
473
+ return provider ? {
474
+ provider,
475
+ model: spec.substring(colonIndex + 1)
476
+ } : {
477
+ provider: "openai",
478
+ model: spec
479
+ };
480
+ }
481
+ /**
482
+ * Embedding configuration manager that handles model parsing and dimension caching.
483
+ * Encapsulates state to avoid global variable issues and improve testability.
484
+ */
485
+ var EmbeddingConfig = class EmbeddingConfig {
486
+ static instance = null;
487
+ /**
488
+ * Get the singleton instance of EmbeddingConfig.
489
+ * Creates the instance if it doesn't exist.
490
+ */
491
+ static getInstance() {
492
+ if (EmbeddingConfig.instance === null) EmbeddingConfig.instance = new EmbeddingConfig();
493
+ return EmbeddingConfig.instance;
494
+ }
495
+ /**
496
+ * Reset the singleton instance (useful for testing).
497
+ */
498
+ static resetInstance() {
499
+ EmbeddingConfig.instance = null;
500
+ }
501
+ /**
502
+ * Known dimensions for common embedding models.
503
+ * This avoids expensive API calls for dimension detection in telemetry.
504
+ *
505
+ * Note: The "openai" provider also supports OpenAI-compatible APIs like:
506
+ * - Ollama (local models)
507
+ * - LMStudio (local models)
508
+ * - Any service implementing OpenAI's embedding API
509
+ */
510
+ knownModelDimensions = {
511
+ "text-embedding-3-small": 1536,
512
+ "text-embedding-3-large": 3072,
513
+ "text-embedding-ada-002": 1536,
514
+ "text-embedding-004": 768,
515
+ "text-embedding-005": 768,
516
+ "textembedding-gecko@003": 768,
517
+ "textembedding-gecko@002": 768,
518
+ "textembedding-gecko@001": 768,
519
+ "text-embedding-preview-0409": 768,
520
+ "embedding-001": 768,
521
+ "gemini-embedding-2-preview": 3072,
522
+ "amazon.titan-embed-text-v1": 1536,
523
+ "amazon.titan-embed-text-v2:0": 1024,
524
+ "amazon.titan-embed-image-v1": 1024,
525
+ "cohere.embed-english-v3": 1024,
526
+ "cohere.embed-multilingual-v3": 1024,
527
+ "Cohere/Cohere-embed-v4.0": 1536,
528
+ "embed-v4.0": 1536,
529
+ "intfloat/multilingual-e5-large": 1024,
530
+ "multilingual-e5-large": 1024,
531
+ "text-embedding-multilingual-e5-large": 1024,
532
+ "sentence-transformers/all-MiniLM-L6-v2": 384,
533
+ "gemini-embedding-001": 3072,
534
+ "Qwen/Qwen3-Embedding-8B": 4096,
535
+ "Qwen/Qwen3-Embedding-4B": 2560,
536
+ "Qwen/Qwen3-Embedding-0.6B": 1024,
537
+ "Linq-AI-Research/Linq-Embed-Mistral": 4096,
538
+ "Alibaba-NLP/gte-Qwen2-7B-instruct": 3584,
539
+ "intfloat/multilingual-e5-large-instruct": 1024,
540
+ "Salesforce/SFR-Embedding-Mistral": 4096,
541
+ "text-multilingual-embedding-002": 768,
542
+ "GritLM/GritLM-7B": 4096,
543
+ "GritLM/GritLM-8x7B": 4096,
544
+ "intfloat/e5-mistral-7b-instruct": 4096,
545
+ "Cohere/Cohere-embed-multilingual-v3.0": 1024,
546
+ "Alibaba-NLP/gte-Qwen2-1.5B-instruct": 8960,
547
+ "Lajavaness/bilingual-embedding-large": 1024,
548
+ "Salesforce/SFR-Embedding-2_R": 4096,
549
+ "NovaSearch/stella_en_1.5B_v5": 8960,
550
+ "NovaSearch/jasper_en_vision_language_v1": 8960,
551
+ "nvidia/NV-Embed-v2": 4096,
552
+ "OrdalieTech/Solon-embeddings-large-0.1": 1024,
553
+ "BAAI/bge-m3": 1024,
554
+ "HIT-TMG/KaLM-embedding-multilingual-mini-v1": 896,
555
+ "jinaai/jina-embeddings-v3": 1024,
556
+ "Alibaba-NLP/gte-multilingual-base": 768,
557
+ "Lajavaness/bilingual-embedding-base": 768,
558
+ "HIT-TMG/KaLM-embedding-multilingual-mini-instruct-v1": 896,
559
+ "nvidia/NV-Embed-v1": 4096,
560
+ "Cohere/Cohere-embed-multilingual-light-v3.0": 384,
561
+ "manu/bge-m3-custom-fr": 1024,
562
+ "Lajavaness/bilingual-embedding-small": 384,
563
+ "Snowflake/snowflake-arctic-embed-l-v2.0": 1024,
564
+ "intfloat/multilingual-e5-base": 768,
565
+ "voyage-3-lite": 512,
566
+ "voyage-3": 1024,
567
+ "voyage-3-large": 1024,
568
+ "voyage-3.5": 1024,
569
+ "voyage-4": 1024,
570
+ "voyage-4-large": 1024,
571
+ "voyage-4-lite": 1024,
572
+ "voyage-code-3": 1024,
573
+ "intfloat/multilingual-e5-small": 384,
574
+ "Alibaba-NLP/gte-Qwen1.5-7B-instruct": 4096,
575
+ "Snowflake/snowflake-arctic-embed-m-v2.0": 768,
576
+ "deepvk/USER-bge-m3": 1024,
577
+ "Cohere/Cohere-embed-english-v3.0": 1024,
578
+ "Omartificial-Intelligence-Space/Arabic-labse-Matryoshka": 768,
579
+ "ibm-granite/granite-embedding-278m-multilingual": 768,
580
+ "NovaSearch/stella_en_400M_v5": 4096,
581
+ "omarelshehy/arabic-english-sts-matryoshka": 1024,
582
+ "sentence-transformers/paraphrase-multilingual-mpnet-base-v2": 768,
583
+ "Omartificial-Intelligence-Space/Arabic-all-nli-triplet-Matryoshka": 768,
584
+ "Haon-Chen/speed-embedding-7b-instruct": 4096,
585
+ "sentence-transformers/LaBSE": 768,
586
+ "WhereIsAI/UAE-Large-V1": 1024,
587
+ "ibm-granite/granite-embedding-107m-multilingual": 384,
588
+ "mixedbread-ai/mxbai-embed-large-v1": 1024,
589
+ "intfloat/e5-large-v2": 1024,
590
+ "avsolatorio/GIST-large-Embedding-v0": 1024,
591
+ "sdadas/mmlw-e5-large": 1024,
592
+ "nomic-ai/nomic-embed-text-v1": 768,
593
+ "nomic-embed-text-v1": 768,
594
+ "nomic-ai/nomic-embed-text-v1-ablated": 768,
595
+ "nomic-ai/nomic-embed-text-v2-moe": 768,
596
+ "nomic-ai/modernbert-embed-base": 768,
597
+ "nomic-ai/nomic-embed-code": 3584,
598
+ "intfloat/e5-base-v2": 768,
599
+ "BAAI/bge-large-en-v1.5": 1024,
600
+ "intfloat/e5-large": 1024,
601
+ "Omartificial-Intelligence-Space/Arabic-MiniLM-L12-v2-all-nli-triplet": 384,
602
+ "Cohere/Cohere-embed-english-light-v3.0": 384,
603
+ "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2": 768,
604
+ "Gameselo/STS-multilingual-mpnet-base-v2": 768,
605
+ "thenlper/gte-large": 1024,
606
+ "avsolatorio/GIST-Embedding-v0": 768,
607
+ "nomic-ai/nomic-embed-text-v1-unsupervised": 768,
608
+ "infgrad/stella-base-en-v2": 768,
609
+ "avsolatorio/NoInstruct-small-Embedding-v0": 384,
610
+ "dwzhu/e5-base-4k": 768,
611
+ "sdadas/mmlw-e5-base": 768,
612
+ "voyage-multilingual-2": 1024,
613
+ "McGill-NLP/LLM2Vec-Mistral-7B-Instruct-v2-mntp-supervised": 4096,
614
+ "BAAI/bge-base-en-v1.5": 768,
615
+ "avsolatorio/GIST-small-Embedding-v0": 384,
616
+ "sdadas/mmlw-roberta-large": 1024,
617
+ "nomic-ai/nomic-embed-text-v1.5": 768,
618
+ "nomic-embed-text-v1.5": 768,
619
+ "text-embedding-nomic-embed-text-v1.5": 768,
620
+ "minishlab/potion-multilingual-128M": 256,
621
+ "shibing624/text2vec-base-multilingual": 384,
622
+ "thenlper/gte-base": 768,
623
+ "intfloat/e5-small-v2": 384,
624
+ "intfloat/e5-base": 768,
625
+ "sentence-transformers/static-similarity-mrl-multilingual-v1": 1024,
626
+ "manu/sentence_croissant_alpha_v0.3": 2048,
627
+ "BAAI/bge-small-en-v1.5": 512,
628
+ "thenlper/gte-small": 384,
629
+ "sdadas/mmlw-e5-small": 384,
630
+ "manu/sentence_croissant_alpha_v0.4": 2048,
631
+ "manu/sentence_croissant_alpha_v0.2": 2048,
632
+ "abhinand/MedEmbed-small-v0.1": 384,
633
+ "ibm-granite/granite-embedding-125m-english": 768,
634
+ "intfloat/e5-small": 384,
635
+ "voyage-large-2-instruct": 1024,
636
+ "sdadas/mmlw-roberta-base": 768,
637
+ "Snowflake/snowflake-arctic-embed-l": 1024,
638
+ "Mihaiii/Ivysaur": 384,
639
+ "Snowflake/snowflake-arctic-embed-m-long": 768,
640
+ "bigscience/sgpt-bloom-7b1-msmarco": 4096,
641
+ "avsolatorio/GIST-all-MiniLM-L6-v2": 384,
642
+ "sergeyzh/LaBSE-ru-turbo": 768,
643
+ "sentence-transformers/all-mpnet-base-v2": 768,
644
+ "Snowflake/snowflake-arctic-embed-m": 768,
645
+ "Snowflake/snowflake-arctic-embed-s": 384,
646
+ "sentence-transformers/all-MiniLM-L12-v2": 384,
647
+ "Mihaiii/gte-micro-v4": 384,
648
+ "Snowflake/snowflake-arctic-embed-m-v1.5": 768,
649
+ "cointegrated/LaBSE-en-ru": 768,
650
+ "Mihaiii/Bulbasaur": 384,
651
+ "ibm-granite/granite-embedding-30m-english": 384,
652
+ "deepfile/embedder-100p": 768,
653
+ "Jaume/gemma-2b-embeddings": 2048,
654
+ "OrlikB/KartonBERT-USE-base-v1": 768,
655
+ "izhx/udever-bloom-7b1": 4096,
656
+ "izhx/udever-bloom-1b1": 1024,
657
+ "brahmairesearch/slx-v0.1": 384,
658
+ "Mihaiii/Wartortle": 384,
659
+ "izhx/udever-bloom-3b": 2048,
660
+ "deepvk/USER-base": 768,
661
+ "ai-forever/ru-en-RoSBERTa": 1024,
662
+ "McGill-NLP/LLM2Vec-Mistral-7B-Instruct-v2-mntp-unsup-simcse": 4096,
663
+ "Mihaiii/Venusaur": 384,
664
+ "Snowflake/snowflake-arctic-embed-xs": 384,
665
+ "jinaai/jina-embedding-b-en-v1": 768,
666
+ "Mihaiii/gte-micro": 384,
667
+ "aari1995/German_Semantic_STS_V2": 1024,
668
+ "Mihaiii/Squirtle": 384,
669
+ "OrlikB/st-polish-kartonberta-base-alpha-v1": 768,
670
+ "sergeyzh/rubert-tiny-turbo": 312,
671
+ "minishlab/potion-base-8M": 256,
672
+ "minishlab/M2V_base_glove_subword": 256,
673
+ "jinaai/jina-embedding-s-en-v1": 512,
674
+ "minishlab/potion-base-4M": 128,
675
+ "minishlab/M2V_base_output": 256,
676
+ "DeepPavlov/rubert-base-cased-sentence": 768,
677
+ "jinaai/jina-embeddings-v2-small-en": 512,
678
+ "cointegrated/rubert-tiny2": 312,
679
+ "minishlab/M2V_base_glove": 256,
680
+ "cointegrated/rubert-tiny": 312,
681
+ "silma-ai/silma-embeddding-matryoshka-v0.1": 768,
682
+ "DeepPavlov/rubert-base-cased": 768,
683
+ "Omartificial-Intelligence-Space/Arabic-mpnet-base-all-nli-triplet": 768,
684
+ "izhx/udever-bloom-560m": 1024,
685
+ "minishlab/potion-base-2M": 64,
686
+ "DeepPavlov/distilrubert-small-cased-conversational": 768,
687
+ "consciousAI/cai-lunaris-text-embeddings": 1024,
688
+ "deepvk/deberta-v1-base": 768,
689
+ "Omartificial-Intelligence-Space/Arabert-all-nli-triplet-Matryoshka": 768,
690
+ "Omartificial-Intelligence-Space/Marbert-all-nli-triplet-Matryoshka": 768,
691
+ "ai-forever/sbert_large_mt_nlu_ru": 1024,
692
+ "ai-forever/sbert_large_nlu_ru": 1024,
693
+ "malenia1/ternary-weight-embedding": 1024,
694
+ "jinaai/jina-embeddings-v2-base-en": 768,
695
+ "VPLabs/SearchMap_Preview": 4096,
696
+ "Hum-Works/lodestone-base-4096-v1": 768,
697
+ "jinaai/jina-embeddings-v4": 2048
698
+ };
699
+ runtimeDetectedDimensionModels = /* @__PURE__ */ new Set([
700
+ "novasearch/stella_en_1.5b_v5",
701
+ "stella_en_1.5b_v5",
702
+ "novasearch/stella_en_400m_v5",
703
+ "dunzhang/stella_en_400m_v5",
704
+ "stella_en_400m_v5",
705
+ "novasearch/jasper_en_vision_language_v1",
706
+ "jasper_en_vision_language_v1"
707
+ ]);
708
+ /**
709
+ * Lowercase lookup map for case-insensitive model dimension queries.
710
+ * Built lazily from knownModelDimensions to ensure consistency.
711
+ */
712
+ modelLookup;
713
+ constructor() {
714
+ this.modelLookup = /* @__PURE__ */ new Map();
715
+ for (const [model, dimensions] of Object.entries(this.knownModelDimensions)) this.modelLookup.set(model.toLowerCase(), dimensions);
716
+ }
717
+ /**
718
+ * Build the lookup keys to try for a model name, most specific first:
719
+ * the name itself, then with the namespace dropped, the tag dropped, and both.
720
+ *
721
+ * Dropping a trailing tag lets a quantized or tagged variant reuse the base
722
+ * model's dimensions (e.g. "nomic-ai/nomic-embed-text-v2-moe:latest"), which
723
+ * quantization does not change. Exact matches are tried first, so names whose
724
+ * own identifier contains a colon (e.g. "amazon.titan-embed-text-v2:0") still
725
+ * resolve to their own entry.
726
+ */
727
+ dimensionLookupKeys(normalized) {
728
+ const slashIndex = normalized.lastIndexOf("/");
729
+ const withoutNamespace = slashIndex > -1 ? normalized.substring(slashIndex + 1) : void 0;
730
+ const bases = withoutNamespace ? [normalized, withoutNamespace] : [normalized];
731
+ const withoutTag = (key) => {
732
+ const colonIndex = key.lastIndexOf(":");
733
+ return colonIndex > 0 ? [key.substring(0, colonIndex)] : [];
734
+ };
735
+ return [...bases, ...bases.flatMap(withoutTag)];
736
+ }
737
+ findKnownDimension(model) {
738
+ for (const key of this.dimensionLookupKeys(model.toLowerCase())) {
739
+ if (this.runtimeDetectedDimensionModels.has(key)) return null;
740
+ const dimensions = this.modelLookup?.get(key);
741
+ if (dimensions !== void 0) return dimensions;
742
+ }
743
+ return null;
744
+ }
745
+ /**
746
+ * Parse embedding model configuration from a provided model specification.
747
+ * This is a synchronous operation that extracts provider, model, and known dimensions.
748
+ *
749
+ * Supports various providers:
750
+ * - openai: OpenAI models and OpenAI-compatible APIs (Ollama, LMStudio, etc.)
751
+ * - vertex: Google Cloud Vertex AI
752
+ * - gemini: Google Generative AI
753
+ * - aws: AWS Bedrock models
754
+ * - microsoft: Azure OpenAI
755
+ *
756
+ * @param modelSpec Model specification (e.g., "openai:text-embedding-3-small"), defaults to "text-embedding-3-small"
757
+ * @returns Parsed embedding model configuration
758
+ */
759
+ parse(modelSpec) {
760
+ const spec = normalizeEnvValue(modelSpec || "text-embedding-3-small");
761
+ const { provider, model } = splitModelSpec(spec);
762
+ return {
763
+ provider,
764
+ model,
765
+ dimensions: this.findKnownDimension(model),
766
+ modelSpec: spec
767
+ };
768
+ }
769
+ /**
770
+ * Get the known dimensions for a specific model.
771
+ * Returns null if the model dimensions are not known.
772
+ * Uses case-insensitive lookup.
773
+ *
774
+ * @param model The model name (e.g., "text-embedding-3-small")
775
+ * @returns Known dimensions or null
776
+ */
777
+ getKnownDimensions(model) {
778
+ return this.findKnownDimension(model);
779
+ }
780
+ /**
781
+ * Add or update known dimensions for a model.
782
+ * This can be used to cache discovered dimensions.
783
+ * Stores both original case and lowercase for consistent lookup.
784
+ *
785
+ * @param model The model name
786
+ * @param dimensions The dimensions to cache
787
+ */
788
+ setKnownDimensions(model, dimensions) {
789
+ this.knownModelDimensions[model] = dimensions;
790
+ if (this.modelLookup) this.modelLookup.set(model.toLowerCase(), dimensions);
791
+ }
792
+ /**
793
+ * Static method to parse embedding model configuration using the singleton instance.
794
+ * This maintains backward compatibility while using the class-based approach.
795
+ */
796
+ static parseEmbeddingConfig(modelSpec) {
797
+ return EmbeddingConfig.getInstance().parse(modelSpec);
798
+ }
799
+ /**
800
+ * Static method to get known model dimensions using the singleton instance.
801
+ * This maintains backward compatibility while using the class-based approach.
802
+ */
803
+ static getKnownModelDimensions(model) {
804
+ return EmbeddingConfig.getInstance().getKnownDimensions(model);
805
+ }
806
+ /**
807
+ * Static method to set known model dimensions using the singleton instance.
808
+ * This maintains backward compatibility while using the class-based approach.
809
+ */
810
+ static setKnownModelDimensions(model, dimensions) {
811
+ EmbeddingConfig.getInstance().setKnownDimensions(model, dimensions);
812
+ }
813
+ };
814
+ // src/store/embeddings/FixedDimensionEmbeddings.ts
416
815
  /**
417
816
  * Wrapper around an Embeddings implementation that ensures vectors have a fixed dimension.
418
817
  * - If a vector's dimension is greater than the target and truncation is allowed,
@@ -455,8 +854,7 @@ var FixedDimensionEmbeddings = class extends Embeddings {
455
854
  return (await this.embeddings.embedDocuments(documents)).map((vector) => this.normalizeVector(vector));
456
855
  }
457
856
  };
458
- //#endregion
459
- //#region src/store/embeddings/EmbeddingFactory.ts
857
+ // src/store/embeddings/EmbeddingFactory.ts
460
858
  /**
461
859
  * Error thrown when an invalid or unsupported embedding provider is specified.
462
860
  */
@@ -526,7 +924,7 @@ function createEmbeddingModel(providerAndModel, runtime) {
526
924
  if (!process.env.OPENAI_API_KEY) throw new MissingCredentialsError("openai", ["OPENAI_API_KEY"]);
527
925
  const apiKey = process.env.OPENAI_API_KEY;
528
926
  const baseURL = process.env.OPENAI_API_BASE;
529
- return new OpenAIEmbeddings({
927
+ const config = {
530
928
  ...baseConfig,
531
929
  apiKey,
532
930
  modelName: model,
@@ -537,7 +935,8 @@ function createEmbeddingModel(providerAndModel, runtime) {
537
935
  ...baseURL ? { baseURL } : {},
538
936
  timeout: requestTimeoutMs
539
937
  }
540
- });
938
+ };
939
+ return new OpenAIEmbeddings(config);
541
940
  }
542
941
  case "vertex":
543
942
  if (!process.env.GOOGLE_APPLICATION_CREDENTIALS) throw new MissingCredentialsError("vertex", ["GOOGLE_APPLICATION_CREDENTIALS"]);
@@ -589,8 +988,7 @@ function createEmbeddingModel(providerAndModel, runtime) {
589
988
  default: throw new UnsupportedProviderError(provider);
590
989
  }
591
990
  }
592
- //#endregion
593
- //#region src/telemetry/sanitizer.ts
991
+ // src/telemetry/sanitizer.ts
594
992
  /**
595
993
  * Data sanitization utilities for privacy-first telemetry.
596
994
  * Events carry the host of a URL instead of the URL itself, and error messages
@@ -695,8 +1093,57 @@ function sanitizeErrorForTracking(error) {
695
1093
  sanitized.stack = [`${error.name}: ${message}`, ...frames].join("\n");
696
1094
  return sanitized;
697
1095
  }
698
- //#endregion
699
- //#region src/telemetry/TelemetryConfig.ts
1096
+ // src/utils/paths.ts
1097
+ var projectRoot = null;
1098
+ /**
1099
+ * Finds the project root directory by searching upwards from the current file
1100
+ * for a directory containing 'package.json'. Caches the result.
1101
+ *
1102
+ * @returns {string} The absolute path to the project root.
1103
+ * @throws {Error} If package.json cannot be found.
1104
+ */
1105
+ function getProjectRoot() {
1106
+ if (projectRoot) return projectRoot;
1107
+ const currentFilePath = fileURLToPath(import.meta.url);
1108
+ let currentDir = path.dirname(currentFilePath);
1109
+ while (true) {
1110
+ const packageJsonPath = path.join(currentDir, "package.json");
1111
+ if (fs.existsSync(packageJsonPath)) {
1112
+ projectRoot = currentDir;
1113
+ return currentDir;
1114
+ }
1115
+ const parentDir = path.dirname(currentDir);
1116
+ if (parentDir === currentDir) throw new Error("Could not find project root containing package.json.");
1117
+ currentDir = parentDir;
1118
+ }
1119
+ }
1120
+ /**
1121
+ * Resolves the data storage path using the following priority:
1122
+ * 1. Provided storePath parameter
1123
+ * 2. Legacy .store directory in project root (if exists)
1124
+ * 3. Standard system data directory using env-paths
1125
+ *
1126
+ * @param storePath Optional custom storage path
1127
+ * @returns Resolved absolute path for data storage
1128
+ */
1129
+ function resolveStorePath(storePath) {
1130
+ let dbDir;
1131
+ if (storePath) dbDir = path.resolve(storePath);
1132
+ else {
1133
+ const projectRoot = getProjectRoot();
1134
+ const oldDbDir = path.join(projectRoot, ".store");
1135
+ const oldDbPath = path.join(oldDbDir, "documents.db");
1136
+ if (fs.existsSync(oldDbPath)) dbDir = oldDbDir;
1137
+ else dbDir = envPaths("docs-mcp-server", { suffix: "" }).data;
1138
+ }
1139
+ try {
1140
+ fs.mkdirSync(dbDir, { recursive: true });
1141
+ } catch (error) {
1142
+ logger.warn(`⚠️ Failed to create database directory ${dbDir}: ${error}`);
1143
+ }
1144
+ return dbDir;
1145
+ }
1146
+ // src/telemetry/TelemetryConfig.ts
700
1147
  /**
701
1148
  * Telemetry configuration management for enabling/disabling analytics collection.
702
1149
  * Handles CLI flags, environment variables, and default settings.
@@ -744,8 +1191,7 @@ function generateInstallationId(storePath) {
744
1191
  function shouldEnableTelemetry() {
745
1192
  return TelemetryConfig.getInstance().isEnabled();
746
1193
  }
747
- //#endregion
748
- //#region src/events/types.ts
1194
+ // src/events/types.ts
749
1195
  /**
750
1196
  * Event type enum used by the EventBusService.
751
1197
  * These are the internal event identifiers.
@@ -757,8 +1203,7 @@ var EventType = /* @__PURE__ */ function(EventType) {
757
1203
  EventType["JOB_LIST_CHANGE"] = "JOB_LIST_CHANGE";
758
1204
  return EventType;
759
1205
  }({});
760
- //#endregion
761
- //#region src/pipeline/types.ts
1206
+ // src/pipeline/types.ts
762
1207
  /**
763
1208
  * Represents the possible states of a pipeline job.
764
1209
  */
@@ -771,8 +1216,7 @@ var PipelineJobStatus = /* @__PURE__ */ function(PipelineJobStatus) {
771
1216
  PipelineJobStatus["CANCELLED"] = "cancelled";
772
1217
  return PipelineJobStatus;
773
1218
  }({});
774
- //#endregion
775
- //#region src/telemetry/postHogClient.ts
1219
+ // src/telemetry/postHogClient.ts
776
1220
  /**
777
1221
  * PostHog client wrapper for telemetry events.
778
1222
  * Handles PostHog SDK integration and event capture with privacy-first configuration.
@@ -898,8 +1342,7 @@ var PostHogClient = class PostHogClient {
898
1342
  return this.enabled && !!this.client;
899
1343
  }
900
1344
  };
901
- //#endregion
902
- //#region src/telemetry/telemetry.ts
1345
+ // src/telemetry/telemetry.ts
903
1346
  /**
904
1347
  * Telemtry wrapper for privacy-first telemetry using PostHog.
905
1348
  * Provides global context and automatic data sanitization.
@@ -959,12 +1402,6 @@ var Telemetry = class Telemetry {
959
1402
  setGlobalContext(context) {
960
1403
  this.globalContext = { ...context };
961
1404
  }
962
- /**
963
- * Get current global context
964
- */
965
- getGlobalContext() {
966
- return { ...this.globalContext };
967
- }
968
1405
  track(event, properties = {}) {
969
1406
  if (!this.enabled) return;
970
1407
  const enrichedProperties = {
@@ -1028,8 +1465,7 @@ var telemetry = new Proxy({}, { get(_target, prop) {
1028
1465
  if (typeof value === "function") return value.bind(instance);
1029
1466
  return value;
1030
1467
  } });
1031
- //#endregion
1032
- //#region src/telemetry/TelemetryService.ts
1468
+ // src/telemetry/TelemetryService.ts
1033
1469
  var TelemetryService = class {
1034
1470
  eventBus;
1035
1471
  unsubscribers = [];
@@ -1074,19 +1510,16 @@ var TelemetryService = class {
1074
1510
  throughputPagesPerSecond: duration && job.progressPages ? Math.round(job.progressPages / duration * 1e3) : 0
1075
1511
  });
1076
1512
  break;
1077
- case PipelineJobStatus.FAILED:
1078
- telemetry.track(TelemetryEvent.PIPELINE_JOB_FAILED, {
1079
- jobId: job.id,
1080
- library: job.library,
1081
- durationMs: duration,
1082
- pagesProcessed: job.progressPages || 0,
1083
- maxPagesConfigured: job.scraperOptions?.maxPages ?? null,
1084
- hasVersion: !!job.version,
1085
- hasError: !!job.error,
1086
- errorMessage: job.error ? sanitizeErrorMessage(job.error.message) : void 0
1087
- });
1088
- break;
1089
- default: break;
1513
+ case PipelineJobStatus.FAILED: telemetry.track(TelemetryEvent.PIPELINE_JOB_FAILED, {
1514
+ jobId: job.id,
1515
+ library: job.library,
1516
+ durationMs: duration,
1517
+ pagesProcessed: job.progressPages || 0,
1518
+ maxPagesConfigured: job.scraperOptions?.maxPages ?? null,
1519
+ hasVersion: !!job.version,
1520
+ hasError: !!job.error,
1521
+ errorMessage: job.error ? sanitizeErrorMessage(job.error.message) : void 0
1522
+ });
1090
1523
  }
1091
1524
  }
1092
1525
  /**
@@ -1103,8 +1536,7 @@ var TelemetryService = class {
1103
1536
  logger.debug("TelemetryService shut down");
1104
1537
  }
1105
1538
  };
1106
- //#endregion
1107
- //#region src/events/EventBusService.ts
1539
+ // src/events/EventBusService.ts
1108
1540
  /**
1109
1541
  * Central event bus service for application-wide event distribution.
1110
1542
  *
@@ -1142,33 +1574,13 @@ var EventBusService = class {
1142
1574
  return () => this.emitter.off(eventType, listener);
1143
1575
  }
1144
1576
  /**
1145
- * Subscribe to events once (auto-unsubscribes after first event).
1146
- */
1147
- once(eventType, listener) {
1148
- this.emitter.once(eventType, listener);
1149
- }
1150
- /**
1151
1577
  * Remove a specific listener.
1152
1578
  */
1153
1579
  off(eventType, listener) {
1154
1580
  this.emitter.off(eventType, listener);
1155
1581
  }
1156
- /**
1157
- * Remove all listeners for a specific event type, or all listeners if no type specified.
1158
- */
1159
- removeAllListeners(eventType) {
1160
- if (eventType === void 0) this.emitter.removeAllListeners();
1161
- else this.emitter.removeAllListeners(eventType);
1162
- }
1163
- /**
1164
- * Get the count of listeners for a specific event type.
1165
- */
1166
- listenerCount(eventType) {
1167
- return this.emitter.listenerCount(eventType);
1168
- }
1169
1582
  };
1170
- //#endregion
1171
- //#region src/utils/serverOrigin.ts
1583
+ // src/utils/serverOrigin.ts
1172
1584
  /**
1173
1585
  * Normalize a configured origin (`scheme://host[:port]`) into its canonical form.
1174
1586
  *
@@ -1311,8 +1723,7 @@ function formatHostForUrl(host) {
1311
1723
  function stripIpv6Brackets(host) {
1312
1724
  return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
1313
1725
  }
1314
- //#endregion
1315
- //#region src/utils/config.ts
1726
+ // src/utils/config.ts
1316
1727
  var managedConfigVectorDimensionOmissionMarker = "docs-mcp-server-managed-vector-dimension-omitted";
1317
1728
  var managedConfigHeader = [
1318
1729
  `# ${managedConfigVectorDimensionOmissionMarker}`,
@@ -1338,6 +1749,15 @@ var envBoolean = z.union([z.boolean(), z.string()]).transform((val) => {
1338
1749
  return lower !== "false" && lower !== "0" && lower !== "no" && lower !== "off" && lower !== "";
1339
1750
  }).pipe(z.boolean());
1340
1751
  /**
1752
+ * Parses a boolean environment variable the way configuration settings are
1753
+ * parsed: "false", "0", "no", "off" and blank are false, anything else true.
1754
+ * @param value - The variable's value.
1755
+ * @returns The boolean, or undefined when the variable is unset.
1756
+ */
1757
+ function parseEnvBoolean(value) {
1758
+ return value === void 0 ? void 0 : envBoolean.parse(value);
1759
+ }
1760
+ /**
1341
1761
  * Treats blank strings (empty env vars, `--flag ""`) as an absent value so that
1342
1762
  * defaults and fallbacks apply instead of an empty string.
1343
1763
  */
@@ -1432,9 +1852,9 @@ var DEFAULT_CONFIG = {
1432
1852
  baseDelayMs: 1e3,
1433
1853
  timeoutMs: 3e4,
1434
1854
  maxCacheItems: 200,
1435
- maxCacheItemSizeBytes: 500 * 1024
1855
+ maxCacheItemSizeBytes: 512e3
1436
1856
  },
1437
- document: { maxSize: 10 * 1024 * 1024 },
1857
+ document: { maxSize: 10485760 },
1438
1858
  security: {
1439
1859
  network: {
1440
1860
  mode: "open",
@@ -1478,7 +1898,6 @@ var DEFAULT_CONFIG = {
1478
1898
  weightFts: 1,
1479
1899
  vectorMultiplier: 10
1480
1900
  },
1481
- sandbox: { defaultTimeoutMs: 5e3 },
1482
1901
  assembly: {
1483
1902
  maxParentChainDepth: 10,
1484
1903
  childLimit: 3,
@@ -1590,7 +2009,6 @@ var AppConfigSchema = z.object({
1590
2009
  weightFts: z.coerce.number().default(DEFAULT_CONFIG.search.weightFts),
1591
2010
  vectorMultiplier: z.coerce.number().int().default(DEFAULT_CONFIG.search.vectorMultiplier)
1592
2011
  }).default(DEFAULT_CONFIG.search),
1593
- sandbox: z.object({ defaultTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.sandbox.defaultTimeoutMs) }).default(DEFAULT_CONFIG.sandbox),
1594
2012
  assembly: z.object({
1595
2013
  maxParentChainDepth: z.coerce.number().int().default(DEFAULT_CONFIG.assembly.maxParentChainDepth),
1596
2014
  childLimit: z.coerce.number().int().default(DEFAULT_CONFIG.assembly.childLimit),
@@ -1995,8 +2413,7 @@ function setConfigValue(path, value) {
1995
2413
  function getDefaultConfigPath() {
1996
2414
  return path.join(systemPaths.config, "config.yaml");
1997
2415
  }
1998
- //#endregion
1999
- //#region src/events/RemoteEventProxy.ts
2416
+ // src/events/RemoteEventProxy.ts
2000
2417
  /** First delay before subscribing again after the subscription itself ended. */
2001
2418
  var RESUBSCRIBE_BASE_DELAY_MS = 1e3;
2002
2419
  /** Longest delay between attempts to subscribe again. */
@@ -2138,8 +2555,7 @@ var RemoteEventProxy = class {
2138
2555
  this.wasLive = true;
2139
2556
  }
2140
2557
  };
2141
- //#endregion
2142
- //#region src/pipeline/trpc/interfaces.ts
2558
+ // src/pipeline/trpc/interfaces.ts
2143
2559
  /**
2144
2560
  * The tRPC codes the pipeline router gives enqueue errors a caller can act on:
2145
2561
  * an existing target (409), an invalid library name (400) and an unknown
@@ -2151,8 +2567,7 @@ var RELAYED_ENQUEUE_ERROR_CODES = [
2151
2567
  "BAD_REQUEST",
2152
2568
  "NOT_FOUND"
2153
2569
  ];
2154
- //#endregion
2155
- //#region src/pipeline/PipelineClient.ts
2570
+ // src/pipeline/PipelineClient.ts
2156
2571
  /**
2157
2572
  * Pipeline backed by a remote worker: every operation calls the worker's
2158
2573
  * application API through a shared {@link ApiClient}.
@@ -2320,9 +2735,7 @@ var PipelineClient = class {
2320
2735
  case PipelineJobStatus.CANCELLED:
2321
2736
  finish();
2322
2737
  break;
2323
- case PipelineJobStatus.FAILED:
2324
- finish(new Error(job.error?.message || job.errorMessage || `Job ${jobId} failed`));
2325
- break;
2738
+ case PipelineJobStatus.FAILED: finish(new Error(job.error?.message || job.errorMessage || `Job ${jobId} failed`));
2326
2739
  }
2327
2740
  };
2328
2741
  const unsubscribe = this.eventBus.on(EventType.JOB_STATUS_CHANGE, (job) => {
@@ -2371,8 +2784,7 @@ var PipelineClient = class {
2371
2784
  });
2372
2785
  }
2373
2786
  };
2374
- //#endregion
2375
- //#region src/utils/errors.ts
2787
+ // src/utils/errors.ts
2376
2788
  var ScraperError = class extends Error {
2377
2789
  isRetryable;
2378
2790
  cause;
@@ -2405,11 +2817,20 @@ var ChallengeError = class extends ScraperError {
2405
2817
  url;
2406
2818
  statusCode;
2407
2819
  challengeType;
2408
- constructor(url, statusCode, challengeType) {
2820
+ responseUrl;
2821
+ /**
2822
+ * @param url The URL that was requested.
2823
+ * @param statusCode The status the challenge was served with.
2824
+ * @param challengeType The kind of challenge, such as "cloudflare".
2825
+ * @param responseUrl The URL whose response carried the challenge, which a
2826
+ * redirect may have moved to another host.
2827
+ */
2828
+ constructor(url, statusCode, challengeType, responseUrl = url) {
2409
2829
  super(`Challenge detected for ${url} (status: ${statusCode}, type: ${challengeType}): the site answered with a bot check instead of the page`, false);
2410
2830
  this.url = url;
2411
2831
  this.statusCode = statusCode;
2412
2832
  this.challengeType = challengeType;
2833
+ this.responseUrl = responseUrl;
2413
2834
  }
2414
2835
  };
2415
2836
  var TlsCertificateError = class extends ScraperError {
@@ -2424,9 +2845,19 @@ var TlsCertificateError = class extends ScraperError {
2424
2845
  /** An HTTP fetch that failed with a response, carrying that response's status. */
2425
2846
  var HttpStatusError = class extends ScraperError {
2426
2847
  statusCode;
2427
- constructor(message, isRetryable, statusCode, cause) {
2848
+ responseUrl;
2849
+ /**
2850
+ * @param message Describes the failure.
2851
+ * @param isRetryable Whether a later attempt may succeed.
2852
+ * @param statusCode The response's status.
2853
+ * @param cause The underlying error.
2854
+ * @param responseUrl The URL that answered with the status, when known; a
2855
+ * redirect may have moved it to another host.
2856
+ */
2857
+ constructor(message, isRetryable, statusCode, cause, responseUrl) {
2428
2858
  super(message, isRetryable, cause);
2429
2859
  this.statusCode = statusCode;
2860
+ this.responseUrl = responseUrl;
2430
2861
  }
2431
2862
  };
2432
2863
  var AccessPolicyError = class extends ScraperError {
@@ -2434,8 +2865,28 @@ var AccessPolicyError = class extends ScraperError {
2434
2865
  super(message, false);
2435
2866
  }
2436
2867
  };
2437
- //#endregion
2438
- //#region src/utils/mimeTypeUtils.ts
2868
+ /**
2869
+ * Returns the first line of a thrown value's message.
2870
+ *
2871
+ * Playwright's messages run on with call logs and install hints; the first line
2872
+ * names the failure.
2873
+ *
2874
+ * @param error The thrown value.
2875
+ * @returns The first line, or the whole message when that line is empty.
2876
+ */
2877
+ function firstErrorLine(error) {
2878
+ const message = error instanceof Error ? error.message : String(error);
2879
+ return message.split("\n")[0] || message;
2880
+ }
2881
+ /** A page that had to be rendered in the browser could not be. */
2882
+ var RenderError = class extends ScraperError {
2883
+ url;
2884
+ constructor(url, cause) {
2885
+ super(`Playwright could not render ${url}: ${firstErrorLine(cause)}`, false, cause);
2886
+ this.url = url;
2887
+ }
2888
+ };
2889
+ // src/utils/mimeTypeUtils.ts
2439
2890
  /**
2440
2891
  * Extension-to-MIME overrides for types the `mime` package gets wrong or does
2441
2892
  * not know. See openspec/changes/refactor-mime-type-detection/design.md.
@@ -2879,8 +3330,7 @@ var MimeTypeUtils = class MimeTypeUtils {
2879
3330
  }[mimeType] || "";
2880
3331
  }
2881
3332
  };
2882
- //#endregion
2883
- //#region src/utils/url.ts
3333
+ // src/utils/url.ts
2884
3334
  var defaultNormalizerOptions = {
2885
3335
  removeHash: true,
2886
3336
  removeTrailingSlash: true,
@@ -2967,8 +3417,7 @@ function stripMarkdownExtension(url) {
2967
3417
  parsed.pathname = stripped;
2968
3418
  return parsed.toString();
2969
3419
  }
2970
- //#endregion
2971
- //#region src/scraper/utils/defaultPatterns.ts
3420
+ // src/scraper/utils/defaultPatterns.ts
2972
3421
  /**
2973
3422
  * Default exclusion patterns for documentation scraping.
2974
3423
  * These patterns are always applied unless user explicitly provides their own exclude patterns.
@@ -3069,8 +3518,7 @@ function getEffectiveExclusionPatterns(userPatterns) {
3069
3518
  if (userPatterns !== void 0) return userPatterns;
3070
3519
  return DEFAULT_EXCLUSION_PATTERNS;
3071
3520
  }
3072
- //#endregion
3073
- //#region src/scraper/utils/patternMatcher.ts
3521
+ // src/scraper/utils/patternMatcher.ts
3074
3522
  /**
3075
3523
  * Utility functions for pattern matching (glob and regex) for URL filtering.
3076
3524
  * Supports auto-detection and conversion of glob patterns to RegExp.
@@ -3200,8 +3648,7 @@ function shouldIncludeUrl(url, includePatterns, excludePatterns) {
3200
3648
  if (!includePatterns || includePatterns.length === 0) return true;
3201
3649
  return matchesAnyPattern(url, includePatterns) || matchesAnyPattern(normalizedPath, includePatterns) || (basename ? matchesAnyPattern(basename, stripSlash(includePatterns)) : false);
3202
3650
  }
3203
- //#endregion
3204
- //#region src/utils/accessPolicy.ts
3651
+ // src/utils/accessPolicy.ts
3205
3652
  var SPECIAL_USE_IPV4_CIDRS = [
3206
3653
  "0.0.0.0/8",
3207
3654
  "10.0.0.0/8",
@@ -3575,8 +4022,7 @@ function hasHiddenSegmentBelowRoot(targetPath, matchedRoot) {
3575
4022
  function hasHiddenArchiveSegment(archivePath) {
3576
4023
  return archivePath.split(/[\\/]+/).filter(Boolean).some((segment) => segment.startsWith("."));
3577
4024
  }
3578
- //#endregion
3579
- //#region src/scraper/fetcher/challenge.ts
4025
+ // src/scraper/fetcher/challenge.ts
3580
4026
  /**
3581
4027
  * Recognition of bot-protection challenge pages that a site serves in place of
3582
4028
  * the requested document, with a success status.
@@ -3586,7 +4032,7 @@ function hasHiddenArchiveSegment(archivePath) {
3586
4032
  * carry their markers in the head, so a documentation page that merely
3587
4033
  * mentions them further down is not mistaken for one.
3588
4034
  */
3589
- var SCAN_LIMIT = 64 * 1024;
4035
+ var SCAN_LIMIT = 65536;
3590
4036
  /** The title of Fastly's client challenge page. */
3591
4037
  var FASTLY_CHALLENGE_TITLE = /<title>\s*Client Challenge\s*<\/title>/i;
3592
4038
  /** The path prefix Fastly serves the challenge's scripts and assets from. */
@@ -3607,8 +4053,7 @@ function detectChallengePage(html) {
3607
4053
  if (FASTLY_CHALLENGE_TITLE.test(head) && head.includes(FASTLY_CHALLENGE_ASSET_PATH)) return "fastly";
3608
4054
  return null;
3609
4055
  }
3610
- //#endregion
3611
- //#region src/scraper/fetcher/FingerprintGenerator.ts
4056
+ // src/scraper/fetcher/FingerprintGenerator.ts
3612
4057
  /**
3613
4058
  * Generates realistic browser-like HTTP headers to help avoid bot detection.
3614
4059
  * Uses the `header-generator` library for header generation.
@@ -3653,9 +4098,6 @@ var FingerprintGenerator = class {
3653
4098
  return this.headerGenerator.getHeaders();
3654
4099
  }
3655
4100
  };
3656
- //#endregion
3657
- //#region src/scraper/fetcher/headers.ts
3658
- var MARKDOWN_PREFERRED_ACCEPT = "text/markdown, text/html;q=0.9, */*;q=0.8";
3659
4101
  /**
3660
4102
  * Reads a header by name, ignoring case.
3661
4103
  *
@@ -3673,21 +4115,10 @@ function getHeader(headers, name) {
3673
4115
  for (const [header, value] of Object.entries(headers)) if (header.toLowerCase() === target) return value;
3674
4116
  }
3675
4117
  /**
3676
- * Returns headers with a Markdown-preferred Accept default unless one was supplied.
3677
- * @param headers Existing request headers.
3678
- * @returns Headers with an Accept value suitable for web scraping.
3679
- */
3680
- function withMarkdownPreferredAccept(headers, callerHeaders = {}) {
3681
- if (Object.keys(callerHeaders).some((header) => header.toLowerCase() === "accept")) return headers;
3682
- return {
3683
- ...Object.fromEntries(Object.entries(headers).filter(([header]) => header.toLowerCase() !== "accept")),
3684
- Accept: MARKDOWN_PREFERRED_ACCEPT
3685
- };
3686
- }
3687
- /**
3688
- * Connection-level headers that Chromium refuses to take from a page. A
3689
- * navigation that carries one fails with `net::ERR_INVALID_ARGUMENT`.
3690
- * Generated Firefox fingerprints include `TE: trailers`.
4118
+ * Connection-level headers, which the client that opens a connection sets for
4119
+ * itself. Chromium refuses to take them from a page: a navigation that carries
4120
+ * one fails with `net::ERR_INVALID_ARGUMENT`. Generated Firefox fingerprints
4121
+ * include `TE: trailers`, and a few include `Connection: keep-alive`.
3691
4122
  */
3692
4123
  var CONNECTION_HEADERS = /* @__PURE__ */ new Set([
3693
4124
  "connection",
@@ -3702,6 +4133,20 @@ var CONNECTION_HEADERS = /* @__PURE__ */ new Set([
3702
4133
  "upgrade"
3703
4134
  ]);
3704
4135
  /**
4136
+ * Returns headers without the connection-level ones.
4137
+ *
4138
+ * A generated fingerprint copies a browser's headers, connection-level ones
4139
+ * included. The HTTP client that sends the request manages its own connection
4140
+ * and sets these itself: a copied `Connection: keep-alive` asks the server to
4141
+ * hold open a connection the client may never reuse.
4142
+ *
4143
+ * @param headers Request headers, such as a generated fingerprint.
4144
+ * @returns The headers minus any connection-level entry, in any letter case.
4145
+ */
4146
+ function withoutConnectionHeaders(headers) {
4147
+ return Object.fromEntries(Object.entries(headers).filter(([header]) => !CONNECTION_HEADERS.has(header.toLowerCase())));
4148
+ }
4149
+ /**
3705
4150
  * Returns headers without the ones Chromium sets for itself.
3706
4151
  *
3707
4152
  * A browser sets the `Sec-Fetch-*` family with values that fit each request: a
@@ -3717,13 +4162,9 @@ var CONNECTION_HEADERS = /* @__PURE__ */ new Set([
3717
4162
  * any letter case.
3718
4163
  */
3719
4164
  function withoutBrowserManagedHeaders(headers) {
3720
- return Object.fromEntries(Object.entries(headers).filter(([header]) => {
3721
- const name = header.toLowerCase();
3722
- return !name.startsWith("sec-fetch-") && !CONNECTION_HEADERS.has(name);
3723
- }));
4165
+ return Object.fromEntries(Object.entries(withoutConnectionHeaders(headers)).filter(([header]) => !header.toLowerCase().startsWith("sec-fetch-")));
3724
4166
  }
3725
- //#endregion
3726
- //#region src/utils/timeout.ts
4167
+ // src/utils/timeout.ts
3727
4168
  /**
3728
4169
  * Waits for an operation, rejecting if it takes longer than the given time.
3729
4170
  * The operation itself keeps running; only the wait is bounded.
@@ -3745,8 +4186,7 @@ async function withTimeout(operation, timeoutMs, description) {
3745
4186
  if (timeout) clearTimeout(timeout);
3746
4187
  }
3747
4188
  }
3748
- //#endregion
3749
- //#region src/scraper/fetcher/ManagedBrowser.ts
4189
+ // src/scraper/fetcher/ManagedBrowser.ts
3750
4190
  /**
3751
4191
  * Process IDs of the browsers `ManagedBrowser.launch()` started. Playwright's
3752
4192
  * `Browser` does not expose its process, so the ID is read over CDP at launch,
@@ -3927,6 +4367,33 @@ var ManagedBrowser = class ManagedBrowser {
3927
4367
  }
3928
4368
  }
3929
4369
  /**
4370
+ * Tells whether Playwright's own Chromium is installed: the headless shell a
4371
+ * launch uses by default, or the full build it falls back to.
4372
+ *
4373
+ * Playwright only reports the full build's path. The shell of the same
4374
+ * revision sits next to it, in `chromium_headless_shell-<revision>`, and
4375
+ * Playwright marks a finished download with an `INSTALLATION_COMPLETE` file.
4376
+ *
4377
+ * @returns True when a launch without an explicit executable can succeed.
4378
+ */
4379
+ static isPlaywrightChromiumInstalled() {
4380
+ let fullBuildPath;
4381
+ try {
4382
+ fullBuildPath = chromium.executablePath();
4383
+ } catch {
4384
+ return false;
4385
+ }
4386
+ if (fs.existsSync(fullBuildPath)) return true;
4387
+ for (let dir = fullBuildPath; path.dirname(dir) !== dir; dir = path.dirname(dir)) {
4388
+ const revision = /^chromium-(\d+)$/.exec(path.basename(dir))?.[1];
4389
+ if (revision) {
4390
+ const shellDir = path.join(path.dirname(dir), `chromium_headless_shell-${revision}`);
4391
+ return fs.existsSync(path.join(shellDir, "INSTALLATION_COMPLETE"));
4392
+ }
4393
+ }
4394
+ return false;
4395
+ }
4396
+ /**
3930
4397
  * Resolves the Chromium binary to launch.
3931
4398
  *
3932
4399
  * Playwright's own managed build is pinned to the installed Playwright
@@ -3939,9 +4406,7 @@ var ManagedBrowser = class ManagedBrowser {
3939
4406
  static resolveChromiumExecutablePath() {
3940
4407
  const configuredPath = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH;
3941
4408
  if (configuredPath) return configuredPath;
3942
- try {
3943
- if (fs.existsSync(chromium.executablePath())) return;
3944
- } catch {}
4409
+ if (ManagedBrowser.isPlaywrightChromiumInstalled()) return;
3945
4410
  const systemPath = [
3946
4411
  "/usr/lib/chromium/chromium",
3947
4412
  "/usr/bin/chromium",
@@ -3964,8 +4429,7 @@ var ManagedBrowser = class ManagedBrowser {
3964
4429
  }
3965
4430
  }
3966
4431
  };
3967
- //#endregion
3968
- //#region src/scraper/fetcher/types.ts
4432
+ // src/scraper/fetcher/types.ts
3969
4433
  /**
3970
4434
  * Semantic status of a fetch operation, abstracting HTTP status codes
3971
4435
  * into meaningful states for content processing.
@@ -3997,8 +4461,7 @@ var FetchStatus = /* @__PURE__ */ function(FetchStatus) {
3997
4461
  FetchStatus["SKIPPED"] = "skipped";
3998
4462
  return FetchStatus;
3999
4463
  }({});
4000
- //#endregion
4001
- //#region src/scraper/fetcher/BrowserFetcher.ts
4464
+ // src/scraper/fetcher/BrowserFetcher.ts
4002
4465
  /**
4003
4466
  * Maximum redirects to follow via the request API. Matches Playwright's own
4004
4467
  * default (20) — redirects are followed manually only so every hop can be
@@ -4091,10 +4554,10 @@ var BrowserFetcher = class {
4091
4554
  page.on("requestfailed", (request) => {
4092
4555
  if (request.frame() === page?.mainFrame() && request.isNavigationRequest() && request.failure()?.errorText.includes("ERR_BLOCKED_BY_CLIENT")) blockedNavigation = request.url();
4093
4556
  });
4094
- const requestHeaders = withMarkdownPreferredAccept({
4557
+ const requestHeaders = {
4095
4558
  ...fingerprintHeaders,
4096
4559
  ...options?.headers
4097
- }, options?.headers);
4560
+ };
4098
4561
  await page.setExtraHTTPHeaders(withoutBrowserManagedHeaders(requestHeaders));
4099
4562
  const timeout = options?.timeout || this.defaultTimeoutMs;
4100
4563
  logger.debug(`Navigating to ${source} with browser...`);
@@ -4112,7 +4575,7 @@ var BrowserFetcher = class {
4112
4575
  } catch (error) {
4113
4576
  const message = error instanceof Error ? error.message : String(error);
4114
4577
  if (/ERR_BLOCKED_BY_CLIENT/.test(message)) throw new AccessPolicyError(`Security policy blocked network access to ${blockedNavigation ?? source}`);
4115
- if (!/frame was detached/i.test(message) && /ERR_INVALID_ARGUMENT|ERR_ABORTED|Download is starting/i.test(message)) return await this.fetchViaRequest(page, source, options, timeout, requestHeaders);
4578
+ if (!(/frame was detached/i.test(message) || !this.managedBrowser.isCurrent(browser)) && /ERR_INVALID_ARGUMENT|ERR_ABORTED|Download is starting/i.test(message)) return await this.fetchViaRequest(page, source, options, timeout, requestHeaders);
4116
4579
  throw error;
4117
4580
  }
4118
4581
  await page.waitForLoadState("networkidle", { timeout: Math.min(timeout, 5e3) }).catch(() => void 0);
@@ -4249,8 +4712,7 @@ var BrowserFetcher = class {
4249
4712
  await this.managedBrowser.close();
4250
4713
  }
4251
4714
  };
4252
- //#endregion
4253
- //#region src/scraper/fetcher/FileFetcher.ts
4715
+ // src/scraper/fetcher/FileFetcher.ts
4254
4716
  /**
4255
4717
  * Fetches content from local file system.
4256
4718
  */
@@ -4299,8 +4761,7 @@ var FileFetcher = class {
4299
4761
  }
4300
4762
  }
4301
4763
  };
4302
- //#endregion
4303
- //#region src/pipeline/errors.ts
4764
+ // src/pipeline/errors.ts
4304
4765
  var PipelineError = class extends Error {
4305
4766
  cause;
4306
4767
  constructor(message, cause) {
@@ -4319,8 +4780,144 @@ var CancellationError = class extends PipelineError {
4319
4780
  super(message);
4320
4781
  }
4321
4782
  };
4322
- //#endregion
4323
- //#region src/scraper/fetcher/HttpFetcher.ts
4783
+ // src/scraper/fetcher/HostBackoff.ts
4784
+ /**
4785
+ * Per-host pause for servers that ask the scraper to slow down.
4786
+ *
4787
+ * A crawl runs several requests at once. When one of them is throttled, the
4788
+ * others would go on requesting the same host at full speed, so a throttle
4789
+ * pauses the host rather than the one request that met it.
4790
+ */
4791
+ /**
4792
+ * The longest a host is paused for, whatever the server asks. A server asking
4793
+ * for an hour would otherwise park the crawl; capped, the request is retried
4794
+ * and fails if the server still refuses it.
4795
+ */
4796
+ var MAX_THROTTLE_DELAY_MS = 6e4;
4797
+ /**
4798
+ * Caps the doubling. Beyond this the pause is at its maximum anyway, and the
4799
+ * cap keeps a base delay of zero from multiplying into NaN.
4800
+ */
4801
+ var MAX_BACKOFF_EXPONENT = 16;
4802
+ /**
4803
+ * Parses a `Retry-After` header into a delay.
4804
+ *
4805
+ * Accepts both forms RFC 9110 allows: delta-seconds (`120`) and an HTTP-date
4806
+ * (`Wed, 21 Oct 2015 07:28:00 GMT`). A date in the past means no delay.
4807
+ *
4808
+ * @param value The header value as the response carried it.
4809
+ * @param now The current time in epoch milliseconds.
4810
+ * @returns The delay in milliseconds, or undefined when the header is missing
4811
+ * or unreadable.
4812
+ */
4813
+ function parseRetryAfter(value, now = Date.now()) {
4814
+ if (typeof value !== "string") return;
4815
+ const trimmed = value.trim();
4816
+ if (/^\d+$/.test(trimmed)) return Number(trimmed) * 1e3;
4817
+ const date = /[a-z]/i.test(trimmed) ? Date.parse(trimmed) : NaN;
4818
+ return Number.isNaN(date) ? void 0 : Math.max(0, date - now);
4819
+ }
4820
+ /**
4821
+ * Pauses every request to a host after the host throttles one of them.
4822
+ *
4823
+ * Shared by the fetchers of one crawl, so all of its workers wait out the same
4824
+ * pause. The pause doubles with each throttled response in a row and resets
4825
+ * once the host answers a request sent after the last throttle.
4826
+ */
4827
+ var HostBackoff = class {
4828
+ hosts = /* @__PURE__ */ new Map();
4829
+ /**
4830
+ * Waits until requests to the host of `url` may resume.
4831
+ *
4832
+ * @param url The URL about to be requested.
4833
+ * @param signal Aborts the wait.
4834
+ * @throws {CancellationError} When the signal aborts.
4835
+ */
4836
+ async wait(url, signal) {
4837
+ const host = hostOf(url);
4838
+ for (let state = this.hosts.get(host); state && state.resumeAt > Date.now(); state = this.hosts.get(host)) await sleep(state.resumeAt - Date.now(), signal);
4839
+ }
4840
+ /**
4841
+ * Records a throttled response and pauses its host.
4842
+ *
4843
+ * Without a `Retry-After`, the pause starts at `baseDelayMs` and doubles with
4844
+ * each throttle in a row, and is jittered down by up to half so the requests
4845
+ * of separate crawls do not retry in step.
4846
+ *
4847
+ * @param url The URL that was throttled.
4848
+ * @param baseDelayMs The pause after the first throttle, before jitter.
4849
+ * @param retryAfterMs The pause the server asked for, if it named one.
4850
+ * @returns How long the host is paused from now, in milliseconds.
4851
+ */
4852
+ throttle(url, baseDelayMs, retryAfterMs) {
4853
+ const host = hostOf(url);
4854
+ const now = Date.now();
4855
+ const state = this.hosts.get(host) ?? {
4856
+ resumeAt: 0,
4857
+ strikes: 0,
4858
+ throttledAt: 0
4859
+ };
4860
+ state.strikes++;
4861
+ state.throttledAt = now;
4862
+ let delay;
4863
+ if (retryAfterMs !== void 0) delay = Math.min(retryAfterMs, MAX_THROTTLE_DELAY_MS);
4864
+ else {
4865
+ const exponent = Math.min(state.strikes - 1, MAX_BACKOFF_EXPONENT);
4866
+ const nominal = Math.min(baseDelayMs * 2 ** exponent, MAX_THROTTLE_DELAY_MS);
4867
+ delay = nominal / 2 + Math.random() * nominal / 2;
4868
+ }
4869
+ state.resumeAt = Math.max(state.resumeAt, now + Math.round(delay));
4870
+ this.hosts.set(host, state);
4871
+ return state.resumeAt - now;
4872
+ }
4873
+ /**
4874
+ * Records a normal answer from the host, which ends its backoff.
4875
+ *
4876
+ * Only a request sent after the last throttle counts: one that was already
4877
+ * in flight says nothing about whether the host has recovered.
4878
+ *
4879
+ * @param url The URL that was answered.
4880
+ * @param sentAt When the request was sent, in epoch milliseconds.
4881
+ */
4882
+ recover(url, sentAt) {
4883
+ const host = hostOf(url);
4884
+ const state = this.hosts.get(host);
4885
+ if (state && sentAt > state.throttledAt) this.hosts.delete(host);
4886
+ }
4887
+ };
4888
+ /**
4889
+ * Returns the key a URL's pause is stored under.
4890
+ *
4891
+ * @param url An absolute URL.
4892
+ * @returns The URL's host, including any port.
4893
+ */
4894
+ function hostOf(url) {
4895
+ return new URL(url).host;
4896
+ }
4897
+ /**
4898
+ * Resolves after `ms` milliseconds, or rejects as soon as the signal aborts.
4899
+ *
4900
+ * @param ms The delay in milliseconds.
4901
+ * @param signal Aborts the delay.
4902
+ */
4903
+ function sleep(ms, signal) {
4904
+ return new Promise((resolve, reject) => {
4905
+ const onAbort = () => {
4906
+ clearTimeout(timer);
4907
+ reject(new CancellationError("Wait for a throttled host cancelled"));
4908
+ };
4909
+ const timer = setTimeout(() => {
4910
+ signal?.removeEventListener("abort", onAbort);
4911
+ resolve();
4912
+ }, ms);
4913
+ if (signal?.aborted) {
4914
+ onAbort();
4915
+ return;
4916
+ }
4917
+ signal?.addEventListener("abort", onAbort, { once: true });
4918
+ });
4919
+ }
4920
+ // src/scraper/fetcher/HttpFetcher.ts
4324
4921
  /**
4325
4922
  * Maximum number of redirects to follow in a single fetch. Matches the legacy
4326
4923
  * axios default; kept here as a named constant because redirects are now
@@ -4328,7 +4925,16 @@ var CancellationError = class extends PipelineError {
4328
4925
  */
4329
4926
  var MAX_REDIRECTS = 5;
4330
4927
  /**
4928
+ * How much longer than other retries a throttled request waits when the server
4929
+ * names no delay. A retry after the usual second would most likely be
4930
+ * throttled again.
4931
+ */
4932
+ var THROTTLE_DELAY_FACTOR = 5;
4933
+ /**
4331
4934
  * Fetches content from remote sources using HTTP/HTTPS.
4935
+ *
4936
+ * A 429, or a 503 with `Retry-After`, pauses every request this fetcher sends
4937
+ * to that host (see {@link HostBackoff}).
4332
4938
  */
4333
4939
  var HttpFetcher = class {
4334
4940
  maxRetriesDefault;
@@ -4365,12 +4971,19 @@ var HttpFetcher = class {
4365
4971
  ];
4366
4972
  fingerprintGenerator;
4367
4973
  accessPolicy;
4368
- constructor(scraperConfig) {
4974
+ hostBackoff;
4975
+ /**
4976
+ * @param scraperConfig - Scraper settings, including the retry defaults.
4977
+ * @param hostBackoff - The per-host pause; pass one to share it with other
4978
+ * fetchers of the same crawl.
4979
+ */
4980
+ constructor(scraperConfig, hostBackoff = new HostBackoff()) {
4369
4981
  this.maxRetriesDefault = scraperConfig.fetcher.maxRetries;
4370
4982
  this.baseDelayDefaultMs = scraperConfig.fetcher.baseDelayMs;
4371
4983
  this.timeoutDefaultMs = scraperConfig.fetcher.timeoutMs;
4372
4984
  this.fingerprintGenerator = new FingerprintGenerator();
4373
4985
  this.accessPolicy = new ScraperAccessPolicy(scraperConfig.security);
4986
+ this.hostBackoff = hostBackoff;
4374
4987
  }
4375
4988
  canFetch(source) {
4376
4989
  return source.startsWith("http://") || source.startsWith("https://");
@@ -4389,134 +5002,141 @@ var HttpFetcher = class {
4389
5002
  }
4390
5003
  async performFetch(source, options, maxRetries = this.maxRetriesDefault, baseDelay = this.baseDelayDefaultMs, followRedirects = true) {
4391
5004
  await this.accessPolicy.assertNetworkUrlAllowed(source);
4392
- for (let attempt = 0; attempt <= maxRetries; attempt++) try {
5005
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
4393
5006
  let currentUrl = source;
4394
- let redirectCount = 0;
4395
- while (true) {
4396
- const headers = withMarkdownPreferredAccept({
4397
- ...this.fingerprintGenerator.generateHeaders(),
4398
- ...options?.headers
4399
- }, options?.headers);
4400
- if (options?.etag) {
4401
- headers["If-None-Match"] = options.etag;
4402
- logger.debug(`Conditional request for ${source} with If-None-Match: ${options.etag}`);
4403
- }
4404
- const config = {
4405
- responseType: "stream",
4406
- headers: {
4407
- ...headers,
4408
- "Accept-Encoding": "gzip, deflate, br"
4409
- },
4410
- timeout: options?.timeout ?? this.timeoutDefaultMs,
4411
- signal: options?.signal,
4412
- maxRedirects: 0,
4413
- decompress: true,
4414
- validateStatus: (status) => {
4415
- return status >= 200 && status < 400 || status === 304;
4416
- }
4417
- };
4418
- if (this.accessPolicy.shouldAllowInvalidTls(currentUrl)) config.httpsAgent = new https.Agent({ rejectUnauthorized: false });
4419
- const response = await axios.get(currentUrl, config);
4420
- let bodyConsumed = false;
4421
- try {
4422
- if (response.status === 304) {
4423
- logger.debug(`HTTP 304 Not Modified for ${currentUrl}`);
4424
- return {
4425
- content: Buffer.from(""),
4426
- mimeType: "text/plain",
4427
- source: currentUrl,
4428
- status: FetchStatus.NOT_MODIFIED
4429
- };
4430
- }
4431
- if (response.status >= 300 && response.status < 400) {
4432
- const location = response.headers.location;
4433
- if (!location) throw new ScraperError(`Redirect response for ${currentUrl} did not include a location header`, false);
4434
- if (!followRedirects) throw new RedirectError(currentUrl, location, response.status);
4435
- if (redirectCount >= MAX_REDIRECTS) throw new ScraperError(`Too many redirects while fetching ${source}`, false);
4436
- const redirectUrl = new URL(location, currentUrl).href;
4437
- await this.accessPolicy.assertNetworkUrlAllowed(redirectUrl);
4438
- currentUrl = redirectUrl;
4439
- redirectCount += 1;
4440
- continue;
5007
+ try {
5008
+ let redirectCount = 0;
5009
+ while (true) {
5010
+ const headers = {
5011
+ ...withoutConnectionHeaders(this.fingerprintGenerator.generateHeaders()),
5012
+ ...options?.headers
5013
+ };
5014
+ if (options?.etag) {
5015
+ headers["If-None-Match"] = options.etag;
5016
+ logger.debug(`Conditional request for ${source} with If-None-Match: ${options.etag}`);
4441
5017
  }
4442
- const contentTypeHeader = response.headers["content-type"];
4443
- const { mimeType, charset } = MimeTypeUtils.parseContentType(typeof contentTypeHeader === "string" ? contentTypeHeader : void 0);
4444
- const rawContentEncoding = response.headers["content-encoding"];
4445
- const contentEncoding = typeof rawContentEncoding === "string" ? rawContentEncoding : void 0;
4446
- const finalUrl = response.request?.res?.responseUrl || response.request?.responseUrl || response.config?.url || currentUrl;
4447
- await this.accessPolicy.assertNetworkUrlAllowed(finalUrl);
4448
- if (options?.acceptsMimeType && !options.acceptsMimeType(mimeType)) {
4449
- logger.debug(`Skipping ${finalUrl}: ${mimeType} is not processable`);
5018
+ const config = {
5019
+ responseType: "stream",
5020
+ headers: {
5021
+ ...headers,
5022
+ "Accept-Encoding": "gzip, deflate, br"
5023
+ },
5024
+ timeout: options?.timeout ?? this.timeoutDefaultMs,
5025
+ signal: options?.signal,
5026
+ maxRedirects: 0,
5027
+ decompress: true,
5028
+ validateStatus: (status) => {
5029
+ return status >= 200 && status < 400 || status === 304;
5030
+ }
5031
+ };
5032
+ if (this.accessPolicy.shouldAllowInvalidTls(currentUrl)) config.httpsAgent = new https.Agent({ rejectUnauthorized: false });
5033
+ await this.hostBackoff.wait(currentUrl, options?.signal);
5034
+ const sentAt = Date.now();
5035
+ const response = await axios.get(currentUrl, config);
5036
+ this.hostBackoff.recover(currentUrl, sentAt);
5037
+ let bodyConsumed = false;
5038
+ try {
5039
+ if (response.status === 304) {
5040
+ logger.debug(`HTTP 304 Not Modified for ${currentUrl}`);
5041
+ return {
5042
+ content: Buffer.from(""),
5043
+ mimeType: "text/plain",
5044
+ source: currentUrl,
5045
+ status: FetchStatus.NOT_MODIFIED
5046
+ };
5047
+ }
5048
+ if (response.status >= 300 && response.status < 400) {
5049
+ const location = response.headers.location;
5050
+ if (!location) throw new ScraperError(`Redirect response for ${currentUrl} did not include a location header`, false);
5051
+ if (!followRedirects) throw new RedirectError(currentUrl, location, response.status);
5052
+ if (redirectCount >= MAX_REDIRECTS) throw new ScraperError(`Too many redirects while fetching ${source}`, false);
5053
+ const redirectUrl = new URL(location, currentUrl).href;
5054
+ await this.accessPolicy.assertNetworkUrlAllowed(redirectUrl);
5055
+ currentUrl = redirectUrl;
5056
+ redirectCount += 1;
5057
+ continue;
5058
+ }
5059
+ const contentTypeHeader = response.headers["content-type"];
5060
+ const { mimeType, charset } = MimeTypeUtils.parseContentType(typeof contentTypeHeader === "string" ? contentTypeHeader : void 0);
5061
+ const rawContentEncoding = response.headers["content-encoding"];
5062
+ const contentEncoding = typeof rawContentEncoding === "string" ? rawContentEncoding : void 0;
5063
+ const finalUrl = response.request?.res?.responseUrl || response.request?.responseUrl || response.config?.url || currentUrl;
5064
+ await this.accessPolicy.assertNetworkUrlAllowed(finalUrl);
5065
+ if (options?.acceptsMimeType && !options.acceptsMimeType(mimeType)) {
5066
+ logger.debug(`Skipping ${finalUrl}: ${mimeType} is not processable`);
5067
+ return {
5068
+ content: Buffer.from(""),
5069
+ mimeType,
5070
+ charset,
5071
+ source: finalUrl,
5072
+ status: FetchStatus.SKIPPED
5073
+ };
5074
+ }
5075
+ const etag = response.headers.etag || response.headers.ETag;
5076
+ if (etag) logger.debug(`Received ETag for ${finalUrl}: ${etag}`);
5077
+ const lastModified = response.headers["last-modified"];
5078
+ const lastModifiedISO = lastModified ? new Date(lastModified).toISOString() : void 0;
5079
+ const content = await readStreamToBuffer(response.data, options?.signal);
5080
+ bodyConsumed = true;
5081
+ const challengeType = MimeTypeUtils.isHtml(mimeType) ? detectChallengePage(content) : null;
5082
+ if (challengeType) throw new ChallengeError(source, response.status, challengeType, currentUrl);
4450
5083
  return {
4451
- content: Buffer.from(""),
5084
+ content,
4452
5085
  mimeType,
4453
5086
  charset,
5087
+ encoding: contentEncoding,
4454
5088
  source: finalUrl,
4455
- status: FetchStatus.SKIPPED
5089
+ etag,
5090
+ lastModified: lastModifiedISO,
5091
+ status: FetchStatus.SUCCESS
4456
5092
  };
5093
+ } finally {
5094
+ if (!bodyConsumed) destroyStream(response.data);
4457
5095
  }
4458
- const etag = response.headers.etag || response.headers.ETag;
4459
- if (etag) logger.debug(`Received ETag for ${finalUrl}: ${etag}`);
4460
- const lastModified = response.headers["last-modified"];
4461
- const lastModifiedISO = lastModified ? new Date(lastModified).toISOString() : void 0;
4462
- const content = await readStreamToBuffer(response.data, options?.signal);
4463
- bodyConsumed = true;
4464
- const challengeType = MimeTypeUtils.isHtml(mimeType) ? detectChallengePage(content) : null;
4465
- if (challengeType) throw new ChallengeError(source, response.status, challengeType);
5096
+ }
5097
+ } catch (error) {
5098
+ if (error instanceof RedirectError || error instanceof ChallengeError) throw error;
5099
+ if (error instanceof ScraperError && !error.isRetryable) throw error;
5100
+ const axiosError = error;
5101
+ const status = axiosError.response?.status;
5102
+ const code = axiosError.code;
5103
+ const errorCause = error instanceof Error ? error : void 0;
5104
+ if (options?.signal?.aborted || code === "ERR_CANCELED") throw new CancellationError("HTTP fetch cancelled");
5105
+ if (status === 404) {
5106
+ logger.debug(`Resource not found (404): ${source}`);
4466
5107
  return {
4467
- content,
4468
- mimeType,
4469
- charset,
4470
- encoding: contentEncoding,
4471
- source: finalUrl,
4472
- etag,
4473
- lastModified: lastModifiedISO,
4474
- status: FetchStatus.SUCCESS
5108
+ content: Buffer.from(""),
5109
+ mimeType: "text/plain",
5110
+ source,
5111
+ status: FetchStatus.NOT_FOUND
4475
5112
  };
4476
- } finally {
4477
- if (!bodyConsumed) destroyStream(response.data);
4478
5113
  }
5114
+ if (!followRedirects && status && status >= 300 && status < 400) {
5115
+ const location = axiosError.response?.headers?.location;
5116
+ if (location) throw new RedirectError(source, location, status);
5117
+ }
5118
+ const retryAfterMs = parseRetryAfter(axiosError.response?.headers?.["retry-after"]);
5119
+ const throttleDelayMs = status === 429 || status === 503 && retryAfterMs !== void 0 ? this.hostBackoff.throttle(currentUrl, baseDelay * THROTTLE_DELAY_FACTOR, retryAfterMs) : void 0;
5120
+ if (status === 403 || status === 429) {
5121
+ const cfMitigated = axiosError.response?.headers?.["cf-mitigated"];
5122
+ const server = axiosError.response?.headers?.server;
5123
+ let responseBody = "";
5124
+ if (axiosError.response?.data) try {
5125
+ responseBody = (await readStreamToBuffer(axiosError.response.data)).toString("utf-8");
5126
+ } catch {}
5127
+ if (cfMitigated === "challenge" || status === 403 && server === "cloudflare" || responseBody.includes("Enable JavaScript and cookies to continue") || responseBody.includes("Just a moment...") || responseBody.includes("cf_chl_opt")) throw new ChallengeError(source, status, "cloudflare", currentUrl);
5128
+ }
5129
+ destroyStream(axiosError.response?.data);
5130
+ if (this.isTlsCertificateError(code)) throw new TlsCertificateError(source, code, errorCause);
5131
+ if (attempt < maxRetries && (status === void 0 || this.retryableStatusCodes.includes(status)) && !this.nonRetryableErrorCodes.includes(code ?? "")) {
5132
+ const delay = throttleDelayMs ?? baseDelay * 2 ** attempt;
5133
+ logger.warn(`⚠️ Attempt ${attempt + 1}/${maxRetries + 1} failed for ${source} (Status: ${status}, Code: ${code}). Retrying in ${delay}ms...`);
5134
+ if (throttleDelayMs === void 0) await this.delay(delay);
5135
+ continue;
5136
+ }
5137
+ const failureMessage = `Failed to fetch ${source} after ${attempt + 1} attempts: ${axiosError.message ?? "Unknown error"}`;
5138
+ throw status === void 0 ? new ScraperError(failureMessage, true, errorCause) : new HttpStatusError(failureMessage, true, status, errorCause, currentUrl);
4479
5139
  }
4480
- } catch (error) {
4481
- if (error instanceof RedirectError || error instanceof ChallengeError) throw error;
4482
- if (error instanceof ScraperError && !error.isRetryable) throw error;
4483
- const axiosError = error;
4484
- const status = axiosError.response?.status;
4485
- const code = axiosError.code;
4486
- const errorCause = error instanceof Error ? error : void 0;
4487
- if (options?.signal?.aborted || code === "ERR_CANCELED") throw new CancellationError("HTTP fetch cancelled");
4488
- if (status === 404) {
4489
- logger.debug(`Resource not found (404): ${source}`);
4490
- return {
4491
- content: Buffer.from(""),
4492
- mimeType: "text/plain",
4493
- source,
4494
- status: FetchStatus.NOT_FOUND
4495
- };
4496
- }
4497
- if (!followRedirects && status && status >= 300 && status < 400) {
4498
- const location = axiosError.response?.headers?.location;
4499
- if (location) throw new RedirectError(source, location, status);
4500
- }
4501
- if (status === 403) {
4502
- const cfMitigated = axiosError.response?.headers?.["cf-mitigated"];
4503
- const server = axiosError.response?.headers?.server;
4504
- let responseBody = "";
4505
- if (axiosError.response?.data) try {
4506
- responseBody = (await readStreamToBuffer(axiosError.response.data)).toString("utf-8");
4507
- } catch {}
4508
- if (cfMitigated === "challenge" || server === "cloudflare" || responseBody.includes("Enable JavaScript and cookies to continue") || responseBody.includes("Just a moment...") || responseBody.includes("cf_chl_opt")) throw new ChallengeError(source, status, "cloudflare");
4509
- }
4510
- destroyStream(axiosError.response?.data);
4511
- if (this.isTlsCertificateError(code)) throw new TlsCertificateError(source, code, errorCause);
4512
- if (attempt < maxRetries && (status === void 0 || this.retryableStatusCodes.includes(status)) && !this.nonRetryableErrorCodes.includes(code ?? "")) {
4513
- const delay = baseDelay * 2 ** attempt;
4514
- logger.warn(`⚠️ Attempt ${attempt + 1}/${maxRetries + 1} failed for ${source} (Status: ${status}, Code: ${code}). Retrying in ${delay}ms...`);
4515
- await this.delay(delay);
4516
- continue;
4517
- }
4518
- const failureMessage = `Failed to fetch ${source} after ${attempt + 1} attempts: ${axiosError.message ?? "Unknown error"}`;
4519
- throw status === void 0 ? new ScraperError(failureMessage, true, errorCause) : new HttpStatusError(failureMessage, true, status, errorCause);
4520
5140
  }
4521
5141
  throw new ScraperError(`Failed to fetch ${source} after ${maxRetries + 1} attempts`, true);
4522
5142
  }
@@ -4556,8 +5176,7 @@ async function readStreamToBuffer(stream, signal) {
4556
5176
  }
4557
5177
  return Buffer.concat(chunks);
4558
5178
  }
4559
- //#endregion
4560
- //#region src/scraper/fetcher/AutoDetectFetcher.ts
5179
+ // src/scraper/fetcher/AutoDetectFetcher.ts
4561
5180
  /** Statuses anti-bot layers return that a real browser can often get past. */
4562
5181
  var ANTI_BOT_STATUS_CODES = /* @__PURE__ */ new Set([403, 429]);
4563
5182
  /**
@@ -4571,13 +5190,15 @@ var AutoDetectFetcher = class AutoDetectFetcher {
4571
5190
  httpFetcher;
4572
5191
  browserFetcher;
4573
5192
  fileFetcher;
5193
+ /** Pauses a host that throttled a request, for the browser fallback too. */
5194
+ hostBackoff = new HostBackoff();
4574
5195
  /**
4575
5196
  * @param scraperConfig - Scraper settings shared by all fetchers.
4576
5197
  * @param managedBrowser - The browser for the browser fallback; pass one to
4577
5198
  * share it with the HTML renderer.
4578
5199
  */
4579
5200
  constructor(scraperConfig, managedBrowser) {
4580
- this.httpFetcher = new HttpFetcher(scraperConfig);
5201
+ this.httpFetcher = new HttpFetcher(scraperConfig, this.hostBackoff);
4581
5202
  this.browserFetcher = new BrowserFetcher(scraperConfig, managedBrowser);
4582
5203
  this.fileFetcher = new FileFetcher(scraperConfig);
4583
5204
  }
@@ -4594,6 +5215,15 @@ var AutoDetectFetcher = class AutoDetectFetcher {
4594
5215
  return null;
4595
5216
  }
4596
5217
  /**
5218
+ * Returns the URL whose response caused a fetch failure.
5219
+ *
5220
+ * @param error The error the HTTP fetcher threw.
5221
+ * @returns The answering URL, or undefined when the error does not name one.
5222
+ */
5223
+ static responseUrl(error) {
5224
+ if (error instanceof ChallengeError || error instanceof HttpStatusError) return error.responseUrl;
5225
+ }
5226
+ /**
4597
5227
  * Check if this fetcher can handle the given source.
4598
5228
  * Returns true for any URL that any of the underlying fetchers can handle.
4599
5229
  */
@@ -4616,6 +5246,7 @@ var AutoDetectFetcher = class AutoDetectFetcher {
4616
5246
  const reason = AutoDetectFetcher.browserFallbackReason(error);
4617
5247
  if (reason) {
4618
5248
  logger.info(`🔄 ${reason} for ${source}, falling back to browser fetcher...`);
5249
+ for (const url of /* @__PURE__ */ new Set([source, AutoDetectFetcher.responseUrl(error)])) if (url) await this.hostBackoff.wait(url, options?.signal);
4619
5250
  return this.browserFetcher.fetch(source, options);
4620
5251
  }
4621
5252
  throw error;
@@ -4629,8 +5260,7 @@ var AutoDetectFetcher = class AutoDetectFetcher {
4629
5260
  await Promise.allSettled([this.browserFetcher.close()]);
4630
5261
  }
4631
5262
  };
4632
- //#endregion
4633
- //#region src/scraper/types.ts
5263
+ // src/scraper/types.ts
4634
5264
  /**
4635
5265
  * Enum defining the available HTML processing strategies.
4636
5266
  */
@@ -4672,8 +5302,7 @@ var PageOutcome = /* @__PURE__ */ function(PageOutcome) {
4672
5302
  PageOutcome["Failed"] = "failed";
4673
5303
  return PageOutcome;
4674
5304
  }({});
4675
- //#endregion
4676
- //#region src/scraper/utils/llmsTxtParser.ts
5305
+ // src/scraper/utils/llmsTxtParser.ts
4677
5306
  var emptyLlmsTxtResult = () => ({
4678
5307
  sections: [],
4679
5308
  links: []
@@ -4781,8 +5410,7 @@ function parseLlmsTxt(content) {
4781
5410
  if (result.links.length === 0) return emptyLlmsTxtResult();
4782
5411
  return result;
4783
5412
  }
4784
- //#endregion
4785
- //#region src/scraper/utils/scope.ts
5413
+ // src/scraper/utils/scope.ts
4786
5414
  var INDEX_FILE_PATTERN = /^index(\.[a-z0-9]+)?$/i;
4787
5415
  /**
4788
5416
  * Extensions that mark a URL's last segment as a page rather than a directory.
@@ -4876,8 +5504,7 @@ function normalizeHost(host, hostname) {
4876
5504
  if (stripped === hostname) return host;
4877
5505
  return host.replace(hostname, stripped);
4878
5506
  }
4879
- //#endregion
4880
- //#region src/scraper/strategies/BaseScraperStrategy.ts
5507
+ // src/scraper/strategies/BaseScraperStrategy.ts
4881
5508
  var FailureThresholdExceededError = class extends ScraperError {};
4882
5509
  var BaseScraperStrategy = class BaseScraperStrategy {
4883
5510
  static FAILURE_RATE_MIN_SAMPLE = 10;
@@ -4977,6 +5604,16 @@ var BaseScraperStrategy = class BaseScraperStrategy {
4977
5604
  };
4978
5605
  }
4979
5606
  /**
5607
+ * Returns the URL that `scope` is measured from: the root after any redirect
5608
+ * on its first fetch, or else the URL the scrape started from.
5609
+ *
5610
+ * @param options Scraper options naming the URL the scrape started from.
5611
+ * @returns The scope base URL.
5612
+ */
5613
+ getScopeBaseUrl(options) {
5614
+ return this.canonicalBaseUrl ?? new URL$1(options.url);
5615
+ }
5616
+ /**
4980
5617
  * Determines if a URL should be processed based on scope and include/exclude patterns in ScraperOptions.
4981
5618
  * Scope is checked first, then patterns.
4982
5619
  *
@@ -4996,7 +5633,7 @@ var BaseScraperStrategy = class BaseScraperStrategy {
4996
5633
  if (!(url.startsWith("file://") && isFileUrlInsideRoots(url, context.internalAllowedFileRoots))) {
4997
5634
  const scope = options.scope ?? "subpages";
4998
5635
  try {
4999
- if (!isInScope(this.canonicalBaseUrl ?? new URL$1(options.url), new URL$1(url), scope)) return false;
5636
+ if (!isInScope(this.getScopeBaseUrl(options), new URL$1(url), scope)) return false;
5000
5637
  } catch {
5001
5638
  return false;
5002
5639
  }
@@ -5078,27 +5715,32 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5078
5715
  this.pagesIndexed++;
5079
5716
  } else this.retuneEffectiveTotal(options);
5080
5717
  logger.info(`🌐 Scraping page ${pagesScraped}/${this.effectiveTotal} (depth ${item.depth}/${maxDepth}): ${item.url}`);
5081
- await progressCallback({
5082
- pagesScraped,
5083
- totalPages: this.effectiveTotal,
5084
- totalDiscovered: this.totalDiscovered,
5085
- pagesIndexed: this.pagesIndexed,
5086
- currentUrl: item.url,
5087
- depth: item.depth,
5088
- maxDepth,
5089
- outcome,
5090
- result: null,
5091
- pageId: item.pageId,
5092
- ...extra,
5093
- ...extra.result ? { result: {
5094
- ...extra.result,
5095
- isAdditionalRepresentation: alreadyStored
5096
- } } : {},
5097
- ...extra.emptyPage ? { emptyPage: {
5098
- ...extra.emptyPage,
5099
- isAdditionalRepresentation: alreadyStored
5100
- } } : {}
5101
- });
5718
+ try {
5719
+ await progressCallback({
5720
+ pagesScraped,
5721
+ totalPages: this.effectiveTotal,
5722
+ totalDiscovered: this.totalDiscovered,
5723
+ pagesIndexed: this.pagesIndexed,
5724
+ currentUrl: item.url,
5725
+ depth: item.depth,
5726
+ maxDepth,
5727
+ outcome,
5728
+ result: null,
5729
+ pageId: item.pageId,
5730
+ ...extra,
5731
+ ...extra.result ? { result: {
5732
+ ...extra.result,
5733
+ isAdditionalRepresentation: alreadyStored
5734
+ } } : {},
5735
+ ...extra.emptyPage ? { emptyPage: {
5736
+ ...extra.emptyPage,
5737
+ isAdditionalRepresentation: alreadyStored
5738
+ } } : {}
5739
+ });
5740
+ } catch (error) {
5741
+ crawl.abortError ??= error instanceof Error ? error : new Error(String(error));
5742
+ throw error;
5743
+ }
5102
5744
  };
5103
5745
  try {
5104
5746
  const result = await this.processItem(item, options, signal);
@@ -5167,6 +5809,7 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5167
5809
  const wasPage = result.isContainer !== true;
5168
5810
  await report(PageOutcome.Empty, {
5169
5811
  currentUrl: finalUrl,
5812
+ ...!wasPage && item.pageId !== void 0 ? { deleted: true } : {},
5170
5813
  emptyPage: !wasPage ? void 0 : {
5171
5814
  url: finalUrl,
5172
5815
  contentUrl: result.contentUrl ?? (result.url && result.url !== finalUrl ? result.url : void 0),
@@ -5337,8 +5980,7 @@ function isFileUrlInsideRoots(url, roots) {
5337
5980
  return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
5338
5981
  });
5339
5982
  }
5340
- //#endregion
5341
- //#region src/utils/dom.ts
5983
+ // src/utils/dom.ts
5342
5984
  /**
5343
5985
  * Creates a JSDOM instance with a pre-configured virtual console to suppress console noise.
5344
5986
  * This utility simplifies the setup of JSDOM by providing a standard configuration.
@@ -5354,13 +5996,13 @@ function createJSDOM(html, options) {
5354
5996
  virtualConsole.on("info", () => {});
5355
5997
  virtualConsole.on("debug", () => {});
5356
5998
  virtualConsole.on("log", () => {});
5357
- return new JSDOM(html, {
5999
+ const finalOptions = {
5358
6000
  virtualConsole,
5359
6001
  ...options
5360
- });
6002
+ };
6003
+ return new JSDOM(html, finalOptions);
5361
6004
  }
5362
- //#endregion
5363
- //#region src/splitter/GreedySplitter.ts
6005
+ // src/splitter/GreedySplitter.ts
5364
6006
  /**
5365
6007
  * Takes small document chunks and greedily concatenates them into larger, more meaningful units
5366
6008
  * while preserving document structure and semantic boundaries.
@@ -5496,8 +6138,7 @@ var GreedySplitter = class {
5496
6138
  return common;
5497
6139
  }
5498
6140
  };
5499
- //#endregion
5500
- //#region src/splitter/errors.ts
6141
+ // src/splitter/errors.ts
5501
6142
  /**
5502
6143
  * Base error class for all splitter-related errors
5503
6144
  */
@@ -5515,8 +6156,7 @@ var MinimumChunkSizeError = class extends SplitterError {
5515
6156
  * Generic error for content splitting failures
5516
6157
  */
5517
6158
  var ContentSplitterError = class extends SplitterError {};
5518
- //#endregion
5519
- //#region src/splitter/splitters/CodeContentSplitter.ts
6159
+ // src/splitter/splitters/CodeContentSplitter.ts
5520
6160
  /**
5521
6161
  * Splits code content while preserving language information and formatting.
5522
6162
  * Uses line boundaries for splitting and ensures each chunk is properly
@@ -5549,8 +6189,7 @@ var CodeContentSplitter = class {
5549
6189
  return `\`\`\`${infoString || ""}\n${content.replace(/\n+$/, "")}\n\`\`\``;
5550
6190
  }
5551
6191
  };
5552
- //#endregion
5553
- //#region src/splitter/splitters/fenceState.ts
6192
+ // src/splitter/splitters/fenceState.ts
5554
6193
  var FENCE_PREFIX = "[ \\t]*(?:>[ \\t]*)*";
5555
6194
  var FENCE_OPENER = new RegExp(`^${FENCE_PREFIX}(\`{3,}|~{3,})`);
5556
6195
  function splitLinesWithOffsets(text) {
@@ -5634,8 +6273,7 @@ function hasOpenFenceAtEnd(chunk) {
5634
6273
  if (!opener) return false;
5635
6274
  return !isClosingFence(lines[lines.length - 1].content, opener[1][0], opener[1].length);
5636
6275
  }
5637
- //#endregion
5638
- //#region src/splitter/splitters/TextContentSplitter.ts
6276
+ // src/splitter/splitters/TextContentSplitter.ts
5639
6277
  /**
5640
6278
  * Splits text content using a hierarchical approach:
5641
6279
  * 1. Try splitting by paragraphs (double newlines)
@@ -5772,8 +6410,7 @@ var TextContentSplitter = class {
5772
6410
  return content;
5773
6411
  }
5774
6412
  };
5775
- //#endregion
5776
- //#region src/splitter/splitters/ListContentSplitter.ts
6413
+ // src/splitter/splitters/ListContentSplitter.ts
5777
6414
  var ListContentSplitter = class {
5778
6415
  options;
5779
6416
  textSplitter;
@@ -5823,8 +6460,7 @@ var ListContentSplitter = class {
5823
6460
  return mergedChunks;
5824
6461
  }
5825
6462
  };
5826
- //#endregion
5827
- //#region src/splitter/splitters/TableContentSplitter.ts
6463
+ // src/splitter/splitters/TableContentSplitter.ts
5828
6464
  /**
5829
6465
  * Splits table content while preserving headers and table formatting.
5830
6466
  * Each chunk maintains the table structure with headers and separator row.
@@ -5888,8 +6524,7 @@ var TableContentSplitter = class {
5888
6524
  return separator.includes("|") && /^\|?[\s-|]+\|?$/.test(separator);
5889
6525
  }
5890
6526
  };
5891
- //#endregion
5892
- //#region src/splitter/SemanticMarkdownSplitter.ts
6527
+ // src/splitter/SemanticMarkdownSplitter.ts
5893
6528
  /**
5894
6529
  * Removes an explicit anchor annotation from the end of a heading.
5895
6530
  *
@@ -6238,8 +6873,7 @@ var SemanticMarkdownSplitter = class SemanticMarkdownSplitter {
6238
6873
  return window.document;
6239
6874
  }
6240
6875
  };
6241
- //#endregion
6242
- //#region src/scraper/pipelines/BasePipeline.ts
6876
+ // src/scraper/pipelines/BasePipeline.ts
6243
6877
  /**
6244
6878
  * Base class for content processing pipelines.
6245
6879
  * Provides common functionality for executing middleware stacks.
@@ -6268,8 +6902,12 @@ var BasePipeline = class {
6268
6902
  * Executes a middleware stack on the given context.
6269
6903
  * This is a utility method used by derived pipeline classes.
6270
6904
  *
6905
+ * A middleware error is recorded in `context.errors` and the pipeline goes on
6906
+ * with what is left, except a `ScraperError`, which fails the page.
6907
+ *
6271
6908
  * @param middleware - The middleware stack to execute
6272
6909
  * @param context - The context to process
6910
+ * @throws {ScraperError} When a middleware throws one.
6273
6911
  */
6274
6912
  async executeMiddlewareStack(middleware, context) {
6275
6913
  let index = -1;
@@ -6283,12 +6921,12 @@ var BasePipeline = class {
6283
6921
  try {
6284
6922
  await dispatch(0);
6285
6923
  } catch (error) {
6924
+ if (error instanceof ScraperError) throw error;
6286
6925
  context.errors.push(error instanceof Error ? error : new Error(String(error)));
6287
6926
  }
6288
6927
  }
6289
6928
  };
6290
- //#endregion
6291
- //#region src/scraper/pipelines/DocumentPipeline.ts
6929
+ // src/scraper/pipelines/DocumentPipeline.ts
6292
6930
  /**
6293
6931
  * DocumentPipeline - Processes binary document formats using Xberg for text extraction,
6294
6932
  * then splits semantically.
@@ -6461,8 +7099,7 @@ function collectErrorReasons(error) {
6461
7099
  }
6462
7100
  return messages;
6463
7101
  }
6464
- //#endregion
6465
- //#region src/scraper/middleware/HtmlCheerioParserMiddleware.ts
7102
+ // src/scraper/middleware/HtmlCheerioParserMiddleware.ts
6466
7103
  /**
6467
7104
  * Middleware to parse HTML string/buffer content into a Cheerio object.
6468
7105
  * It populates the `context.dom` property.
@@ -6482,8 +7119,7 @@ var HtmlCheerioParserMiddleware = class {
6482
7119
  }
6483
7120
  }
6484
7121
  };
6485
- //#endregion
6486
- //#region src/scraper/middleware/HtmlLinkExtractorMiddleware.ts
7122
+ // src/scraper/middleware/HtmlLinkExtractorMiddleware.ts
6487
7123
  /**
6488
7124
  * Middleware to extract links (href attributes from <a> tags) from HTML content using Cheerio.
6489
7125
  * It expects the Cheerio API object to be available in `context.dom`.
@@ -6548,8 +7184,7 @@ var HtmlLinkExtractorMiddleware = class {
6548
7184
  await next();
6549
7185
  }
6550
7186
  };
6551
- //#endregion
6552
- //#region src/scraper/middleware/HtmlMetadataExtractorMiddleware.ts
7187
+ // src/scraper/middleware/HtmlMetadataExtractorMiddleware.ts
6553
7188
  /**
6554
7189
  * Middleware to extract the title from HTML content using Cheerio.
6555
7190
  * Assumes context.dom (Cheerio API object) is populated by a preceding middleware
@@ -6582,8 +7217,7 @@ var HtmlMetadataExtractorMiddleware = class {
6582
7217
  await next();
6583
7218
  }
6584
7219
  };
6585
- //#endregion
6586
- //#region src/scraper/middleware/HtmlNormalizationMiddleware.ts
7220
+ // src/scraper/middleware/HtmlNormalizationMiddleware.ts
6587
7221
  /**
6588
7222
  * Middleware that normalizes URLs and links in HTML content after DOM parsing.
6589
7223
  *
@@ -6774,8 +7408,7 @@ var HtmlNormalizationMiddleware = class {
6774
7408
  $element.replaceWith(htmlContent);
6775
7409
  }
6776
7410
  };
6777
- //#endregion
6778
- //#region src/scraper/utils/SimpleMemoryCache.ts
7411
+ // src/scraper/utils/SimpleMemoryCache.ts
6779
7412
  /**
6780
7413
  * A simple in-memory LRU (Least Recently Used) cache.
6781
7414
  * When the cache reaches maxSize, the oldest (least recently used) entry is evicted.
@@ -6845,8 +7478,7 @@ var SimpleMemoryCache = class {
6845
7478
  this.cache.clear();
6846
7479
  }
6847
7480
  };
6848
- //#endregion
6849
- //#region src/scraper/middleware/subresourceBlocklist.ts
7481
+ // src/scraper/middleware/subresourceBlocklist.ts
6850
7482
  var BLOCKLIST_NOT_BLOCKED = Object.freeze({ blocked: false });
6851
7483
  var SUBRESOURCE_BLOCKLIST = Object.freeze([
6852
7484
  {
@@ -7000,8 +7632,7 @@ function isBlockedSubresource(url) {
7000
7632
  }
7001
7633
  return BLOCKLIST_NOT_BLOCKED;
7002
7634
  }
7003
- //#endregion
7004
- //#region src/scraper/middleware/HtmlPlaywrightMiddleware.ts
7635
+ // src/scraper/middleware/HtmlPlaywrightMiddleware.ts
7005
7636
  /**
7006
7637
  * Most redirects a sub-resource fetch follows. Matches Playwright's own default
7007
7638
  * (20): the renderer follows redirects itself only to check every hop against
@@ -7435,10 +8066,6 @@ var HtmlPlaywrightMiddleware = class HtmlPlaywrightMiddleware {
7435
8066
  if (!(error instanceof Error)) return false;
7436
8067
  return error.message.includes("Target page, context or browser has been closed");
7437
8068
  }
7438
- formatRouteError(error) {
7439
- const message = error instanceof Error ? error.message : String(error);
7440
- return message.split("\n")[0] || message;
7441
- }
7442
8069
  isSpeculativePrefetch(route) {
7443
8070
  const headers = route.request().headers();
7444
8071
  return headers["next-router-prefetch"] === "1" || headers.purpose?.toLowerCase() === "prefetch" || headers["sec-purpose"]?.toLowerCase().includes("prefetch") === true;
@@ -7486,7 +8113,7 @@ var HtmlPlaywrightMiddleware = class HtmlPlaywrightMiddleware {
7486
8113
  await route.continue(options);
7487
8114
  } catch (error) {
7488
8115
  if (this.ignoreRouteLifecycleError(error, "continue", reqUrl)) return;
7489
- const errorMessage = this.formatRouteError(error);
8116
+ const errorMessage = firstErrorLine(error);
7490
8117
  logger.debug(`Error continuing ${resourceType} ${reqUrl}: ${errorMessage}`);
7491
8118
  await this.abortRoute(route, reqUrl, "abort after continue error", "failed");
7492
8119
  }
@@ -7559,7 +8186,7 @@ var HtmlPlaywrightMiddleware = class HtmlPlaywrightMiddleware {
7559
8186
  await this.fulfillRoute(route, reqUrl, { response }, "fulfill");
7560
8187
  } catch (error) {
7561
8188
  if (this.ignoreRouteLifecycleError(error, `fetch ${resourceType}`, reqUrl)) return;
7562
- const errorMessage = this.formatRouteError(error);
8189
+ const errorMessage = firstErrorLine(error);
7563
8190
  logger.debug(`Network error fetching ${resourceType} ${reqUrl}: ${errorMessage}`);
7564
8191
  await this.abortRoute(route, reqUrl, "abort after error", "failed");
7565
8192
  }
@@ -7692,9 +8319,11 @@ var HtmlPlaywrightMiddleware = class HtmlPlaywrightMiddleware {
7692
8319
  * - Injects Authorization header for all same-origin requests if credentials are present and not already set.
7693
8320
  * - Forwards all custom headers from context.options?.headers to Playwright requests.
7694
8321
  * - Waits for common loading indicators to disappear before extracting HTML.
8322
+ * - When rendering fails, `auto` mode records the error and keeps the fetched HTML.
7695
8323
  *
7696
8324
  * @param context The middleware context containing the HTML and source URL.
7697
8325
  * @param next The next middleware function in the pipeline.
8326
+ * @throws {RenderError} When rendering fails in `playwright` mode.
7698
8327
  */
7699
8328
  async process(context, next) {
7700
8329
  const contentType = context.options?.headers?.["content-type"] || context.contentType;
@@ -7721,7 +8350,9 @@ var HtmlPlaywrightMiddleware = class HtmlPlaywrightMiddleware {
7721
8350
  renderedHtml = await withTimeout(this.renderPage(browser, context, handles), this.getRenderTimeoutMs(), `Playwright render for ${context.source}`);
7722
8351
  } catch (error) {
7723
8352
  logger.error(`❌ Playwright failed to render ${context.source}: ${error}`);
7724
- context.errors.push(error instanceof Error ? error : /* @__PURE__ */ new Error(`Playwright rendering failed: ${String(error)}`));
8353
+ const renderError = error instanceof Error ? error : /* @__PURE__ */ new Error(`Playwright rendering failed: ${String(error)}`);
8354
+ if (scrapeMode === ScrapeMode.Playwright) throw new RenderError(context.source, renderError);
8355
+ context.errors.push(renderError);
7725
8356
  } finally {
7726
8357
  const closed = await this.cleanupPageAndContext(handles.page, handles.browserContext, context.source);
7727
8358
  const failedBeforeContext = renderedHtml === null && handles.browserContext === null;
@@ -7730,7 +8361,7 @@ var HtmlPlaywrightMiddleware = class HtmlPlaywrightMiddleware {
7730
8361
  if (renderedHtml !== null) {
7731
8362
  context.content = renderedHtml;
7732
8363
  logger.debug(`Playwright middleware updated content for ${context.source}. Proceeding.`);
7733
- } else logger.warn(`⚠️ Playwright rendering resulted in null content for ${context.source}. Proceeding without content update.`);
8364
+ }
7734
8365
  await next();
7735
8366
  }
7736
8367
  /**
@@ -7864,10 +8495,9 @@ function mergePlaywrightHeaders(requestHeaders, customHeaders, credentials, orig
7864
8495
  Authorization: `Basic ${basic}`
7865
8496
  };
7866
8497
  }
7867
- return withMarkdownPreferredAccept(headers, customHeaders);
8498
+ return headers;
7868
8499
  }
7869
- //#endregion
7870
- //#region src/scraper/middleware/HtmlSanitizerMiddleware.ts
8500
+ // src/scraper/middleware/HtmlSanitizerMiddleware.ts
7871
8501
  /**
7872
8502
  * Minimum share of the sanitized body's visible text that the main-content
7873
8503
  * region must hold before extraction is scoped to it. Tuning value: measured
@@ -8113,8 +8743,7 @@ var HtmlSanitizerMiddleware = class {
8113
8743
  await next();
8114
8744
  }
8115
8745
  };
8116
- //#endregion
8117
- //#region src/scraper/middleware/HtmlToMarkdownMiddleware.ts
8746
+ // src/scraper/middleware/HtmlToMarkdownMiddleware.ts
8118
8747
  var maxGfmTableRows = 500;
8119
8748
  var maxGfmTableCells = 1e3;
8120
8749
  var maxGfmTableHtmlLength = 1e5;
@@ -8349,8 +8978,7 @@ var HtmlToMarkdownMiddleware = class {
8349
8978
  await next();
8350
8979
  }
8351
8980
  };
8352
- //#endregion
8353
- //#region src/scraper/utils/charset.ts
8981
+ // src/scraper/utils/charset.ts
8354
8982
  /**
8355
8983
  * Utility functions for enhanced charset detection and handling.
8356
8984
  */
@@ -8411,8 +9039,7 @@ function normalizeCharset(charset) {
8411
9039
  const normalized = charset.toLowerCase().trim();
8412
9040
  return CHARSET_ALIASES[normalized] || normalized;
8413
9041
  }
8414
- //#endregion
8415
- //#region src/scraper/utils/buffer.ts
9042
+ // src/scraper/utils/buffer.ts
8416
9043
  /**
8417
9044
  * Decodes a Buffer or string to a JavaScript string using the specified charset.
8418
9045
  * The charset should be the encoding as reported by the source (e.g., HTTP header).
@@ -8437,8 +9064,7 @@ function convertToString(content, charset) {
8437
9064
  }
8438
9065
  }
8439
9066
  }
8440
- //#endregion
8441
- //#region src/scraper/pipelines/HtmlPipeline.ts
9067
+ // src/scraper/pipelines/HtmlPipeline.ts
8442
9068
  /**
8443
9069
  * HtmlPipeline - Processes HTML content into Markdown chunks.
8444
9070
  * Uses Playwright for rendering if needed and Cheerio for semantic extraction.
@@ -8520,12 +9146,11 @@ var HtmlPipeline = class extends BasePipeline {
8520
9146
  function createLazyDefuddleMiddleware() {
8521
9147
  let real = null;
8522
9148
  return { async process(context, next) {
8523
- if (!real) real = new (await (import("./HtmlDefuddleMiddleware-BNIv3ibo.js"))).HtmlDefuddleMiddleware();
9149
+ if (!real) real = new (await (import("./HtmlDefuddleMiddleware-DxjoyIFY.js"))).HtmlDefuddleMiddleware();
8524
9150
  await real.process(context, next);
8525
9151
  } };
8526
9152
  }
8527
- //#endregion
8528
- //#region src/splitter/TextDocumentSplitter.ts
9153
+ // src/splitter/TextDocumentSplitter.ts
8529
9154
  /**
8530
9155
  * TextDocumentSplitter - Simple text-based document splitter
8531
9156
  *
@@ -8578,8 +9203,7 @@ var TextDocumentSplitter = class {
8578
9203
  }
8579
9204
  }
8580
9205
  };
8581
- //#endregion
8582
- //#region src/splitter/JsonDocumentSplitter.ts
9206
+ // src/splitter/JsonDocumentSplitter.ts
8583
9207
  /**
8584
9208
  * JsonDocumentSplitter - Concatenation-friendly JSON document splitting.
8585
9209
  *
@@ -8806,8 +9430,7 @@ var JsonDocumentSplitter = class {
8806
9430
  });
8807
9431
  }
8808
9432
  };
8809
- //#endregion
8810
- //#region src/scraper/pipelines/JsonPipeline.ts
9433
+ // src/scraper/pipelines/JsonPipeline.ts
8811
9434
  /**
8812
9435
  * Pipeline for processing JSON content with semantic, hierarchical splitting.
8813
9436
  * Uses JsonDocumentSplitter to produce structurally faithful chunks (preserving {level, path})
@@ -8907,8 +9530,7 @@ var JsonPipeline = class extends BasePipeline {
8907
9530
  return currentDepth;
8908
9531
  }
8909
9532
  };
8910
- //#endregion
8911
- //#region src/scraper/middleware/MarkdownLinkExtractorMiddleware.ts
9533
+ // src/scraper/middleware/MarkdownLinkExtractorMiddleware.ts
8912
9534
  var inlineLinkPattern = /(^|[^!\\])\[[^\]\n]+\]\(([^)\s]+)(?:\s+"[^"]*"|\s+'[^']*'|\s+\([^)]*\))?\)/g;
8913
9535
  var referenceLinkPattern = /(^|[^!\\])\[[^\]\n]+\]\[([^\]\n]+)\]/g;
8914
9536
  var referenceDefinitionPattern = /^\s{0,3}\[([^\]\n]+)\]:\s*(\S+)(?:\s+.*)?$/gm;
@@ -8953,8 +9575,7 @@ function cleanReferenceTarget(target) {
8953
9575
  if (!target) return "";
8954
9576
  return target.trim().replace(/^<(.+)>$/, "$1");
8955
9577
  }
8956
- //#endregion
8957
- //#region src/scraper/middleware/MarkdownMetadataExtractorMiddleware.ts
9578
+ // src/scraper/middleware/MarkdownMetadataExtractorMiddleware.ts
8958
9579
  /**
8959
9580
  * Middleware to extract the title from Markdown content.
8960
9581
  * Prioritizes YAML frontmatter 'title' field, falls back to first H1 heading.
@@ -8987,8 +9608,7 @@ var MarkdownMetadataExtractorMiddleware = class {
8987
9608
  await next();
8988
9609
  }
8989
9610
  };
8990
- //#endregion
8991
- //#region src/scraper/pipelines/MarkdownPipeline.ts
9611
+ // src/scraper/pipelines/MarkdownPipeline.ts
8992
9612
  /**
8993
9613
  * MarkdownPipeline - Processes Markdown content using middleware and semantic splitting.
8994
9614
  */
@@ -9031,37 +9651,7 @@ var MarkdownPipeline = class extends BasePipeline {
9031
9651
  };
9032
9652
  }
9033
9653
  };
9034
- //#endregion
9035
- //#region src/splitter/treesitter/parsers/types.ts
9036
- /**
9037
- * Universal tree-sitter parser size limit.
9038
- * Set to 30,000 characters to be safely under the observed 32,767 limit.
9039
- */
9040
- var StructuralNodeType = /* @__PURE__ */ function(StructuralNodeType) {
9041
- StructuralNodeType["FUNCTION_DECLARATION"] = "function_declaration";
9042
- StructuralNodeType["ARROW_FUNCTION"] = "arrow_function";
9043
- StructuralNodeType["METHOD_DEFINITION"] = "method_definition";
9044
- StructuralNodeType["CONSTRUCTOR"] = "constructor";
9045
- StructuralNodeType["CLASS_DECLARATION"] = "class_declaration";
9046
- StructuralNodeType["OBJECT_EXPRESSION"] = "object_expression";
9047
- StructuralNodeType["INTERFACE_DECLARATION"] = "interface_declaration";
9048
- StructuralNodeType["TYPE_ALIAS_DECLARATION"] = "type_alias_declaration";
9049
- StructuralNodeType["NAMESPACE_DECLARATION"] = "namespace_declaration";
9050
- StructuralNodeType["ENUM_DECLARATION"] = "enum_declaration";
9051
- StructuralNodeType["JSX_ELEMENT"] = "jsx_element";
9052
- StructuralNodeType["JSX_FRAGMENT"] = "jsx_fragment";
9053
- StructuralNodeType["JSX_EXPRESSION"] = "jsx_expression";
9054
- StructuralNodeType["VARIABLE_DECLARATION"] = "variable_declaration";
9055
- StructuralNodeType["EXPORT_STATEMENT"] = "export_statement";
9056
- StructuralNodeType["IMPORT_STATEMENT"] = "import_statement";
9057
- StructuralNodeType["IF_STATEMENT"] = "if_statement";
9058
- StructuralNodeType["FOR_STATEMENT"] = "for_statement";
9059
- StructuralNodeType["WHILE_STATEMENT"] = "while_statement";
9060
- StructuralNodeType["SWITCH_STATEMENT"] = "switch_statement";
9061
- return StructuralNodeType;
9062
- }({});
9063
- //#endregion
9064
- //#region src/splitter/treesitter/parsers/PythonParser.ts
9654
+ // src/splitter/treesitter/parsers/PythonParser.ts
9065
9655
  /**
9066
9656
  * Python parser for tree-sitter based source code splitting.
9067
9657
  *
@@ -9251,54 +9841,6 @@ var PythonParser = class {
9251
9841
  if (node.hasError && node.type === "ERROR") acc.push(node);
9252
9842
  for (const c of node.children) this.collectErrorNodes(c, acc);
9253
9843
  }
9254
- getNodeText(node, source) {
9255
- return source.slice(node.startIndex, node.endIndex);
9256
- }
9257
- getNodeLines(node, _source) {
9258
- return {
9259
- startLine: node.startPosition.row + 1,
9260
- endLine: node.endPosition.row + 1
9261
- };
9262
- }
9263
- /**
9264
- * Legacy structural node extraction (used by existing tests).
9265
- * Produces a flat list (no parent/child linking beyond simple push).
9266
- */
9267
- extractStructuralNodes(tree, source) {
9268
- const src = source ?? tree.rootNode.text;
9269
- const out = [];
9270
- const structuralTypes = /* @__PURE__ */ new Set([...STRUCTURAL_DECL_TYPES$1, ...CONTENT_DECL_TYPES$1]);
9271
- const visit = (node) => {
9272
- if (structuralTypes.has(node.type)) {
9273
- if (this.shouldSkipStructuralNode(node)) {
9274
- for (const child of node.children) visit(child);
9275
- return;
9276
- }
9277
- const name = extractName$1(node);
9278
- const { startLine, startByte } = findDocumentationStart$1(node, src);
9279
- const endLine = node.endPosition.row + 1;
9280
- const structuralNode = {
9281
- type: this.classifyStructuralNode(node),
9282
- name,
9283
- startLine,
9284
- endLine,
9285
- startByte,
9286
- endByte: node.endIndex,
9287
- children: [],
9288
- text: this.getNodeText(node, src),
9289
- indentLevel: 0,
9290
- modifiers: [],
9291
- documentation: void 0
9292
- };
9293
- out.push(structuralNode);
9294
- for (const child of node.children) visit(child);
9295
- return;
9296
- }
9297
- for (const child of node.children) visit(child);
9298
- };
9299
- visit(tree.rootNode);
9300
- return this.deduplicate(out);
9301
- }
9302
9844
  /**
9303
9845
  * Boundary extraction: produces CodeBoundary[] directly from AST.
9304
9846
  */
@@ -9347,31 +9889,8 @@ var PythonParser = class {
9347
9889
  shouldSkipStructuralNode(_node) {
9348
9890
  return false;
9349
9891
  }
9350
- classifyStructuralNode(node) {
9351
- switch (node.type) {
9352
- case "function_definition":
9353
- case "async_function_definition": return StructuralNodeType.FUNCTION_DECLARATION;
9354
- case "class_definition": return StructuralNodeType.CLASS_DECLARATION;
9355
- case "import_statement":
9356
- case "import_from_statement": return StructuralNodeType.IMPORT_STATEMENT;
9357
- default: return StructuralNodeType.VARIABLE_DECLARATION;
9358
- }
9359
- }
9360
- deduplicate(nodes) {
9361
- const seen = /* @__PURE__ */ new Set();
9362
- const out = [];
9363
- for (const n of nodes) {
9364
- const key = `${n.startByte}:${n.endByte}:${n.type}:${n.name}`;
9365
- if (seen.has(key)) continue;
9366
- seen.add(key);
9367
- out.push(n);
9368
- }
9369
- out.sort((a, b) => a.startByte - b.startByte);
9370
- return out;
9371
- }
9372
9892
  };
9373
- //#endregion
9374
- //#region src/splitter/treesitter/parsers/TypeScriptParser.ts
9893
+ // src/splitter/treesitter/parsers/TypeScriptParser.ts
9375
9894
  /**
9376
9895
  * Simplified standalone TypeScript (and JavaScript) parser.
9377
9896
  *
@@ -9379,7 +9898,6 @@ var PythonParser = class {
9379
9898
  * - Single, unified parser for .ts/.tsx/.js/.jsx (+ mjs/cjs/mts/cts)
9380
9899
  * - Direct boundary extraction aligned with canonical ruleset
9381
9900
  * - Minimal, predictable logic (no complex multi-phase traversals)
9382
- * - Retain legacy extractStructuralNodes() for existing tests
9383
9901
  *
9384
9902
  * This replaces the previous inheritance-heavy BaseLanguageParser design.
9385
9903
  */
@@ -9414,20 +9932,6 @@ var CONTENT_DECL_TYPES = /* @__PURE__ */ new Set([
9414
9932
  "variable_declarator"
9415
9933
  ]);
9416
9934
  /**
9417
- * Tokens considered modifiers (merged into name for static methods if needed).
9418
- */
9419
- var MODIFIER_TOKENS = /* @__PURE__ */ new Set([
9420
- "export",
9421
- "default",
9422
- "public",
9423
- "private",
9424
- "protected",
9425
- "readonly",
9426
- "abstract",
9427
- "async",
9428
- "static"
9429
- ]);
9430
- /**
9431
9935
  * Decide if node type is boundary-worthy (before suppression rules).
9432
9936
  */
9433
9937
  function isCandidateBoundary(node) {
@@ -9556,31 +10060,6 @@ function extractName(node) {
9556
10060
  }
9557
10061
  }
9558
10062
  /**
9559
- * Modifier extraction (scan children + backward tokens).
9560
- */
9561
- function extractModifiers(node) {
9562
- const mods = /* @__PURE__ */ new Set();
9563
- for (const c of node.children) if (MODIFIER_TOKENS.has(c.type)) mods.add(c.type);
9564
- let prev = node.previousSibling;
9565
- while (prev) {
9566
- if (prev.type === "comment") {
9567
- prev = prev.previousSibling;
9568
- continue;
9569
- }
9570
- if (/^\s*$/.test(prev.text)) {
9571
- prev = prev.previousSibling;
9572
- continue;
9573
- }
9574
- if (MODIFIER_TOKENS.has(prev.type)) {
9575
- mods.add(prev.type);
9576
- prev = prev.previousSibling;
9577
- continue;
9578
- }
9579
- break;
9580
- }
9581
- return Array.from(mods);
9582
- }
9583
- /**
9584
10063
  * Boundary classification mapping.
9585
10064
  */
9586
10065
  function classifyBoundaryKind(node) {
@@ -9680,55 +10159,6 @@ var TypeScriptParser = class {
9680
10159
  if (node.hasError && node.type === "ERROR") acc.push(node);
9681
10160
  for (const c of node.children) this.collectErrorNodes(c, acc);
9682
10161
  }
9683
- getNodeText(node, source) {
9684
- return source.slice(node.startIndex, node.endIndex);
9685
- }
9686
- getNodeLines(node, _source) {
9687
- return {
9688
- startLine: node.startPosition.row + 1,
9689
- endLine: node.endPosition.row + 1
9690
- };
9691
- }
9692
- /**
9693
- * Legacy structural node extraction (used by existing tests).
9694
- * Produces a flat list (no parent/child linking beyond simple push).
9695
- */
9696
- extractStructuralNodes(tree, source) {
9697
- const src = source ?? tree.rootNode.text;
9698
- const out = [];
9699
- const structuralTypes = /* @__PURE__ */ new Set([...STRUCTURAL_DECL_TYPES, ...CONTENT_DECL_TYPES]);
9700
- const visit = (node) => {
9701
- if (structuralTypes.has(node.type)) {
9702
- if (this.shouldSkipStructuralNode(node)) {
9703
- for (const child of node.children) visit(child);
9704
- return;
9705
- }
9706
- const name = extractName(node);
9707
- const modifiers = extractModifiers(node);
9708
- const { startLine, startByte } = findDocumentationStart(node, src);
9709
- const endLine = node.endPosition.row + 1;
9710
- const structuralNode = {
9711
- type: this.classifyStructuralNode(node),
9712
- name,
9713
- startLine,
9714
- endLine,
9715
- startByte,
9716
- endByte: node.endIndex,
9717
- children: [],
9718
- text: this.getNodeText(node, src),
9719
- indentLevel: 0,
9720
- modifiers,
9721
- documentation: void 0
9722
- };
9723
- out.push(structuralNode);
9724
- for (const child of node.children) visit(child);
9725
- return;
9726
- }
9727
- for (const child of node.children) visit(child);
9728
- };
9729
- visit(tree.rootNode);
9730
- return this.deduplicate(out);
9731
- }
9732
10162
  /**
9733
10163
  * Boundary extraction: produces CodeBoundary[] directly from AST.
9734
10164
  */
@@ -9806,45 +10236,8 @@ var TypeScriptParser = class {
9806
10236
  }
9807
10237
  return false;
9808
10238
  }
9809
- classifyStructuralNode(node) {
9810
- switch (node.type) {
9811
- case "function_declaration": return StructuralNodeType.FUNCTION_DECLARATION;
9812
- case "arrow_function": return StructuralNodeType.ARROW_FUNCTION;
9813
- case "method_definition":
9814
- case "method_signature":
9815
- case "abstract_method_signature": return StructuralNodeType.METHOD_DEFINITION;
9816
- case "constructor": return StructuralNodeType.CONSTRUCTOR;
9817
- case "class_declaration":
9818
- case "abstract_class_declaration": return StructuralNodeType.CLASS_DECLARATION;
9819
- case "interface_declaration": return StructuralNodeType.INTERFACE_DECLARATION;
9820
- case "type_alias_declaration": return StructuralNodeType.TYPE_ALIAS_DECLARATION;
9821
- case "enum_declaration": return StructuralNodeType.ENUM_DECLARATION;
9822
- case "namespace_declaration":
9823
- case "module_declaration":
9824
- case "internal_module": return StructuralNodeType.NAMESPACE_DECLARATION;
9825
- case "import_statement": return StructuralNodeType.IMPORT_STATEMENT;
9826
- case "export_statement": return StructuralNodeType.EXPORT_STATEMENT;
9827
- case "variable_declaration":
9828
- case "lexical_declaration":
9829
- case "variable_declarator": return StructuralNodeType.VARIABLE_DECLARATION;
9830
- default: return StructuralNodeType.VARIABLE_DECLARATION;
9831
- }
9832
- }
9833
- deduplicate(nodes) {
9834
- const seen = /* @__PURE__ */ new Set();
9835
- const out = [];
9836
- for (const n of nodes) {
9837
- const key = `${n.startByte}:${n.endByte}:${n.type}:${n.name}`;
9838
- if (seen.has(key)) continue;
9839
- seen.add(key);
9840
- out.push(n);
9841
- }
9842
- out.sort((a, b) => a.startByte - b.startByte);
9843
- return out;
9844
- }
9845
10239
  };
9846
- //#endregion
9847
- //#region src/splitter/treesitter/LanguageParserRegistry.ts
10240
+ // src/splitter/treesitter/LanguageParserRegistry.ts
9848
10241
  /**
9849
10242
  * LanguageParserRegistry - Registry for tree-sitter language parsers
9850
10243
  *
@@ -9881,42 +10274,6 @@ var LanguageParserRegistry = class {
9881
10274
  return language ? this.parsers.get(language) : void 0;
9882
10275
  }
9883
10276
  /**
9884
- * Check if a language is supported
9885
- */
9886
- isLanguageSupported(language) {
9887
- return this.parsers.has(language);
9888
- }
9889
- /**
9890
- * Check if a file extension is supported
9891
- */
9892
- isExtensionSupported(extension) {
9893
- return this.extensionMap.has(extension.toLowerCase());
9894
- }
9895
- /**
9896
- * Check if a MIME type is supported
9897
- */
9898
- isMimeTypeSupported(mimeType) {
9899
- return this.mimeTypeMap.has(mimeType.toLowerCase());
9900
- }
9901
- /**
9902
- * Get all supported languages
9903
- */
9904
- getSupportedLanguages() {
9905
- return Array.from(this.parsers.keys());
9906
- }
9907
- /**
9908
- * Get all supported file extensions
9909
- */
9910
- getSupportedExtensions() {
9911
- return Array.from(this.extensionMap.keys());
9912
- }
9913
- /**
9914
- * Get all supported MIME types
9915
- */
9916
- getSupportedMimeTypes() {
9917
- return Array.from(this.mimeTypeMap.keys());
9918
- }
9919
- /**
9920
10277
  * Register a new parser
9921
10278
  */
9922
10279
  registerParser(parser) {
@@ -9928,48 +10285,11 @@ var LanguageParserRegistry = class {
9928
10285
  const limit = this.treeSitterSizeLimit;
9929
10286
  const unified = new TypeScriptParser(limit);
9930
10287
  this.registerParser(unified);
9931
- const jsAlias = {
9932
- ...unified,
9933
- name: "javascript",
9934
- parse: unified.parse.bind(unified),
9935
- extractStructuralNodes: unified.extractStructuralNodes.bind(unified),
9936
- getNodeText: unified.getNodeText.bind(unified),
9937
- getNodeLines: unified.getNodeLines.bind(unified),
9938
- extractBoundaries: unified.extractBoundaries.bind(unified),
9939
- fileExtensions: [
9940
- ".js",
9941
- ".jsx",
9942
- ".mjs",
9943
- ".cjs"
9944
- ],
9945
- mimeTypes: [
9946
- "text/x-jsx",
9947
- "text/javascript",
9948
- "application/javascript",
9949
- "text/jsx",
9950
- "application/jsx"
9951
- ]
9952
- };
9953
- this.parsers.set("javascript", jsAlias);
9954
- for (const ext of [
9955
- ".js",
9956
- ".jsx",
9957
- ".mjs",
9958
- ".cjs"
9959
- ]) this.extensionMap.set(ext.toLowerCase(), "javascript");
9960
- for (const mt of [
9961
- "text/x-jsx",
9962
- "text/javascript",
9963
- "application/javascript",
9964
- "text/jsx",
9965
- "application/jsx"
9966
- ]) this.mimeTypeMap.set(mt.toLowerCase(), "javascript");
9967
10288
  const pythonParser = new PythonParser(limit);
9968
10289
  this.registerParser(pythonParser);
9969
10290
  }
9970
10291
  };
9971
- //#endregion
9972
- //#region src/splitter/treesitter/TreesitterSourceCodeSplitter.ts
10292
+ // src/splitter/treesitter/TreesitterSourceCodeSplitter.ts
9973
10293
  /**
9974
10294
  * Tree-sitter based source code splitter that provides semantic parsing
9975
10295
  * while maintaining compatibility with existing chunk patterns
@@ -10023,30 +10343,6 @@ var TreesitterSourceCodeSplitter = class {
10023
10343
  if (contentType.includes("jsx") || contentType.includes("tsx")) return this.registry.getParser("typescript");
10024
10344
  }
10025
10345
  /**
10026
- * Check if the content type is supported
10027
- */
10028
- isSupportedContentType(contentType) {
10029
- return this.getParserForContent(contentType) !== void 0;
10030
- }
10031
- /**
10032
- * Get the list of supported languages
10033
- */
10034
- getSupportedLanguages() {
10035
- return this.registry.getSupportedLanguages();
10036
- }
10037
- /**
10038
- * Get the list of supported file extensions
10039
- */
10040
- getSupportedExtensions() {
10041
- return this.registry.getSupportedExtensions();
10042
- }
10043
- /**
10044
- * Get the list of supported MIME types
10045
- */
10046
- getSupportedMimeTypes() {
10047
- return this.registry.getSupportedMimeTypes();
10048
- }
10049
- /**
10050
10346
  * Helper method to split content using TextContentSplitter only if needed
10051
10347
  * and create ContentChunks with the specified hierarchical path and level
10052
10348
  */
@@ -10126,8 +10422,10 @@ var TreesitterSourceCodeSplitter = class {
10126
10422
  level = 0;
10127
10423
  }
10128
10424
  let isStructural = boundary?.boundaryType === "structural";
10129
- if (isStructural && boundary) if (structuralBoundaryFirstChunk.has(boundary)) isStructural = false;
10130
- else structuralBoundaryFirstChunk.add(boundary);
10425
+ if (isStructural && boundary) {
10426
+ if (structuralBoundaryFirstChunk.has(boundary)) isStructural = false;
10427
+ else structuralBoundaryFirstChunk.add(boundary);
10428
+ }
10131
10429
  const segmentChunks = await this.splitContentIntoChunks(segment.content, path, level);
10132
10430
  for (const c of segmentChunks) {
10133
10431
  if (pendingWhitespace) {
@@ -10195,8 +10493,7 @@ var TreesitterSourceCodeSplitter = class {
10195
10493
  return innermost;
10196
10494
  }
10197
10495
  };
10198
- //#endregion
10199
- //#region src/scraper/pipelines/SourceCodePipeline.ts
10496
+ // src/scraper/pipelines/SourceCodePipeline.ts
10200
10497
  /**
10201
10498
  * Pipeline for processing source code content with semantic, structure-aware splitting.
10202
10499
  * Uses TreesitterSourceCodeSplitter for language-aware hierarchical chunking that preserves
@@ -10238,8 +10535,7 @@ var SourceCodePipeline = class extends BasePipeline {
10238
10535
  };
10239
10536
  }
10240
10537
  };
10241
- //#endregion
10242
- //#region src/scraper/pipelines/TextPipeline.ts
10538
+ // src/scraper/pipelines/TextPipeline.ts
10243
10539
  /**
10244
10540
  * TextPipeline - Processes plain text content with size optimization.
10245
10541
  */
@@ -10284,8 +10580,7 @@ var TextPipeline = class extends BasePipeline {
10284
10580
  };
10285
10581
  }
10286
10582
  };
10287
- //#endregion
10288
- //#region src/scraper/pipelines/PipelineFactory.ts
10583
+ // src/scraper/pipelines/PipelineFactory.ts
10289
10584
  /**
10290
10585
  * Factory class for creating content processing pipelines.
10291
10586
  * Provides standardized pipeline configurations used across different scraper strategies.
@@ -10313,8 +10608,7 @@ var PipelineFactory = class {
10313
10608
  ];
10314
10609
  }
10315
10610
  };
10316
- //#endregion
10317
- //#region src/scraper/strategies/GitHubRepoProcessor.ts
10611
+ // src/scraper/strategies/GitHubRepoProcessor.ts
10318
10612
  /**
10319
10613
  * GitHubRepoProcessor handles processing individual files from GitHub repositories.
10320
10614
  * It processes HTTPS blob URLs (https://github.com/owner/repo/blob/branch/filepath).
@@ -10418,8 +10712,7 @@ var GitHubRepoProcessor = class {
10418
10712
  await Promise.allSettled(this.pipelines.map((pipeline) => pipeline.close()));
10419
10713
  }
10420
10714
  };
10421
- //#endregion
10422
- //#region src/scraper/strategies/GitHubWikiProcessor.ts
10715
+ // src/scraper/strategies/GitHubWikiProcessor.ts
10423
10716
  /**
10424
10717
  * GitHubWikiProcessor handles scraping GitHub wiki pages using standard web scraping techniques.
10425
10718
  * GitHub wikis are separate from the main repository and are hosted at /wiki/ URLs.
@@ -10476,6 +10769,16 @@ var GitHubWikiProcessor = class {
10476
10769
  etag: item.etag,
10477
10770
  headers
10478
10771
  });
10772
+ const wikiInfo = this.parseGitHubWikiUrl(currentUrl);
10773
+ const wikiPath = `/${wikiInfo.owner}/${wikiInfo.repo}/wiki`;
10774
+ if (!new URL(rawContent.source, currentUrl).pathname.startsWith(wikiPath)) {
10775
+ logger.debug(`Wiki URL redirected out of the wiki: ${currentUrl}`);
10776
+ return {
10777
+ url: currentUrl,
10778
+ links: [],
10779
+ status: FetchStatus.NOT_FOUND
10780
+ };
10781
+ }
10479
10782
  if (rawContent.status !== FetchStatus.SUCCESS) return {
10480
10783
  url: currentUrl,
10481
10784
  links: [],
@@ -10501,8 +10804,6 @@ var GitHubWikiProcessor = class {
10501
10804
  }
10502
10805
  for (const err of processed.errors ?? []) logger.warn(`⚠️ Processing error for ${currentUrl}: ${err.message}`);
10503
10806
  const parsedUrl = new URL(currentUrl);
10504
- const wikiInfo = this.parseGitHubWikiUrl(currentUrl);
10505
- const pageTitle = parsedUrl.pathname.replace(`/${wikiInfo.owner}/${wikiInfo.repo}/wiki`, "").replace(/^\//, "") || "Home";
10506
10807
  const wikiLinks = (processed.links || []).filter((link) => {
10507
10808
  if (!link || link.trim() === "" || link === "invalid-url" || link === "not-a-url-at-all") return false;
10508
10809
  return true;
@@ -10515,14 +10816,14 @@ var GitHubWikiProcessor = class {
10515
10816
  }).filter((link) => link !== null).filter((link) => {
10516
10817
  try {
10517
10818
  const linkUrl = new URL(link);
10518
- return linkUrl.hostname === parsedUrl.hostname && linkUrl.pathname.startsWith(`/${wikiInfo.owner}/${wikiInfo.repo}/wiki`);
10819
+ return linkUrl.hostname === parsedUrl.hostname && linkUrl.pathname.startsWith(wikiPath);
10519
10820
  } catch {
10520
10821
  return false;
10521
10822
  }
10522
10823
  });
10523
10824
  return {
10524
10825
  url: currentUrl,
10525
- title: pageTitle,
10826
+ title: processed.title,
10526
10827
  etag: rawContent.etag,
10527
10828
  lastModified: rawContent.lastModified,
10528
10829
  contentType: rawContent.mimeType,
@@ -10546,8 +10847,7 @@ var GitHubWikiProcessor = class {
10546
10847
  await Promise.allSettled(this.pipelines.map((pipeline) => pipeline.close()));
10547
10848
  }
10548
10849
  };
10549
- //#endregion
10550
- //#region src/scraper/strategies/github-auth.ts
10850
+ // src/scraper/strategies/github-auth.ts
10551
10851
  var execAsync = promisify(exec);
10552
10852
  /**
10553
10853
  * Resolves GitHub authentication headers using a cascading fallback mechanism.
@@ -10594,8 +10894,7 @@ async function resolveGitHubAuth(explicitHeaders) {
10594
10894
  } catch {}
10595
10895
  return explicitHeaders ?? {};
10596
10896
  }
10597
- //#endregion
10598
- //#region src/scraper/strategies/GitHubScraperStrategy.ts
10897
+ // src/scraper/strategies/GitHubScraperStrategy.ts
10599
10898
  /** Text-based file extensions recognized for GitHub repository scraping. */
10600
10899
  var TEXT_EXTENSIONS = /* @__PURE__ */ new Set([
10601
10900
  ".md",
@@ -10818,19 +11117,6 @@ var GitHubScraperStrategy = class extends BaseScraperStrategy {
10818
11117
  this.wikiProcessor = new GitHubWikiProcessor(config);
10819
11118
  this.repoProcessor = new GitHubRepoProcessor(config);
10820
11119
  }
10821
- canHandle(url) {
10822
- if (url.startsWith("github-file://")) return true;
10823
- try {
10824
- const { hostname, pathname } = new URL(url);
10825
- if (!["github.com", "www.github.com"].includes(hostname)) return false;
10826
- if (pathname.match(/^\/([^/]+)\/([^/]+)\/?$/)) return true;
10827
- if (pathname.match(/^\/([^/]+)\/([^/]+)\/tree\//)) return true;
10828
- if (pathname.match(/^\/([^/]+)\/([^/]+)\/blob\//)) return true;
10829
- return false;
10830
- } catch {
10831
- return false;
10832
- }
10833
- }
10834
11120
  /**
10835
11121
  * Parses a GitHub URL to extract repository information.
10836
11122
  */
@@ -10990,6 +11276,21 @@ var GitHubScraperStrategy = class extends BaseScraperStrategy {
10990
11276
  if (statusCode === 401) throw new ScraperError(`GitHub authentication failed for "${owner}/${repo}". Your token is invalid or expired. Please check your GITHUB_TOKEN or GH_TOKEN environment variable.`, false, error);
10991
11277
  if (statusCode === 403) throw new ScraperError(`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.`, false, error);
10992
11278
  }
11279
+ /**
11280
+ * Measures scope from the repository root rather than the URL the scrape
11281
+ * started from.
11282
+ *
11283
+ * A `/tree/<branch>` URL names a branch, but the files discovered under it
11284
+ * live at `/blob/<branch>/...` and the wiki at `/wiki`, so measured from the
11285
+ * tree URL the default `subpages` scope rejects every one of them.
11286
+ *
11287
+ * @param options Scraper options naming the GitHub URL the scrape started from.
11288
+ * @returns The repository root URL.
11289
+ */
11290
+ getScopeBaseUrl(options) {
11291
+ const { owner, repo } = this.parseGitHubUrl(options.url);
11292
+ return new URL(`/${owner}/${repo}`, options.url);
11293
+ }
10993
11294
  async processItem(item, options, signal) {
10994
11295
  if (item.url.startsWith("github-file://")) {
10995
11296
  logger.info(`🗑️ Legacy github-file:// URL detected, marking as deleted: ${item.url}`);
@@ -11007,30 +11308,27 @@ var GitHubScraperStrategy = class extends BaseScraperStrategy {
11007
11308
  if (item.depth === 0) {
11008
11309
  const repoInfo = this.parseGitHubUrl(options.url);
11009
11310
  const { owner, repo } = repoInfo;
11311
+ if (repoInfo.isBlob && repoInfo.filePath) {
11312
+ logger.debug(`Single file URL detected: ${owner}/${repo}/${repoInfo.filePath} - indexing file only`);
11313
+ return await this.repoProcessor.process(item, options, headers, signal);
11314
+ }
11010
11315
  logger.debug(`Discovering GitHub repository ${owner}/${repo}`);
11011
11316
  const discoveredLinks = [];
11012
- if ("isBlob" in repoInfo && repoInfo.isBlob && repoInfo.filePath) {
11013
- const { branch = "main", filePath } = repoInfo;
11014
- logger.debug(`Single file URL detected: ${owner}/${repo}/${filePath} - indexing file only`);
11015
- discoveredLinks.push(`https://github.com/${owner}/${repo}/blob/${branch}/${filePath}`);
11016
- return {
11017
- url: item.url,
11018
- links: discoveredLinks,
11019
- status: FetchStatus.SUCCESS
11020
- };
11317
+ if (!repoInfo.subPath) {
11318
+ const wikiUrl = new URL(`/${owner}/${repo}/wiki`, options.url).href;
11319
+ discoveredLinks.push(wikiUrl);
11320
+ logger.debug(`Discovered wiki URL: ${wikiUrl}`);
11021
11321
  }
11022
- const wikiUrl = `${options.url.replace(/\/$/, "")}/wiki`;
11023
- discoveredLinks.push(wikiUrl);
11024
- logger.debug(`Discovered wiki URL: ${wikiUrl}`);
11025
11322
  const { tree, resolvedBranch } = await this.fetchRepositoryTree(repoInfo, headers, signal);
11026
11323
  const fileItems = tree.tree.filter((treeItem) => this.isWithinSubPath(treeItem.path, repoInfo.subPath)).filter((treeItem) => this.shouldProcessFile(treeItem, options));
11027
11324
  logger.debug(`Discovered ${fileItems.length} processable files in repository (branch: ${resolvedBranch})`);
11028
11325
  const fileUrls = fileItems.map((treeItem) => `https://github.com/${owner}/${repo}/blob/${resolvedBranch}/${treeItem.path}`);
11029
11326
  discoveredLinks.push(...fileUrls);
11030
- logger.debug(`Discovery complete: ${fileUrls.length} repo file(s) + 1 wiki URL = ${discoveredLinks.length} total URLs`);
11327
+ logger.debug(`Discovery complete: ${fileUrls.length} repo file(s), ${discoveredLinks.length} total URLs`);
11031
11328
  return {
11032
11329
  url: item.url,
11033
11330
  links: discoveredLinks,
11331
+ isContainer: true,
11034
11332
  status: FetchStatus.SUCCESS
11035
11333
  };
11036
11334
  }
@@ -11048,11 +11346,11 @@ var GitHubScraperStrategy = class extends BaseScraperStrategy {
11048
11346
  status: FetchStatus.SUCCESS
11049
11347
  };
11050
11348
  }
11051
- logger.debug(`No further processing for URL at depth ${item.depth}: ${item.url}`);
11349
+ logger.debug(`Not a GitHub file or wiki page at depth ${item.depth}: ${item.url}`);
11052
11350
  return {
11053
11351
  url: item.url,
11054
11352
  links: [],
11055
- status: FetchStatus.SUCCESS
11353
+ status: FetchStatus.NOT_FOUND
11056
11354
  };
11057
11355
  }
11058
11356
  async scrape(options, progressCallback, signal) {
@@ -11069,8 +11367,7 @@ var GitHubScraperStrategy = class extends BaseScraperStrategy {
11069
11367
  await Promise.all([this.wikiProcessor.cleanup(), this.repoProcessor.cleanup()]);
11070
11368
  }
11071
11369
  };
11072
- //#endregion
11073
- //#region src/utils/archive/TarAdapter.ts
11370
+ // src/utils/archive/TarAdapter.ts
11074
11371
  var TarAdapter = class {
11075
11372
  filePath;
11076
11373
  constructor(filePath) {
@@ -11143,8 +11440,7 @@ var TarAdapter = class {
11143
11440
  return Promise.resolve();
11144
11441
  }
11145
11442
  };
11146
- //#endregion
11147
- //#region src/utils/archive/ZipAdapter.ts
11443
+ // src/utils/archive/ZipAdapter.ts
11148
11444
  var ZipAdapter = class {
11149
11445
  zipfile = null;
11150
11446
  filePath;
@@ -11239,8 +11535,7 @@ var ZipAdapter = class {
11239
11535
  this.entriesCache = null;
11240
11536
  }
11241
11537
  };
11242
- //#endregion
11243
- //#region src/utils/archive/ArchiveFactory.ts
11538
+ // src/utils/archive/ArchiveFactory.ts
11244
11539
  /**
11245
11540
  * Returns an appropriate archive adapter for the given file path based on its
11246
11541
  * extension, or `null` if the file is not a recognized archive format.
@@ -11257,8 +11552,7 @@ async function getArchiveAdapter(filePath) {
11257
11552
  if (ext === ".tar" || ext === ".gz" || ext === ".tgz") return new TarAdapter(filePath);
11258
11553
  return null;
11259
11554
  }
11260
- //#endregion
11261
- //#region src/scraper/strategies/LocalFileStrategy.ts
11555
+ // src/scraper/strategies/LocalFileStrategy.ts
11262
11556
  /**
11263
11557
  * Orders two names by Unicode code point, which is the byte order of their
11264
11558
  * UTF-8 encoding, so the result is the same on every platform and locale.
@@ -11288,9 +11582,6 @@ var LocalFileStrategy = class extends BaseScraperStrategy {
11288
11582
  this.pipelines = PipelineFactory.createStandardPipelines(config);
11289
11583
  this.accessPolicy = new ScraperAccessPolicy(config.scraper.security);
11290
11584
  }
11291
- canHandle(url) {
11292
- return url.startsWith("file://");
11293
- }
11294
11585
  async processItem(item, options, _signal) {
11295
11586
  const filePath = (await this.accessPolicy.resolveFileAccess(item.url, options.internalAllowedFileRoots)).filePath;
11296
11587
  let stats = null;
@@ -11504,8 +11795,7 @@ var LocalFileStrategy = class extends BaseScraperStrategy {
11504
11795
  await Promise.allSettled(this.pipelines.map((pipeline) => pipeline.close()));
11505
11796
  }
11506
11797
  };
11507
- //#endregion
11508
- //#region src/scraper/pipelines/capability.ts
11798
+ // src/scraper/pipelines/capability.ts
11509
11799
  /**
11510
11800
  * Builds the single predicate used to decide whether content is worth fetching.
11511
11801
  *
@@ -11525,8 +11815,7 @@ var LocalFileStrategy = class extends BaseScraperStrategy {
11525
11815
  function createMimeTypeCapabilityPredicate(pipelines) {
11526
11816
  return (mimeType) => pipelines.some((pipeline) => pipeline.canProcess(mimeType));
11527
11817
  }
11528
- //#endregion
11529
- //#region src/scraper/strategies/WebScraperStrategy.ts
11818
+ // src/scraper/strategies/WebScraperStrategy.ts
11530
11819
  /**
11531
11820
  * Web scraper strategy that normalizes URLs, fetches content with automatic
11532
11821
  * fetcher selection, and routes content through pipelines. Requires resolved
@@ -11565,14 +11854,6 @@ var WebScraperStrategy = class extends BaseScraperStrategy {
11565
11854
  this.canProcessMimeType = createMimeTypeCapabilityPredicate(this.pipelines);
11566
11855
  this.localFileStrategy = new LocalFileStrategy(config);
11567
11856
  }
11568
- canHandle(url) {
11569
- try {
11570
- const parsedUrl = new URL(url);
11571
- return parsedUrl.protocol === "http:" || parsedUrl.protocol === "https:";
11572
- } catch {
11573
- return false;
11574
- }
11575
- }
11576
11857
  restorePreservedHash(requestedUrl, actualUrl) {
11577
11858
  if (!requestedUrl.includes("#")) return actualUrl;
11578
11859
  try {
@@ -11975,18 +12256,9 @@ var WebScraperStrategy = class extends BaseScraperStrategy {
11975
12256
  ]);
11976
12257
  }
11977
12258
  };
11978
- //#endregion
11979
- //#region src/scraper/strategies/NpmScraperStrategy.ts
12259
+ // src/scraper/strategies/NpmScraperStrategy.ts
11980
12260
  var NpmScraperStrategy = class {
11981
12261
  defaultStrategy;
11982
- canHandle(url) {
11983
- const { hostname } = new URL(url);
11984
- return [
11985
- "npmjs.org",
11986
- "npmjs.com",
11987
- "www.npmjs.com"
11988
- ].includes(hostname);
11989
- }
11990
12262
  constructor(config) {
11991
12263
  this.defaultStrategy = new WebScraperStrategy(config, { urlNormalizerOptions: {
11992
12264
  removeHash: true,
@@ -12004,14 +12276,9 @@ var NpmScraperStrategy = class {
12004
12276
  await this.defaultStrategy.cleanup();
12005
12277
  }
12006
12278
  };
12007
- //#endregion
12008
- //#region src/scraper/strategies/PyPiScraperStrategy.ts
12279
+ // src/scraper/strategies/PyPiScraperStrategy.ts
12009
12280
  var PyPiScraperStrategy = class {
12010
12281
  defaultStrategy;
12011
- canHandle(url) {
12012
- const { hostname } = new URL(url);
12013
- return ["pypi.org", "www.pypi.org"].includes(hostname);
12014
- }
12015
12282
  constructor(config) {
12016
12283
  this.defaultStrategy = new WebScraperStrategy(config, { urlNormalizerOptions: {
12017
12284
  removeHash: true,
@@ -12029,8 +12296,7 @@ var PyPiScraperStrategy = class {
12029
12296
  await this.defaultStrategy.cleanup();
12030
12297
  }
12031
12298
  };
12032
- //#endregion
12033
- //#region src/scraper/ScraperRegistry.ts
12299
+ // src/scraper/ScraperRegistry.ts
12034
12300
  /**
12035
12301
  * Factory for creating scraper strategy instances.
12036
12302
  * Each call to getStrategy() returns a fresh instance to ensure
@@ -12114,8 +12380,7 @@ function isWebUrl(url) {
12114
12380
  return false;
12115
12381
  }
12116
12382
  }
12117
- //#endregion
12118
- //#region src/scraper/ScraperService.ts
12383
+ // src/scraper/ScraperService.ts
12119
12384
  /**
12120
12385
  * Orchestrates document scraping operations using registered scraping strategies.
12121
12386
  * Automatically selects appropriate strategy based on URL patterns.
@@ -12151,8 +12416,7 @@ var ScraperService = class {
12151
12416
  if (cleanupErrorToThrow) throw cleanupErrorToThrow;
12152
12417
  }
12153
12418
  };
12154
- //#endregion
12155
- //#region src/pipeline/PipelineWorker.ts
12419
+ // src/pipeline/PipelineWorker.ts
12156
12420
  /**
12157
12421
  * Executes a single document processing job.
12158
12422
  * Handles scraping, storing documents, and reporting progress/errors via callbacks.
@@ -12219,7 +12483,10 @@ var PipelineWorker = class {
12219
12483
  */
12220
12484
  async recordEmptyPage(job, callbacks, library, version, progress) {
12221
12485
  const { emptyPage } = progress;
12222
- if (!emptyPage) return;
12486
+ if (!emptyPage) {
12487
+ await this.removeDeletedPage(job, callbacks, progress);
12488
+ return;
12489
+ }
12223
12490
  if (emptyPage.pipelineFailed) {
12224
12491
  logger.debug(`[${job.id}] Extraction failed with no content, leaving stored page untouched: ${progress.currentUrl}`);
12225
12492
  return;
@@ -12270,11 +12537,11 @@ var PipelineWorker = class {
12270
12537
  } catch (docError) {
12271
12538
  logger.error(`❌ [${job.id}] Failed to process content ${progress.currentUrl}: ${docError}`);
12272
12539
  await callbacks.onJobError?.(job, docError instanceof Error ? docError : new Error(String(docError)), progress.result);
12540
+ if (docError instanceof EmbeddingError) throw docError;
12273
12541
  }
12274
12542
  }
12275
12543
  };
12276
- //#endregion
12277
- //#region src/pipeline/PipelineManager.ts
12544
+ // src/pipeline/PipelineManager.ts
12278
12545
  /**
12279
12546
  * PipelineManager orchestrates a queue of scraping/indexing jobs.
12280
12547
  * - Controls concurrency, recovery, and job lifecycle
@@ -12751,9 +13018,7 @@ var PipelineManager = class {
12751
13018
  case PipelineJobStatus.CANCELLED:
12752
13019
  logger.warn(`⚠️ Job ${jobId} cannot be cancelled in its current state: ${job.status}`);
12753
13020
  break;
12754
- default:
12755
- logger.error(`❌ Unhandled job status for cancellation: ${job.status}`);
12756
- break;
13021
+ default: logger.error(`❌ Unhandled job status for cancellation: ${job.status}`);
12757
13022
  }
12758
13023
  }
12759
13024
  /**
@@ -12913,8 +13178,7 @@ var PipelineManager = class {
12913
13178
  logger.debug(`Job ${job.id} progress: ${progress.pagesScraped}/${progress.totalPages} processed, ${progress.pagesIndexed} indexed`);
12914
13179
  }
12915
13180
  };
12916
- //#endregion
12917
- //#region src/store/DocumentManagementClient.ts
13181
+ // src/store/DocumentManagementClient.ts
12918
13182
  /**
12919
13183
  * How long the health report waits for the worker's embedding config before the
12920
13184
  * last known value stands in; a worker that drops traffic would otherwise hold
@@ -13058,8 +13322,7 @@ var DocumentManagementClient = class {
13058
13322
  });
13059
13323
  }
13060
13324
  };
13061
- //#endregion
13062
- //#region src/utils/version.ts
13325
+ // src/utils/version.ts
13063
13326
  /**
13064
13327
  * Version label classification and comparison utilities.
13065
13328
  *
@@ -13180,14 +13443,37 @@ function compareVersionsDescending(a, b) {
13180
13443
  function sortVersionsDescending(versions) {
13181
13444
  return [...versions].sort(compareVersionsDescending);
13182
13445
  }
13183
- //#endregion
13184
- //#region src/store/assembly/strategies/HierarchicalAssemblyStrategy.ts
13446
+ // src/store/assembly/strategies/HierarchicalAssemblyStrategy.ts
13447
+ /** Returns a chunk's path, or the root path when it has none. */
13448
+ function pathOf(chunk) {
13449
+ return chunk.metadata.path ?? [];
13450
+ }
13451
+ /** Returns whether `path` begins with every segment of `prefix`. */
13452
+ function startsWithPath(path, prefix) {
13453
+ return path.length >= prefix.length && prefix.every((segment, index) => segment === path[index]);
13454
+ }
13455
+ /** Returns whether two paths have the same segments. */
13456
+ function isSamePath(a, b) {
13457
+ return a.length === b.length && startsWithPath(a, b);
13458
+ }
13459
+ /** Returns the longest path that every given path starts with. */
13460
+ function commonPrefix(paths) {
13461
+ const [first = [], ...rest] = paths;
13462
+ let length = 0;
13463
+ while (length < first.length && rest.every((path) => path[length] === first[length])) length++;
13464
+ return first.slice(0, length);
13465
+ }
13466
+ /** Returns whether a chunk opens a declaration such as a class or namespace. */
13467
+ function isStructural(chunk) {
13468
+ return chunk.metadata.types?.includes("structural") ?? false;
13469
+ }
13185
13470
  /**
13186
13471
  * Assembly strategy for structured content (source code, JSON, config files).
13187
13472
  *
13188
- * Uses selective subtree reassembly: for single matches, walks up the complete parent
13189
- * hierarchy to the root. For multiple matches within the same document, finds the common
13190
- * ancestor and reconstructs only the relevant subtrees, avoiding inclusion of excessive
13473
+ * Uses selective subtree reassembly: a single match brings the structure that contains
13474
+ * it, such as its class or JSON object, with the opening and closing chunks of the scopes
13475
+ * around it. Multiple matches within the same document bring only their own subtrees,
13476
+ * inside the opening and closing chunks of their scopes, avoiding inclusion of excessive
13191
13477
  * unrelated content. Simple concatenation leverages splitter concatenation guarantees.
13192
13478
  */
13193
13479
  var HierarchicalAssemblyStrategy = class {
@@ -13206,9 +13492,9 @@ var HierarchicalAssemblyStrategy = class {
13206
13492
  return false;
13207
13493
  }
13208
13494
  /**
13209
- * Selects chunks using selective subtree reassembly for multiple matches within documents.
13210
- * For single matches: uses existing parent chain logic.
13211
- * For multiple matches in same document: finds common ancestor and reconstructs minimal subtree.
13495
+ * Selects the chunks to reassemble around the matches of each document.
13496
+ * For a single match: the subtree of its container plus the boundaries of the enclosing scopes.
13497
+ * For multiple matches in same document: each match's subtree plus the boundaries of its scopes.
13212
13498
  */
13213
13499
  async selectChunks(library, version, initialChunks, documentStore) {
13214
13500
  if (initialChunks.length === 0) return [];
@@ -13220,36 +13506,19 @@ var HierarchicalAssemblyStrategy = class {
13220
13506
  chunksByDocument.get(url)?.push(chunk);
13221
13507
  }
13222
13508
  const allChunkIds = /* @__PURE__ */ new Set();
13223
- for (const [_url, documentChunks] of Array.from(chunksByDocument.entries())) if (documentChunks.length === 1) {
13224
- const matched = documentChunks[0];
13225
- let promotedAncestor = await this.findStructuralAncestor(library, version, matched, documentStore) ?? matched;
13226
- try {
13227
- const path = matched.metadata.path || [];
13228
- if (promotedAncestor === matched && path.length > 0) {
13229
- const topLevelPath = [path[0]];
13230
- const containerIds = await this.findContainerChunks(library, version, matched, topLevelPath, documentStore);
13231
- if (containerIds.length > 0) {
13232
- const topChunks = await documentStore.findChunksByIds(library, version, [containerIds[0]]);
13233
- if (topChunks.length > 0) promotedAncestor = topChunks[0];
13234
- }
13235
- }
13236
- } catch (e) {
13237
- logger.warn(`Top-level function promotion failed for chunk ${matched.id}: ${e}`);
13238
- }
13239
- allChunkIds.add(matched.id);
13240
- const ancestorParentChain = await this.walkToRoot(library, version, promotedAncestor, documentStore);
13241
- for (const id of ancestorParentChain) allChunkIds.add(id);
13242
- const subtreeIds = await this.findSubtreeChunks(library, version, promotedAncestor, documentStore);
13243
- for (const id of subtreeIds) allChunkIds.add(id);
13244
- } else {
13509
+ for (const [url, documentChunks] of Array.from(chunksByDocument.entries())) {
13245
13510
  for (const matched of documentChunks) allChunkIds.add(matched.id);
13246
- const subtreeIds = await this.selectSubtreeChunks(library, version, documentChunks, documentStore);
13247
- for (const id of subtreeIds) allChunkIds.add(id);
13511
+ const pageChunks = await documentStore.findChunksByUrl(library, version, url);
13512
+ const matchedIds = new Set(documentChunks.map((matched) => matched.id));
13513
+ const matchIndices = pageChunks.flatMap((chunk, index) => matchedIds.has(chunk.id) ? [index] : []);
13514
+ if (matchIndices.length === 0) continue;
13515
+ const selected = documentChunks.length === 1 ? this.selectAroundMatch(pageChunks, matchIndices[0], MimeTypeUtils.isJson(documentChunks[0].content_type ?? "")) : this.selectAroundMatches(pageChunks, matchIndices);
13516
+ for (const chunk of selected) allChunkIds.add(chunk.id);
13248
13517
  }
13249
13518
  const chunkIds = Array.from(allChunkIds);
13250
13519
  return await documentStore.findChunksByIds(library, version, chunkIds);
13251
13520
  } catch (error) {
13252
- logger.warn(`Hierarchical parent chain walking failed, falling back to basic selection: ${error}`);
13521
+ logger.warn(`Hierarchical chunk selection failed, falling back to basic selection: ${error}`);
13253
13522
  return this.fallbackSelection(library, version, initialChunks, documentStore);
13254
13523
  }
13255
13524
  }
@@ -13257,189 +13526,201 @@ var HierarchicalAssemblyStrategy = class {
13257
13526
  * Assembles chunks using simple concatenation.
13258
13527
  * Relies on splitter concatenation guarantees - chunks are designed to join seamlessly.
13259
13528
  */
13260
- assembleContent(chunks, debug = false) {
13261
- if (debug) return chunks.map((chunk) => `=== #${chunk.id} ${chunk.metadata.path?.join("/")} [${chunk.metadata.level}] ===\n` + chunk.content).join("");
13529
+ assembleContent(chunks) {
13262
13530
  return chunks.map((chunk) => chunk.content).join("");
13263
13531
  }
13264
13532
  /**
13265
- * Walks up the parent hierarchy from a chunk to collect the complete parent chain.
13266
- * Includes the chunk itself and every parent until reaching the root.
13267
- * Protected against circular references and infinite loops.
13533
+ * Selects the chunks around a single match: the subtree of its container (for code
13534
+ * its structural ancestor, such as its class; for JSON the object or array holding
13535
+ * it) and the opening and closing chunks of the scopes that enclose that container.
13268
13536
  *
13269
- * Handles hierarchical gaps by attempting to find ancestors at progressively shorter
13270
- * path lengths when direct parent lookup fails (e.g., when intermediate chunks
13271
- * have been merged or are missing).
13272
- */
13273
- async walkToRoot(library, version, chunk, documentStore) {
13274
- const chainIds = [];
13275
- const visited = /* @__PURE__ */ new Set();
13276
- let currentChunk = chunk;
13277
- const { maxParentChainDepth } = this.config.assembly;
13278
- let depth = 0;
13279
- while (currentChunk && depth < maxParentChainDepth) {
13280
- const currentId = currentChunk.id;
13281
- if (visited.has(currentId)) {
13282
- logger.warn(`Circular reference detected in parent chain for chunk ${currentId}`);
13283
- break;
13284
- }
13285
- visited.add(currentId);
13286
- chainIds.push(currentId);
13287
- depth++;
13288
- let parentChunk = await documentStore.findParentChunk(library, version, currentId);
13289
- if (!parentChunk) parentChunk = await this.findAncestorWithGaps(library, version, currentChunk.url, currentChunk.metadata.path ?? [], documentStore);
13290
- currentChunk = parentChunk;
13291
- }
13292
- if (depth >= maxParentChainDepth) logger.warn(`Maximum parent chain depth (${maxParentChainDepth}) reached for chunk ${chunk.id}`);
13293
- return chainIds;
13294
- }
13295
- /**
13296
- * Attempts to find ancestors when there are gaps in the hierarchy.
13297
- * Tries progressively shorter path prefixes to find existing ancestor chunks.
13298
- */
13299
- async findAncestorWithGaps(library, version, url, path, documentStore) {
13300
- if (path.length <= 1) return null;
13301
- for (let pathLength = path.length - 1; pathLength > 0; pathLength--) {
13302
- const ancestorPath = path.slice(0, pathLength);
13303
- try {
13304
- const potentialAncestors = await this.findChunksByPathPrefix(library, version, url, ancestorPath, documentStore);
13305
- if (potentialAncestors.length > 0) return potentialAncestors[0];
13306
- } catch (error) {
13307
- logger.debug(`Failed to find ancestor with path ${ancestorPath.join("/")}: ${error}`);
13308
- }
13309
- }
13310
- return null;
13311
- }
13312
- /**
13313
- * Finds chunks that have an exact path match or are prefixes of the given path.
13314
- * This is a more flexible version of findChunksByPath that can handle gaps.
13537
+ * @param pageChunks All chunks of one page, in document order.
13538
+ * @param matchIndex Position of the match.
13539
+ * @param isJson Whether the page is JSON.
13315
13540
  */
13316
- async findChunksByPathPrefix(library, version, url, targetPath, documentStore) {
13317
- try {
13318
- const allChunks = await documentStore.findChunksByUrl(library, version, url);
13319
- if (allChunks.length === 0) return [];
13320
- return allChunks.filter((chunk) => {
13321
- const chunkPath = chunk.metadata.path || [];
13322
- if (chunk.url !== url) return false;
13323
- if (chunkPath.length !== targetPath.length) return false;
13324
- return chunkPath.every((part, index) => part === targetPath[index]);
13325
- });
13326
- } catch (error) {
13327
- logger.warn(`Error in findChunksByPathPrefix: ${error}`);
13328
- return [];
13329
- }
13541
+ selectAroundMatch(pageChunks, matchIndex, isJson) {
13542
+ const containerIndex = isJson ? this.findJsonContainer(pageChunks, matchIndex) : this.findCodeContainer(pageChunks, matchIndex);
13543
+ return this.selectSubtree(pageChunks, containerIndex);
13330
13544
  }
13331
13545
  /**
13332
- * Finds the nearest structural ancestor (types includes "structural") for a chunk.
13333
- * If none exists (e.g. the matched chunk itself is structural or at top), returns null.
13334
- */
13335
- async findStructuralAncestor(library, version, chunk, documentStore) {
13336
- let current = chunk;
13337
- const isStructural = (c) => !!c && Array.isArray(c.metadata?.types) && c.metadata.types.includes("structural");
13338
- if (isStructural(current)) return current;
13339
- while (true) {
13340
- const parent = await documentStore.findParentChunk(library, version, current.id);
13341
- if (!parent) return null;
13342
- if (isStructural(parent)) return parent;
13343
- current = parent;
13546
+ * Selects the chunks around several matches in one page: each match's subtree with
13547
+ * the opening and closing chunks of the scopes that enclose it, but none of their
13548
+ * other members. Within the scope that holds all matches, the chunks at that scope's
13549
+ * own path, such as fields or statements, are included as well.
13550
+ *
13551
+ * @param pageChunks All chunks of one page, in document order.
13552
+ * @param matchIndices Positions of the matches, in document order.
13553
+ */
13554
+ selectAroundMatches(pageChunks, matchIndices) {
13555
+ const selected = matchIndices.flatMap((index) => this.selectSubtree(pageChunks, index));
13556
+ const commonPath = commonPrefix(matchIndices.map((index) => pathOf(pageChunks[index])));
13557
+ const commonScope = commonPath.length > 0 ? this.findScopeStart(pageChunks, matchIndices[0], commonPath) : void 0;
13558
+ if (commonScope !== void 0) {
13559
+ const scope = this.containerRange(pageChunks, commonScope);
13560
+ for (const chunk of pageChunks.slice(scope.start, scope.end)) if (isSamePath(pathOf(chunk), commonPath)) selected.push(chunk);
13561
+ }
13562
+ return selected;
13563
+ }
13564
+ /**
13565
+ * Selects the subtree that the chunk at `index` opens, through its closing chunk, and
13566
+ * the opening and closing chunks of the scopes that enclose it. A chunk that opens
13567
+ * nothing, such as a field or statement that follows other members of its scope, comes
13568
+ * back on its own inside its scope's opening and closing chunks.
13569
+ */
13570
+ selectSubtree(pageChunks, index) {
13571
+ if (!this.opensContainer(pageChunks, index)) {
13572
+ const scopeStart = this.findScopeStart(pageChunks, index, pathOf(pageChunks[index]));
13573
+ const scope = scopeStart === void 0 ? [] : this.scopeBoundaries(pageChunks, this.containerRange(pageChunks, scopeStart));
13574
+ return [
13575
+ pageChunks[index],
13576
+ ...scope,
13577
+ ...this.findEnclosingScopeBoundaries(pageChunks, scopeStart ?? index)
13578
+ ];
13344
13579
  }
13580
+ const subtree = this.containerRange(pageChunks, index);
13581
+ return [...pageChunks.slice(subtree.start, subtree.end), ...this.findEnclosingScopeBoundaries(pageChunks, subtree.start)];
13345
13582
  }
13346
13583
  /**
13347
- * Selects chunks for selective subtree reassembly when multiple matches exist in the same document.
13348
- * Finds the common ancestor and reconstructs only the relevant subtrees.
13584
+ * Returns whether the chunk at `index` opens a container: no chunk nested deeper in its
13585
+ * path comes before it in the run of chunks inside that path. A field between two
13586
+ * methods carries its class's path but follows the first method, so it opens nothing.
13349
13587
  */
13350
- async selectSubtreeChunks(library, version, documentChunks, documentStore) {
13351
- const chunkIds = /* @__PURE__ */ new Set();
13352
- const commonAncestorPath = this.findCommonAncestorPath(documentChunks);
13353
- if (commonAncestorPath.length === 0) {
13354
- logger.warn("No common ancestor found for multiple matches, using individual parent chains");
13355
- for (const chunk of documentChunks) {
13356
- const parentChain = await this.walkToRoot(library, version, chunk, documentStore);
13357
- for (const id of parentChain) chunkIds.add(id);
13358
- }
13359
- return Array.from(chunkIds);
13588
+ opensContainer(pageChunks, index) {
13589
+ const path = pathOf(pageChunks[index]);
13590
+ if (path.length === 0) return true;
13591
+ for (let previous = index - 1; previous >= 0; previous--) {
13592
+ const previousPath = pathOf(pageChunks[previous]);
13593
+ if (!startsWithPath(previousPath, path)) return true;
13594
+ if (previousPath.length > path.length) return false;
13360
13595
  }
13361
- const containerIds = await this.findContainerChunks(library, version, documentChunks[0], commonAncestorPath, documentStore);
13362
- for (const id of containerIds) chunkIds.add(id);
13363
- for (const chunk of documentChunks) {
13364
- const subtreeIds = await this.findSubtreeChunks(library, version, chunk, documentStore);
13365
- for (const id of subtreeIds) chunkIds.add(id);
13366
- }
13367
- return Array.from(chunkIds);
13596
+ return true;
13368
13597
  }
13369
13598
  /**
13370
- * Finds the common ancestor path from a list of chunks by finding the longest common prefix.
13599
+ * Finds the code container to reconstruct for a single match: the innermost scope
13600
+ * around the match, the match's own included, whose opening chunk is structural (a
13601
+ * class, interface, enum or namespace). Without one, as for a match in a top-level
13602
+ * function, it is the top-level element named by the first path segment, otherwise
13603
+ * the match itself.
13604
+ *
13605
+ * @param pageChunks All chunks of one page, in document order.
13606
+ * @param matchIndex Position of the match.
13607
+ * @returns The position of the container's opening chunk.
13371
13608
  */
13372
- findCommonAncestorPath(chunks) {
13373
- if (chunks.length === 0) return [];
13374
- if (chunks.length === 1) return chunks[0].metadata.path ?? [];
13375
- const paths = chunks.map((chunk) => chunk.metadata.path ?? []);
13376
- if (paths.length === 0) return [];
13377
- const minLength = Math.min(...paths.map((path) => path.length));
13378
- const commonPrefix = [];
13379
- for (let i = 0; i < minLength; i++) {
13380
- const currentElement = paths[0][i];
13381
- if (paths.every((path) => path[i] === currentElement)) commonPrefix.push(currentElement);
13382
- else break;
13609
+ findCodeContainer(pageChunks, matchIndex) {
13610
+ const path = pathOf(pageChunks[matchIndex]);
13611
+ let topLevel;
13612
+ for (let length = path.length; length > 0; length--) {
13613
+ const start = this.findScopeStart(pageChunks, matchIndex, path.slice(0, length));
13614
+ if (start === void 0) continue;
13615
+ if (isStructural(pageChunks[start])) return start;
13616
+ if (length === 1) topLevel = start;
13383
13617
  }
13384
- return commonPrefix;
13618
+ return topLevel ?? matchIndex;
13385
13619
  }
13386
13620
  /**
13387
- * Finds the container chunks (opening/closing) for a given ancestor path.
13621
+ * Finds the JSON object or array to reconstruct for a single match: the one the match
13622
+ * opens, otherwise the one that contains it. Unlike code, a match is not promoted to
13623
+ * the top level, which in JSON is the whole document.
13624
+ *
13625
+ * The JSON splitter puts a key whose value is an object or array at the key's path,
13626
+ * followed by a chunk at the same path that begins with the opening bracket: the
13627
+ * bracket alone, or, past `splitter.json.maxNestingDepth`, the whole value serialized
13628
+ * as text. That chunk marks an object or array even when it is empty. A primitive
13629
+ * value never begins with a bracket.
13630
+ *
13631
+ * @param pageChunks All chunks of one page, in document order.
13632
+ * @param matchIndex Position of the match.
13633
+ * @returns The position of a chunk that opens the container.
13634
+ */
13635
+ findJsonContainer(pageChunks, matchIndex) {
13636
+ const path = pathOf(pageChunks[matchIndex]);
13637
+ const own = this.containerRange(pageChunks, matchIndex);
13638
+ if (pageChunks.slice(own.start, own.end).some((chunk) => isSamePath(pathOf(chunk), path) && /^[[{]/.test(chunk.content.trim())) || path.length <= 1) return matchIndex;
13639
+ return this.findScopeStart(pageChunks, own.start, path.slice(0, -1)) ?? matchIndex;
13640
+ }
13641
+ /**
13642
+ * Finds the chunks that open and close each scope enclosing a container, innermost
13643
+ * first and up to `assembly.maxParentChainDepth` scopes. A scope opens where the run
13644
+ * of chunks inside its path begins, so the members and statements between its
13645
+ * declaration and the container are left out. A scope with no chunk at its own path,
13646
+ * such as a level the splitter skipped, adds nothing.
13647
+ *
13648
+ * @param pageChunks All chunks of one page, in document order.
13649
+ * @param containerStart Position of the container's first chunk.
13650
+ * @returns The scopes' opening and closing chunks.
13388
13651
  */
13389
- async findContainerChunks(library, version, referenceChunk, ancestorPath, documentStore) {
13390
- const containerIds = [];
13391
- try {
13392
- const ancestorChunks = await this.findChunksByExactPath(library, version, referenceChunk.url, ancestorPath, documentStore);
13393
- for (const chunk of ancestorChunks) containerIds.push(chunk.id);
13394
- } catch (error) {
13395
- logger.warn(`Failed to find container chunks for path ${ancestorPath.join("/")}: ${error}`);
13652
+ findEnclosingScopeBoundaries(pageChunks, containerStart) {
13653
+ const path = pathOf(pageChunks[containerStart]);
13654
+ const { maxParentChainDepth } = this.config.assembly;
13655
+ const boundaries = [];
13656
+ let index = containerStart;
13657
+ for (let length = path.length - 1; length > 0 && path.length - length < maxParentChainDepth; length--) {
13658
+ const start = this.findScopeStart(pageChunks, index, path.slice(0, length));
13659
+ if (start === void 0) continue;
13660
+ index = start;
13661
+ boundaries.push(...this.scopeBoundaries(pageChunks, this.containerRange(pageChunks, start)));
13396
13662
  }
13397
- return containerIds;
13663
+ return boundaries;
13398
13664
  }
13399
13665
  /**
13400
- * Finds all chunks with an exact path match within a specific document.
13401
- * More efficient than searching across all chunks by first filtering by URL.
13666
+ * Finds where the scope with the given path opens, looking back from the chunk at
13667
+ * `index`: the first chunk of the run of chunks inside that path.
13668
+ *
13669
+ * @param pageChunks All chunks of one page, in document order.
13670
+ * @param index Position of a chunk inside the scope.
13671
+ * @param scopePath Path of the scope.
13672
+ * @returns The position of the scope's opening chunk, or undefined when the run does
13673
+ * not begin with a chunk at the scope's own path.
13402
13674
  */
13403
- async findChunksByExactPath(library, version, url, path, documentStore) {
13404
- try {
13405
- if (path.length === 0) {
13406
- logger.debug("Root path requested - no chunks found");
13407
- return [];
13408
- }
13409
- const allChunks = await documentStore.findChunksByUrl(library, version, url);
13410
- if (allChunks.length === 0) return [];
13411
- const matchingChunks = allChunks.filter((chunk) => {
13412
- const chunkPath = chunk.metadata.path ?? [];
13413
- if (chunkPath.length !== path.length) return false;
13414
- return chunkPath.every((part, index) => part === path[index]);
13415
- });
13416
- logger.debug(`Found ${matchingChunks.length} chunks for exact path: ${path.join("/")}`);
13417
- return matchingChunks;
13418
- } catch (error) {
13419
- logger.warn(`Error finding chunks for exact path ${path.join("/")}: ${error}`);
13420
- return [];
13421
- }
13675
+ findScopeStart(pageChunks, index, scopePath) {
13676
+ let start = index;
13677
+ while (start > 0 && startsWithPath(pathOf(pageChunks[start - 1]), scopePath)) start--;
13678
+ return isSamePath(pathOf(pageChunks[start]), scopePath) ? start : void 0;
13422
13679
  }
13423
13680
  /**
13424
- * Finds all chunks in the subtree rooted at the given chunk.
13425
- */
13426
- async findSubtreeChunks(library, version, rootChunk, documentStore) {
13427
- const subtreeIds = [];
13428
- const visited = /* @__PURE__ */ new Set();
13429
- const queue = [rootChunk];
13430
- while (queue.length > 0) {
13431
- const currentId = queue.shift().id;
13432
- if (visited.has(currentId)) continue;
13433
- visited.add(currentId);
13434
- subtreeIds.push(currentId);
13435
- try {
13436
- const children = await documentStore.findChildChunks(library, version, currentId, 1e3);
13437
- queue.push(...children);
13438
- } catch (error) {
13439
- logger.warn(`Failed to find children for chunk ${currentId}: ${error}`);
13440
- }
13441
- }
13442
- return subtreeIds;
13681
+ * Returns the chunks that open and close a scope: those at the scope's own path before
13682
+ * its first nested member (a class declaration, or a JSON key and its bracket) and
13683
+ * after its last one (a closing brace). A scope without nested members has none.
13684
+ *
13685
+ * @param pageChunks All chunks of one page, in document order.
13686
+ * @param scope Range of the scope, as found by `containerRange`.
13687
+ */
13688
+ scopeBoundaries(pageChunks, scope) {
13689
+ const depth = pathOf(pageChunks[scope.start]).length;
13690
+ const isOwn = (index) => pathOf(pageChunks[index]).length === depth;
13691
+ let firstNested = scope.start;
13692
+ while (firstNested < scope.end && isOwn(firstNested)) firstNested++;
13693
+ if (firstNested === scope.end) return [];
13694
+ let lastNested = scope.end - 1;
13695
+ while (isOwn(lastNested)) lastNested--;
13696
+ return [...pageChunks.slice(scope.start, firstNested), ...pageChunks.slice(lastNested + 1, scope.end)];
13697
+ }
13698
+ /**
13699
+ * Finds the container that the chunk at `index` belongs to. The container opens with
13700
+ * the chunk and the chunks right before it that carry the same path (such as a JSON
13701
+ * key and its bracket), and holds the chunks right after it whose path starts with
13702
+ * that path. The run ends at the first chunk outside the container, so it holds the
13703
+ * nested members and the closing chunk, which repeats the container's path, but no
13704
+ * unrelated code. A chunk with an empty path is global code and contains nothing else.
13705
+ *
13706
+ * @param pageChunks All chunks of one page, in document order.
13707
+ * @param index Position of a chunk that opens the container.
13708
+ * @returns The container's range in `pageChunks`.
13709
+ */
13710
+ containerRange(pageChunks, index) {
13711
+ const rootPath = pathOf(pageChunks[index]);
13712
+ if (rootPath.length === 0) return {
13713
+ start: index,
13714
+ end: index + 1
13715
+ };
13716
+ let start = index;
13717
+ while (start > 0 && isSamePath(pathOf(pageChunks[start - 1]), rootPath)) start--;
13718
+ let end = index + 1;
13719
+ while (end < pageChunks.length && startsWithPath(pathOf(pageChunks[end]), rootPath)) end++;
13720
+ return {
13721
+ start,
13722
+ end
13723
+ };
13443
13724
  }
13444
13725
  /**
13445
13726
  * Fallback selection method when parent chain walking fails.
@@ -13462,8 +13743,7 @@ var HierarchicalAssemblyStrategy = class {
13462
13743
  return await documentStore.findChunksByIds(library, version, Array.from(chunkIds));
13463
13744
  }
13464
13745
  };
13465
- //#endregion
13466
- //#region src/store/assembly/strategies/MarkdownAssemblyStrategy.ts
13746
+ // src/store/assembly/strategies/MarkdownAssemblyStrategy.ts
13467
13747
  /**
13468
13748
  * Assembly strategy that preserves the current behavior for markdown and text content.
13469
13749
  *
@@ -13525,8 +13805,7 @@ var MarkdownAssemblyStrategy = class {
13525
13805
  return relatedIds;
13526
13806
  }
13527
13807
  };
13528
- //#endregion
13529
- //#region src/store/assembly/ContentAssemblyStrategyFactory.ts
13808
+ // src/store/assembly/ContentAssemblyStrategyFactory.ts
13530
13809
  /**
13531
13810
  * Creates the appropriate assembly strategy based on content MIME type.
13532
13811
  *
@@ -13540,8 +13819,7 @@ function createContentAssemblyStrategy(mimeType, config) {
13540
13819
  for (const strategy of strategies) if (strategy.canHandle(mimeType)) return strategy;
13541
13820
  return new MarkdownAssemblyStrategy(config);
13542
13821
  }
13543
- //#endregion
13544
- //#region src/store/DocumentRetrieverService.ts
13822
+ // src/store/DocumentRetrieverService.ts
13545
13823
  var DocumentRetrieverService = class {
13546
13824
  documentStore;
13547
13825
  config;
@@ -13636,15 +13914,14 @@ var DocumentRetrieverService = class {
13636
13914
  return clusters;
13637
13915
  }
13638
13916
  };
13639
- //#endregion
13640
- //#region src/store/applyMigrations.ts
13917
+ // src/store/applyMigrations.ts
13641
13918
  var MIGRATIONS_DIR = path.join(getProjectRoot(), "db", "migrations");
13642
13919
  var MIGRATIONS_TABLE = "_schema_migrations";
13643
13920
  var MIGRATION_STEP_MARKER = /^\s*--\s*@migration-step\s+(.+?)\s*$/;
13644
13921
  var VECTOR_PARTITION_MIGRATION = "014-rebuild-vector-partition-keys.sql";
13645
13922
  var DEFAULT_VECTOR_DIMENSION = 1536;
13646
13923
  var VECTOR_DIMENSION_TOKEN = "__DOCUMENTS_VEC_DIMENSION__";
13647
- var WAL_SIZE_LIMIT_BYTES = 64 * 1024 * 1024;
13924
+ var WAL_SIZE_LIMIT_BYTES = 67108864;
13648
13925
  /**
13649
13926
  * Splits migration SQL into executable blocks using full-line migration markers.
13650
13927
  * SQL before the first marker is treated as an implicit prepare block, and SQL
@@ -13817,8 +14094,7 @@ async function applyMigrations(db, options) {
13817
14094
  logger.warn("⚠️ Could not apply all production database settings");
13818
14095
  }
13819
14096
  }
13820
- //#endregion
13821
- //#region src/store/DocumentStore.ts
14097
+ // src/store/DocumentStore.ts
13822
14098
  /**
13823
14099
  * How many full-text candidates are sorted by score alone before the
13824
14100
  * deterministic tie-break, as a multiple of the candidates kept. Sorting every
@@ -14073,8 +14349,12 @@ var DocumentStore = class {
14073
14349
  WHERE l.name = ?
14074
14350
  AND COALESCE(v.name, '') = COALESCE(?, '')
14075
14351
  AND p.url = ?
14352
+ -- A child's path is the parent's path plus one element. Compare the path
14353
+ -- without its last element as JSON instead of using LIKE, so ["AB","X"]
14354
+ -- is never a child of ["A"] and % or _ in a segment stay literal.
14355
+ -- The length check keeps an empty-path chunk from matching an empty parent.
14076
14356
  AND json_array_length(json_extract(d.metadata, '$.path')) = ?
14077
- AND json_extract(d.metadata, '$.path') LIKE ? || '%'
14357
+ AND json_remove(json_extract(d.metadata, '$.path'), '$[#-1]') = json(?)
14078
14358
  AND d.sort_order > (SELECT sort_order FROM documents WHERE id = ?)
14079
14359
  ORDER BY d.sort_order
14080
14360
  LIMIT ?
@@ -14197,7 +14477,10 @@ var DocumentStore = class {
14197
14477
  const currentDimension = String(this.dbDimension);
14198
14478
  const modelChanged = stored.model !== currentModel;
14199
14479
  const dimensionChanged = stored.dimension !== null && stored.dimension !== currentDimension;
14200
- if (modelChanged || dimensionChanged) throw new EmbeddingModelChangedError(stored.model, stored.dimension ?? "unknown", currentModel, currentDimension);
14480
+ if (modelChanged || dimensionChanged) {
14481
+ const currentDimensionKnown = !modelChanged || this.embeddingConfig.dimensions !== null || isVectorDimensionExplicit(this.config);
14482
+ throw new EmbeddingModelChangedError(stored.model, stored.dimension, currentModel, currentDimensionKnown ? currentDimension : null);
14483
+ }
14201
14484
  }
14202
14485
  /**
14203
14486
  * Invalidates all existing embedding vectors after a confirmed model/dimension change.
@@ -14947,7 +15230,7 @@ var DocumentStore = class {
14947
15230
  const modelSpec = this.embeddingConfig?.modelSpec ?? "unknown";
14948
15231
  const hints = [this.getEmbeddingErrorHint(error), this.embeddingConfig ? "Verify embedding provider configuration, model availability, credentials, quota, request size, and backend logs." : null].filter((hint) => hint !== null);
14949
15232
  const hintText = hints.length > 0 ? `\n ${hints.join("\n ")}` : "";
14950
- return new ConnectionError(`Failed to generate embeddings for ${context.url} using ${modelSpec}.\n Batch ${context.batchIndex}: ${context.batchTextCount} text(s), ${context.batchChars} chars, ${context.totalChunks} page chunk(s).\n Config: batchSize=${this.embeddingBatchSize}, batchChars=${this.embeddingBatchChars}, vectorDimension=${this.dbDimension}.` + hintText, error);
15233
+ return new EmbeddingError(`Failed to generate embeddings for ${context.url} using ${modelSpec}.\n Batch ${context.batchIndex}: ${context.batchTextCount} text(s), ${context.batchChars} chars, ${context.totalChunks} page chunk(s).\n Config: batchSize=${this.embeddingBatchSize}, batchChars=${this.embeddingBatchChars}, vectorDimension=${this.dbDimension}.` + hintText, error);
14951
15234
  }
14952
15235
  /**
14953
15236
  * Creates embeddings for an array of texts with automatic retry logic for size-related errors.
@@ -14967,24 +15250,26 @@ var DocumentStore = class {
14967
15250
  if (embeddings === null) throw new StoreError("Embeddings are not initialized");
14968
15251
  return await embeddings.embedDocuments(texts);
14969
15252
  } catch (error) {
14970
- if (this.isInputSizeError(error)) if (texts.length > 1) {
14971
- const midpoint = Math.floor(texts.length / 2);
14972
- const firstHalf = texts.slice(0, midpoint);
14973
- const secondHalf = texts.slice(midpoint);
14974
- if (!isRetry) logger.warn(`⚠️ Batch of ${texts.length} texts exceeded size limit, splitting into ${firstHalf.length} + ${secondHalf.length}`);
14975
- const [firstEmbeddings, secondEmbeddings] = await Promise.all([this.embedDocumentsWithRetry(firstHalf, true, false), this.embedDocumentsWithRetry(secondHalf, true, false)]);
14976
- return [...firstEmbeddings, ...secondEmbeddings];
14977
- } else {
14978
- if (hasTruncatedSingleText) throw error;
14979
- const text = texts[0];
14980
- const midpoint = Math.floor(text.length / 2);
14981
- const firstHalf = text.substring(0, midpoint);
14982
- if (!isRetry) logger.warn(`⚠️ Single text exceeded embedding size limit (${text.length} chars).`);
14983
- try {
14984
- return await this.embedDocumentsWithRetry([firstHalf], true, true);
14985
- } catch (retryError) {
14986
- logger.error(`❌ Failed to embed even after splitting. Original length: ${text.length}`);
14987
- throw retryError;
15253
+ if (this.isInputSizeError(error)) {
15254
+ if (texts.length > 1) {
15255
+ const midpoint = Math.floor(texts.length / 2);
15256
+ const firstHalf = texts.slice(0, midpoint);
15257
+ const secondHalf = texts.slice(midpoint);
15258
+ if (!isRetry) logger.warn(`⚠️ Batch of ${texts.length} texts exceeded size limit, splitting into ${firstHalf.length} + ${secondHalf.length}`);
15259
+ const [firstEmbeddings, secondEmbeddings] = await Promise.all([this.embedDocumentsWithRetry(firstHalf, true, false), this.embedDocumentsWithRetry(secondHalf, true, false)]);
15260
+ return [...firstEmbeddings, ...secondEmbeddings];
15261
+ } else {
15262
+ if (hasTruncatedSingleText) throw error;
15263
+ const text = texts[0];
15264
+ const midpoint = Math.floor(text.length / 2);
15265
+ const firstHalf = text.substring(0, midpoint);
15266
+ if (!isRetry) logger.warn(`⚠️ Single text exceeded embedding size limit (${text.length} chars).`);
15267
+ try {
15268
+ return await this.embedDocumentsWithRetry([firstHalf], true, true);
15269
+ } catch (retryError) {
15270
+ logger.error(`❌ Failed to embed even after splitting. Original length: ${text.length}`);
15271
+ throw retryError;
15272
+ }
14988
15273
  }
14989
15274
  }
14990
15275
  throw error;
@@ -15481,7 +15766,14 @@ var DocumentStore = class {
15481
15766
  }
15482
15767
  }
15483
15768
  /**
15484
- * Finds child chunks of a given document based on path hierarchy.
15769
+ * Finds the child chunks of a chunk: the chunks on the same page, after it in
15770
+ * document order, whose path extends its path by exactly one element.
15771
+ *
15772
+ * @param library Library name.
15773
+ * @param version Version label.
15774
+ * @param id ID of the parent chunk.
15775
+ * @param limit Maximum number of children to return.
15776
+ * @returns The children in document order, or an empty array if the parent does not exist.
15485
15777
  */
15486
15778
  async findChildChunks(library, version, id, limit) {
15487
15779
  try {
@@ -15776,8 +16068,7 @@ var DocumentStore = class {
15776
16068
  }
15777
16069
  }
15778
16070
  };
15779
- //#endregion
15780
- //#region src/store/DocumentManagementService.ts
16071
+ // src/store/DocumentManagementService.ts
15781
16072
  /** Upper bound on the pages listed when a path matches more than one. */
15782
16073
  var MAX_AMBIGUOUS_PAGE_MATCHES = 10;
15783
16074
  /**
@@ -16322,7 +16613,7 @@ var DocumentManagementService = class DocumentManagementService {
16322
16613
  * where to continue.
16323
16614
  *
16324
16615
  * @param library Library name.
16325
- * @param version Version or version range; resolved like `searchStore`.
16616
+ * @param version Version or version range, resolved like `findBestVersion`.
16326
16617
  * @param pathOrUrl Page URL or path.
16327
16618
  * @param options `startChunk` to continue reading, `maxChars` to bound the size.
16328
16619
  * @returns The assembled window and its position within the page.
@@ -16357,7 +16648,7 @@ var DocumentManagementService = class DocumentManagementService {
16357
16648
  * Lists the stored pages of a library version.
16358
16649
  *
16359
16650
  * @param library Library name.
16360
- * @param version Version or version range; resolved like `searchStore`.
16651
+ * @param version Version or version range, resolved like `findBestVersion`.
16361
16652
  * @param options `contains` filters URLs; `limit` (default 50) and `offset` paginate.
16362
16653
  * @returns One page of results and whether more follow.
16363
16654
  */
@@ -16496,8 +16787,7 @@ var DocumentManagementService = class DocumentManagementService {
16496
16787
  return this.store.getVersionComposition(normalized.library, normalized.version);
16497
16788
  }
16498
16789
  };
16499
- //#endregion
16500
- //#region src/services/apiClient.ts
16790
+ // src/services/apiClient.ts
16501
16791
  /**
16502
16792
  * Client for the merged application API (`AppRouter`) served at `/api`.
16503
16793
  *
@@ -16585,8 +16875,7 @@ async function pingApi(api, apiUrl) {
16585
16875
  throw new Error(`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').`);
16586
16876
  }
16587
16877
  }
16588
- //#endregion
16589
- //#region src/services/backend.ts
16878
+ // src/services/backend.ts
16590
16879
  async function openBackend(options) {
16591
16880
  const closer = new Closer();
16592
16881
  try {
@@ -16675,8 +16964,7 @@ var Closer = class {
16675
16964
  if (firstError !== void 0) throw firstError;
16676
16965
  }
16677
16966
  };
16678
- //#endregion
16679
- //#region src/cli/output.ts
16967
+ // src/cli/output.ts
16680
16968
  function isInteractiveOutput() {
16681
16969
  return !!process.stdout.isTTY && !!process.stderr.isTTY;
16682
16970
  }
@@ -16727,8 +17015,213 @@ function registerGlobalOutputOptions(yargs) {
16727
17015
  function reportCliError(message) {
16728
17016
  logger.error(message);
16729
17017
  }
16730
- //#endregion
16731
- //#region src/cli/commands/compact.ts
17018
+ // src/cli/utils.ts
17019
+ /**
17020
+ * Shared CLI utilities and helper functions.
17021
+ */
17022
+ /**
17023
+ * Retrieves the global EventBusService from the arguments context.
17024
+ * @param argv The parsed arguments context.
17025
+ * @returns The global EventBusService.
17026
+ * @throws Error if EventBusService is not initialized.
17027
+ */
17028
+ function getEventBus(argv) {
17029
+ const eventBus = argv._eventBus;
17030
+ if (!eventBus) throw new Error("EventBusService not initialized");
17031
+ return eventBus;
17032
+ }
17033
+ /**
17034
+ * Ensures a Chromium for scraping is installed, unless a system Chromium path
17035
+ * is set.
17036
+ *
17037
+ * Any Chromium `ManagedBrowser` launches without an explicit path counts: the
17038
+ * headless shell or the full build. When neither is there, the headless shell
17039
+ * is installed with the CLI of the Playwright this package depends on, so it
17040
+ * matches that version. The install leaves other browsers alone, since another
17041
+ * process may be running them.
17042
+ */
17043
+ function ensurePlaywrightBrowsersInstalled() {
17044
+ if (process.env.PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD === "1") {
17045
+ logger.debug("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD is set, skipping Playwright browser install.");
17046
+ return;
17047
+ }
17048
+ const chromiumEnvPath = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH;
17049
+ if (chromiumEnvPath && existsSync(chromiumEnvPath)) {
17050
+ logger.debug(`PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH is set to '${chromiumEnvPath}', skipping Playwright browser install.`);
17051
+ return;
17052
+ }
17053
+ if (ManagedBrowser.isPlaywrightChromiumInstalled()) return;
17054
+ const playwrightCli = path.join(path.dirname(createRequire(import.meta.url).resolve("playwright/package.json")), "cli.js");
17055
+ try {
17056
+ logger.info("🌐 Installing Playwright Chromium browser... (this may take a moment)");
17057
+ execFileSync(process.execPath, [
17058
+ playwrightCli,
17059
+ "install",
17060
+ "chromium-headless-shell",
17061
+ "--no-remove"
17062
+ ], { stdio: "ignore" });
17063
+ } catch (error) {
17064
+ logger.debug(String(error));
17065
+ logger.error(`❌ Failed to install Playwright browsers automatically. Please run:\n node "${playwrightCli}" install --with-deps chromium-headless-shell\nand try again.`);
17066
+ process.exit(1);
17067
+ }
17068
+ }
17069
+ /**
17070
+ * Resolves the protocol based on auto-detection or explicit specification.
17071
+ * Auto-detection uses TTY status to determine appropriate protocol.
17072
+ */
17073
+ function resolveProtocol(protocol) {
17074
+ if (protocol === "auto") {
17075
+ if (!process.stdin.isTTY && !process.stdout.isTTY) return "stdio";
17076
+ return "http";
17077
+ }
17078
+ if (protocol === "stdio" || protocol === "http") return protocol;
17079
+ throw new Error(`Invalid protocol: ${protocol}. Must be 'auto', 'stdio', or 'http'`);
17080
+ }
17081
+ /**
17082
+ * Validates and parses port number
17083
+ */
17084
+ function validatePort(portString) {
17085
+ const port = Number.parseInt(portString, 10);
17086
+ if (Number.isNaN(port) || port < 1 || port > 65535) throw new Error("Invalid port number");
17087
+ return port;
17088
+ }
17089
+ /**
17090
+ * Validates host string for basic format checking
17091
+ */
17092
+ function validateHost(hostString) {
17093
+ const trimmed = hostString.trim();
17094
+ if (!trimmed) throw new Error("Host cannot be empty");
17095
+ if (trimmed.includes(" ") || trimmed.includes(" ") || trimmed.includes("\n")) throw new Error("Host cannot contain whitespace");
17096
+ return trimmed;
17097
+ }
17098
+ /**
17099
+ * Creates AppServerConfig based on service requirements.
17100
+ *
17101
+ * AppConfig is the source of truth for host/auth/telemetry/read-only settings.
17102
+ * AppServerConfig only selects which services to run and which port to bind to.
17103
+ * Whether the server runs jobs itself or uses a worker follows from the backend.
17104
+ *
17105
+ * @param options Which services to run, the port, and startup details.
17106
+ * @returns The server configuration.
17107
+ */
17108
+ function createAppServerConfig(options) {
17109
+ return {
17110
+ enableWebInterface: options.enableWebInterface ?? false,
17111
+ enableMcpServer: options.enableMcpServer ?? true,
17112
+ enableApiServer: options.enableApiServer ?? false,
17113
+ port: options.port,
17114
+ showLogo: options.showLogo ?? true,
17115
+ startupContext: options.startupContext
17116
+ };
17117
+ }
17118
+ /**
17119
+ * Parses custom headers from CLI options
17120
+ */
17121
+ function parseHeaders(headerOptions) {
17122
+ const headers = {};
17123
+ if (Array.isArray(headerOptions)) for (const entry of headerOptions) {
17124
+ const idx = entry.indexOf(":");
17125
+ if (idx > 0) {
17126
+ const name = entry.slice(0, idx).trim();
17127
+ const value = entry.slice(idx + 1).trim();
17128
+ if (name) headers[name] = value;
17129
+ }
17130
+ }
17131
+ return headers;
17132
+ }
17133
+ /**
17134
+ * Check the auth settings for the transport a command serves. Authentication
17135
+ * applies to MCP over HTTP only. Over stdio the host launching the process is
17136
+ * the trust boundary, so auth settings are ignored with a warning on stderr,
17137
+ * which never carries protocol data.
17138
+ * @param auth - The loaded auth settings.
17139
+ * @param protocol - The resolved transport.
17140
+ * @param port - The HTTP port, for the plain-HTTP warning.
17141
+ * @throws Error when an auth setting over HTTP is malformed.
17142
+ */
17143
+ function checkAuthForProtocol(auth, protocol, port) {
17144
+ if (!auth.enabled) return;
17145
+ if (protocol === "stdio") {
17146
+ console.error("⚠️ Authentication does not apply to MCP over stdio; auth settings are ignored.");
17147
+ return;
17148
+ }
17149
+ validateAuthConfig(auth);
17150
+ warnHttpUsage(port);
17151
+ }
17152
+ /**
17153
+ * Validates the format of auth settings that are present. Whether a setting
17154
+ * is required depends on what the process serves, so the server checks that
17155
+ * at startup.
17156
+ */
17157
+ function validateAuthConfig(authConfig) {
17158
+ const errors = [];
17159
+ if (authConfig.issuerUrl) try {
17160
+ if (new URL(authConfig.issuerUrl).protocol !== "https:") errors.push("Issuer URL must use HTTPS protocol");
17161
+ } catch {
17162
+ errors.push("Issuer URL must be a valid URL");
17163
+ }
17164
+ if (authConfig.audience) try {
17165
+ const url = new URL(authConfig.audience);
17166
+ if (url.protocol === "http:" && url.hostname !== "localhost") logger.warn("⚠️ Audience uses HTTP protocol - consider using HTTPS for production");
17167
+ if (url.hash) errors.push("Audience must not contain URL fragments");
17168
+ } catch {
17169
+ if (authConfig.audience.startsWith("urn:")) {
17170
+ const urnParts = authConfig.audience.split(":");
17171
+ if (urnParts.length < 3 || !urnParts[1] || !urnParts[2]) errors.push("URN audience must follow format: urn:namespace:specific-string");
17172
+ } else errors.push("Audience must be a valid absolute URL or URN (e.g., https://api.example.com or urn:company:service)");
17173
+ }
17174
+ if (errors.length > 0) throw new Error(`Auth configuration validation failed:\n${errors.join("\n")}`);
17175
+ }
17176
+ /**
17177
+ * Warns about HTTP usage in production when auth is enabled.
17178
+ */
17179
+ function warnHttpUsage(port) {
17180
+ if (!(process.env.NODE_ENV !== "production" || port === 6280 || process.env.HOSTNAME?.includes("localhost"))) logger.warn("⚠️ Authentication is enabled but running over HTTP in production. Consider using HTTPS for security.");
17181
+ }
17182
+ /**
17183
+ * Prompts the user interactively to confirm an embedding model change.
17184
+ * Returns true if the user confirms (y/Y), false otherwise.
17185
+ */
17186
+ function promptModelChangeConfirmation(change) {
17187
+ return new Promise((resolve) => {
17188
+ console.error(`\n⚠️ Embedding model change detected:\n Previous: ${describeEmbeddingModel(change.previousModel, change.previousDimension)}\n Current: ${describeEmbeddingModel(change.currentModel, change.currentDimension)}\n\n All existing embedding vectors will be invalidated.\n Libraries must be re-scraped to restore vector search.\n Full-text search will continue working for all existing documents.\n`);
17189
+ const rl = createInterface({
17190
+ input: process.stdin,
17191
+ output: process.stderr
17192
+ });
17193
+ rl.question(" Proceed with model change? (y/N) ", (answer) => {
17194
+ rl.close();
17195
+ resolve(answer.trim().toLowerCase() === "y");
17196
+ });
17197
+ });
17198
+ }
17199
+ /**
17200
+ * Handles EmbeddingModelChangedError during service initialization.
17201
+ *
17202
+ * - When accepted (`--accept-model-change` or `DOCS_MCP_ACCEPT_MODEL_CHANGE`):
17203
+ * resolves the model change (invalidates vectors) without asking.
17204
+ * - In non-interactive mode (no TTY): re-throws the error to fail startup.
17205
+ * - In interactive mode (TTY): prompts the user for confirmation, then either
17206
+ * resolves the model change or exits.
17207
+ *
17208
+ * @param error The EmbeddingModelChangedError thrown by DocumentStore.initialize()
17209
+ * @param service The DocumentManagementService instance (already partially initialized)
17210
+ * @param acceptFlag The value of `--accept-model-change`; when omitted,
17211
+ * `DOCS_MCP_ACCEPT_MODEL_CHANGE` decides
17212
+ * @throws Re-throws the error in non-interactive mode or if the user rejects the change
17213
+ */
17214
+ async function handleEmbeddingModelChange(error, service, acceptFlag) {
17215
+ if (acceptFlag ?? parseEnvBoolean(process.env.DOCS_MCP_ACCEPT_MODEL_CHANGE) ?? false) {
17216
+ logger.warn(`⚠️ Accepting embedding model change without a prompt: ${describeEmbeddingModel(error.previousModel, error.previousDimension)} → ${describeEmbeddingModel(error.currentModel, error.currentDimension)}`);
17217
+ await service.resolveModelChange();
17218
+ return;
17219
+ }
17220
+ if (!process.stdin.isTTY || !process.stdout.isTTY) throw error;
17221
+ if (!await promptModelChangeConfirmation(error)) throw new Error("Embedding model change rejected. Startup aborted.\nRestore the previous embedding model configuration to continue without changes.");
17222
+ await service.resolveModelChange();
17223
+ }
17224
+ // src/cli/commands/compact.ts
16732
17225
  function createCompactCommand(cli) {
16733
17226
  cli.command("compact", "Reclaim unused space in the document store (exclusive lock; may block searches)", (yargs) => {
16734
17227
  return yargs.option("force", {
@@ -16769,8 +17262,7 @@ function createCompactCommand(cli) {
16769
17262
  }
16770
17263
  });
16771
17264
  }
16772
- //#endregion
16773
- //#region src/cli/commands/config.ts
17265
+ // src/cli/commands/config.ts
16774
17266
  function validateConfigPath(path) {
16775
17267
  return isValidConfigPath(path);
16776
17268
  }
@@ -16848,8 +17340,7 @@ function createConfigCommand(cli) {
16848
17340
  }
16849
17341
  });
16850
17342
  }
16851
- //#endregion
16852
- //#region src/auth/JwtAccessTokenVerifier.ts
17343
+ // src/auth/JwtAccessTokenVerifier.ts
16853
17344
  /**
16854
17345
  * Verifies OAuth 2.0 access tokens for the MCP endpoint, which acts as a
16855
17346
  * resource server: a token is accepted only when it is a JWT signed with a key
@@ -16975,8 +17466,7 @@ var JwtAccessTokenVerifier = class JwtAccessTokenVerifier {
16975
17466
  };
16976
17467
  }
16977
17468
  };
16978
- //#endregion
16979
- //#region src/auth/protectedResourceMetadata.ts
17469
+ // src/auth/protectedResourceMetadata.ts
16980
17470
  /**
16981
17471
  * OAuth 2.0 Protected Resource Metadata (RFC 9728) for the MCP endpoint, and
16982
17472
  * the pieces of the discovery challenge that point clients at it.
@@ -17041,8 +17531,7 @@ function protectedResourceMetadataUrl(publicUrl, endpointPath) {
17041
17531
  function missingTokenChallenge(resourceMetadataUrl) {
17042
17532
  return `Bearer resource_metadata="${resourceMetadataUrl.replaceAll(/[\\"]/g, "\\$&")}"`;
17043
17533
  }
17044
- //#endregion
17045
- //#region src/app/originPolicy.ts
17534
+ // src/app/originPolicy.ts
17046
17535
  /**
17047
17536
  * Build the origin policy. Loopback origins, the public URL's origin and each
17048
17537
  * allowed origin (matched exactly) are allowed.
@@ -17159,8 +17648,7 @@ function isLoopbackBindHost(host) {
17159
17648
  if (family === 0) return unbracketed === "localhost";
17160
17649
  return LOOPBACK_ADDRESSES.check(unbracketed, family === 6 ? "ipv6" : "ipv4");
17161
17650
  }
17162
- //#endregion
17163
- //#region src/tools/errors.ts
17651
+ // src/tools/errors.ts
17164
17652
  var ToolError = class extends Error {
17165
17653
  toolName;
17166
17654
  constructor(message, toolName) {
@@ -17174,8 +17662,7 @@ var ToolError = class extends Error {
17174
17662
  * This indicates a client-side issue with the request parameters.
17175
17663
  */
17176
17664
  var ValidationError = class extends ToolError {};
17177
- //#endregion
17178
- //#region src/mcp/defaultInstructions.ts
17665
+ // src/mcp/defaultInstructions.ts
17179
17666
  /**
17180
17667
  * Built-in instructions sent to MCP clients when no instructions are configured.
17181
17668
  * Tool descriptions each explain one tool; this text explains how the tools work
@@ -17200,8 +17687,7 @@ function buildDefaultInstructions(readOnly) {
17200
17687
  readOnly ? READ_ONLY : INDEX
17201
17688
  ].join("\n");
17202
17689
  }
17203
- //#endregion
17204
- //#region src/mcp/utils.ts
17690
+ // src/mcp/utils.ts
17205
17691
  /**
17206
17692
  * Creates a success response object in the format expected by the MCP server.
17207
17693
  * @param text The text content of the response.
@@ -17230,8 +17716,7 @@ function createError(errorOrText) {
17230
17716
  isError: true
17231
17717
  };
17232
17718
  }
17233
- //#endregion
17234
- //#region src/mcp/mcpServer.ts
17719
+ // src/mcp/mcpServer.ts
17235
17720
  /**
17236
17721
  * Splits a comma-separated pattern string into an array of patterns. Commas
17237
17722
  * inside `{}`, `[]`, or `()` (regex quantifiers, glob brace expansion,
@@ -17422,7 +17907,7 @@ function createMcpServerInstance(tools, config, instructions, schemas) {
17422
17907
  const server = new McpServer({
17423
17908
  name,
17424
17909
  ...title !== void 0 ? { title } : {},
17425
- version: "3.3.0"
17910
+ version: "3.4.1"
17426
17911
  }, {
17427
17912
  capabilities: {
17428
17913
  tools: {},
@@ -17841,8 +18326,7 @@ ${r.content}\n`);
17841
18326
  }
17842
18327
  return server;
17843
18328
  }
17844
- //#endregion
17845
- //#region src/tools/CancelJobTool.ts
18329
+ // src/tools/CancelJobTool.ts
17846
18330
  /**
17847
18331
  * Tool for attempting to cancel a pipeline job.
17848
18332
  */
@@ -17890,8 +18374,7 @@ var CancelJobTool = class {
17890
18374
  }
17891
18375
  }
17892
18376
  };
17893
- //#endregion
17894
- //#region src/tools/FetchUrlTool.ts
18377
+ // src/tools/FetchUrlTool.ts
17895
18378
  /**
17896
18379
  * Tool for fetching a single URL and converting its content to Markdown.
17897
18380
  * Unlike scrape_docs, this tool only processes one page without crawling
@@ -17962,14 +18445,14 @@ var FetchUrlTool = class {
17962
18445
  } catch (error) {
17963
18446
  if (error instanceof ToolError) throw error;
17964
18447
  if (error instanceof ChallengeError) throw new ToolError(`Unable to fetch the URL "${url}": the site answered with a ${error.challengeType} bot challenge instead of the page, which cannot be passed automatically.`, this.constructor.name);
18448
+ if (error instanceof RenderError) throw new ToolError(`${error.message}. Use scrape mode "auto" to read the page as fetched instead.`, this.constructor.name);
17965
18449
  throw new ToolError(`Unable to fetch or process the URL "${url}". Please verify the URL is correct and accessible.`, this.constructor.name);
17966
18450
  } finally {
17967
18451
  await Promise.allSettled([...this.pipelines.map((pipeline) => pipeline.close()), this.fetcher.close()]);
17968
18452
  }
17969
18453
  }
17970
18454
  };
17971
- //#endregion
17972
- //#region src/tools/FindVersionTool.ts
18455
+ // src/tools/FindVersionTool.ts
17973
18456
  /**
17974
18457
  * Tool for finding the best matching version of a library in the store.
17975
18458
  * Supports exact version matches and X-Range patterns (e.g., '5.x', '5.2.x').
@@ -18003,8 +18486,7 @@ var FindVersionTool = class {
18003
18486
  };
18004
18487
  }
18005
18488
  };
18006
- //#endregion
18007
- //#region src/tools/GetJobInfoTool.ts
18489
+ // src/tools/GetJobInfoTool.ts
18008
18490
  /**
18009
18491
  * Tool for retrieving simplified information about a specific pipeline job.
18010
18492
  */
@@ -18049,8 +18531,7 @@ var GetJobInfoTool = class {
18049
18531
  } };
18050
18532
  }
18051
18533
  };
18052
- //#endregion
18053
- //#region src/tools/ListJobsTool.ts
18534
+ // src/tools/ListJobsTool.ts
18054
18535
  /**
18055
18536
  * Tool for listing pipeline jobs managed by the pipeline.
18056
18537
  * Allows filtering jobs by their status.
@@ -18093,8 +18574,7 @@ var ListJobsTool = class {
18093
18574
  }) };
18094
18575
  }
18095
18576
  };
18096
- //#endregion
18097
- //#region src/tools/ListLibrariesTool.ts
18577
+ // src/tools/ListLibrariesTool.ts
18098
18578
  /**
18099
18579
  * Tool for listing all available libraries and their indexed versions in the store.
18100
18580
  */
@@ -18120,8 +18600,7 @@ var ListLibrariesTool = class {
18120
18600
  })) };
18121
18601
  }
18122
18602
  };
18123
- //#endregion
18124
- //#region src/tools/ListPagesTool.ts
18603
+ // src/tools/ListPagesTool.ts
18125
18604
  /**
18126
18605
  * Tool for listing indexed pages and documentation sitemap for a library version.
18127
18606
  */
@@ -18144,8 +18623,7 @@ var ListPagesTool = class {
18144
18623
  });
18145
18624
  }
18146
18625
  };
18147
- //#endregion
18148
- //#region src/tools/ReadPageTool.ts
18626
+ // src/tools/ReadPageTool.ts
18149
18627
  /**
18150
18628
  * Strips what agents tend to copy along with a link: the HTML-escaped `&lt;…&gt;`
18151
18629
  * wrapper, angle brackets and quotes, `./` and `../` prefixes, and Windows
@@ -18178,8 +18656,7 @@ var ReadPageTool = class {
18178
18656
  });
18179
18657
  }
18180
18658
  };
18181
- //#endregion
18182
- //#region src/tools/RefreshVersionTool.ts
18659
+ // src/tools/RefreshVersionTool.ts
18183
18660
  /**
18184
18661
  * Tool for refreshing an existing library version by re-scraping all pages
18185
18662
  * and using ETag comparison to skip unchanged content.
@@ -18209,8 +18686,7 @@ var RefreshVersionTool = class {
18209
18686
  return { jobId };
18210
18687
  }
18211
18688
  };
18212
- //#endregion
18213
- //#region src/tools/RemoveTool.ts
18689
+ // src/tools/RemoveTool.ts
18214
18690
  /**
18215
18691
  * Tool to remove indexed documentation for a specific library version.
18216
18692
  * This class provides the core logic, intended to be called by the McpServer.
@@ -18253,8 +18729,7 @@ var RemoveTool = class {
18253
18729
  }
18254
18730
  }
18255
18731
  };
18256
- //#endregion
18257
- //#region src/tools/ScrapeTool.ts
18732
+ // src/tools/ScrapeTool.ts
18258
18733
  /**
18259
18734
  * Tool for enqueuing documentation scraping jobs via the pipeline.
18260
18735
  */
@@ -18302,8 +18777,7 @@ var ScrapeTool = class {
18302
18777
  return { jobId };
18303
18778
  }
18304
18779
  };
18305
- //#endregion
18306
- //#region src/tools/SearchTool.ts
18780
+ // src/tools/SearchTool.ts
18307
18781
  /**
18308
18782
  * Tool for searching indexed documentation.
18309
18783
  * Supports exact version matches and version range patterns.
@@ -18340,8 +18814,7 @@ var SearchTool = class {
18340
18814
  }
18341
18815
  }
18342
18816
  };
18343
- //#endregion
18344
- //#region src/mcp/tools.ts
18817
+ // src/mcp/tools.ts
18345
18818
  /**
18346
18819
  * Initializes and returns the shared tool instances.
18347
18820
  * This should be called after initializeServices has completed.
@@ -18366,8 +18839,7 @@ async function initializeTools(docService, pipeline, config) {
18366
18839
  fetchUrl: new FetchUrlTool(new AutoDetectFetcher(config.scraper), config)
18367
18840
  };
18368
18841
  }
18369
- //#endregion
18370
- //#region src/services/mcpService.ts
18842
+ // src/services/mcpService.ts
18371
18843
  /** Path of the MCP endpoint, relative to the public URL. */
18372
18844
  var MCP_ENDPOINT_PATH = "/mcp";
18373
18845
  /** Path of the deprecated HTTP+SSE transport's event stream, relative to the public URL. */
@@ -18531,8 +19003,7 @@ function registerLegacySseTransport(server, deps, createServer) {
18531
19003
  await Promise.all([...sessions.values()].map((transport) => transport.close()));
18532
19004
  });
18533
19005
  }
18534
- //#endregion
18535
- //#region src/services/systemInfo.ts
19006
+ // src/services/systemInfo.ts
18536
19007
  /**
18537
19008
  * Assembles the {@link SystemInfo} snapshot from server + app configuration.
18538
19009
  * @param serverConfig - Service composition/runtime wiring for this process.
@@ -18545,7 +19016,7 @@ function buildSystemInfo(serverConfig, appConfig, mcpEndpointUrl, workerUrl) {
18545
19016
  const mcpEnabled = Boolean(serverConfig.enableMcpServer);
18546
19017
  const authEnabled = Boolean(appConfig.auth.enabled);
18547
19018
  return {
18548
- version: "3.3.0",
19019
+ version: "3.4.1",
18549
19020
  readOnly: Boolean(appConfig.app.readOnly),
18550
19021
  telemetryEnabled: Boolean(appConfig.app.telemetryEnabled),
18551
19022
  services: {
@@ -18579,8 +19050,7 @@ function buildSystemInfo(serverConfig, appConfig, mcpEndpointUrl, workerUrl) {
18579
19050
  }
18580
19051
  };
18581
19052
  }
18582
- //#endregion
18583
- //#region src/events/trpc/router.ts
19053
+ // src/events/trpc/router.ts
18584
19054
  /**
18585
19055
  * tRPC router for event subscriptions.
18586
19056
  * Allows remote processes to subscribe to application events via tRPC.
@@ -18616,8 +19086,7 @@ subscribe: tt.procedure.input(z.object({ events: z.array(z.nativeEnum(EventType)
18616
19086
  }) });
18617
19087
  }
18618
19088
  createEventsRouter(t$4);
18619
- //#endregion
18620
- //#region src/pipeline/trpc/router.ts
19089
+ // src/pipeline/trpc/router.ts
18621
19090
  /**
18622
19091
  * tRPC router exposing pipeline procedures for external workers.
18623
19092
  * Provides a minimal RPC surface to replace legacy REST endpoints.
@@ -18706,8 +19175,7 @@ function createPipelineRouter(trpc) {
18706
19175
  });
18707
19176
  }
18708
19177
  createPipelineRouter(t$3);
18709
- //#endregion
18710
- //#region src/store/trpc/router.ts
19178
+ // src/store/trpc/router.ts
18711
19179
  /**
18712
19180
  * tRPC router exposing document data store operations via the worker API.
18713
19181
  * Only procedures actually used externally are included to keep surface minimal.
@@ -18849,8 +19317,7 @@ function createDataRouter(trpc) {
18849
19317
  });
18850
19318
  }
18851
19319
  createDataRouter(t$2);
18852
- //#endregion
18853
- //#region src/services/systemHealthRouter.ts
19320
+ // src/services/systemHealthRouter.ts
18854
19321
  /**
18855
19322
  * tRPC router exposing a single `getSystemHealth` query that composes the
18856
19323
  * server's startup {@link SystemInfo} snapshot with the small amount of
@@ -18902,8 +19369,7 @@ getSystemHealth: tt.procedure.query(async ({ ctx }) => {
18902
19369
  }) });
18903
19370
  }
18904
19371
  createSystemHealthRouter(t$1);
18905
- //#endregion
18906
- //#region src/services/appRouter.ts
19372
+ // src/services/appRouter.ts
18907
19373
  /**
18908
19374
  * Canonical tRPC router builder for the merged application API.
18909
19375
  * Combines the health check, pipeline, data store, and events routers into a
@@ -18938,11 +19404,30 @@ removeDocs: t.procedure.input(z.object({
18938
19404
  library: input.library,
18939
19405
  version: input.version ?? void 0
18940
19406
  })) });
19407
+ const searchRouter = t.router({
19408
+ /**
19409
+ * Searches a library as `search_docs` does: the version resolves to the
19410
+ * best stored match first, and an omitted or empty one to the newest. The
19411
+ * data router's `search` stays literal, since remote clients send it a
19412
+ * version the tool has already resolved.
19413
+ */
19414
+ searchDocs: t.procedure.input(z.object({
19415
+ library: nonEmpty,
19416
+ version: optionalVersion,
19417
+ query: nonEmpty,
19418
+ limit: z.number().int().positive().max(50).optional()
19419
+ })).query(({ ctx, input }) => new SearchTool(ctx.docService).execute({
19420
+ library: input.library,
19421
+ version: input.version ?? void 0,
19422
+ query: input.query,
19423
+ limit: input.limit
19424
+ })) });
18941
19425
  return t.router({
18942
19426
  ...healthRouter._def.procedures,
18943
19427
  ...createPipelineRouter(t)._def.procedures,
18944
19428
  ...createDataRouter(t)._def.procedures,
18945
19429
  ...removalRouter._def.procedures,
19430
+ ...searchRouter._def.procedures,
18946
19431
  ...createSystemHealthRouter(t)._def.procedures,
18947
19432
  events: createEventsRouter(t)
18948
19433
  });
@@ -18963,8 +19448,7 @@ function createAppRouterContext(deps) {
18963
19448
  isWorkerConnected: deps.isWorkerConnected
18964
19449
  };
18965
19450
  }
18966
- //#endregion
18967
- //#region src/services/trpcService.ts
19451
+ // src/services/trpcService.ts
18968
19452
  /**
18969
19453
  * Fastify service to register unified tRPC API at /api.
18970
19454
  * Merges pipeline, data store, and events routers under a single endpoint.
@@ -19019,8 +19503,7 @@ function applyTrpcWebSocketHandler(wss, pipeline, docService, eventBus, systemIn
19019
19503
  })
19020
19504
  });
19021
19505
  }
19022
- //#endregion
19023
- //#region src/utils/banner.ts
19506
+ // src/utils/banner.ts
19024
19507
  /**
19025
19508
  * ASCII art banner for console startup display.
19026
19509
  * Uses ANSI colors: gray (dim) top line, bright white bottom line.
@@ -19035,8 +19518,7 @@ function printBanner() {
19035
19518
  console.log(BANNER);
19036
19519
  console.log();
19037
19520
  }
19038
- //#endregion
19039
- //#region src/app/basePath.ts
19521
+ // src/app/basePath.ts
19040
19522
  /**
19041
19523
  * Helpers for serving the application under the path of its public URL, e.g.
19042
19524
  * `https://example.com/docs`, behind proxies that either forward or strip that
@@ -19111,8 +19593,7 @@ function isApiSocketPath(url, basePath) {
19111
19593
  const pathname = stripBasePath(url, basePath).split("?")[0];
19112
19594
  return pathname === "/" || isUnderPath(pathname, "/api");
19113
19595
  }
19114
- //#endregion
19115
- //#region src/app/AppServer.ts
19596
+ // src/app/AppServer.ts
19116
19597
  /**
19117
19598
  * Central application server that can be configured to run different combinations of services.
19118
19599
  * This replaces the separate server implementations with a single, modular approach.
@@ -19207,7 +19688,7 @@ var AppServer = class AppServer {
19207
19688
  if (this.appConfig.app.telemetryEnabled && shouldEnableTelemetry()) try {
19208
19689
  if (telemetry.isEnabled()) {
19209
19690
  telemetry.setGlobalContext({
19210
- appVersion: "3.3.0",
19691
+ appVersion: "3.4.1",
19211
19692
  appPlatform: process.platform,
19212
19693
  appNodeVersion: process.version,
19213
19694
  appServicesEnabled: this.getActiveServicesList(),
@@ -19518,8 +19999,7 @@ function refuseUpgrade(socket, status) {
19518
19999
  socket.once("finish", () => socket.destroy());
19519
20000
  socket.end(`HTTP/1.1 ${status}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
19520
20001
  }
19521
- //#endregion
19522
- //#region src/app/index.ts
20002
+ // src/app/index.ts
19523
20003
  /**
19524
20004
  * Starts an AppServer that serves `backend` with the given configuration.
19525
20005
  * Convenience function for CLI integration.
@@ -19534,8 +20014,7 @@ async function startAppServer(backend, serverConfig, appConfig) {
19534
20014
  await appServer.start();
19535
20015
  return appServer;
19536
20016
  }
19537
- //#endregion
19538
- //#region src/mcp/startStdioServer.ts
20017
+ // src/mcp/startStdioServer.ts
19539
20018
  /**
19540
20019
  * Starts the MCP server on the process's stdio.
19541
20020
  *
@@ -19555,8 +20034,7 @@ async function startStdioServer(tools, config) {
19555
20034
  logger.info("🤖 MCP server listening on stdio");
19556
20035
  return handle;
19557
20036
  }
19558
- //#endregion
19559
- //#region src/cli/options.ts
20037
+ // src/cli/options.ts
19560
20038
  /**
19561
20039
  * Declare `--public-url` and its deprecated alias `--public-origin`.
19562
20040
  * @param yargs - The command's builder.
@@ -19619,8 +20097,21 @@ function withServerIdentityOptions(yargs) {
19619
20097
  alias: "serverInstructionsFile"
19620
20098
  });
19621
20099
  }
19622
- //#endregion
19623
- //#region src/cli/services.ts
20100
+ /**
20101
+ * Declare `--accept-model-change`, which confirms a changed embedding model
20102
+ * without a prompt. Without the flag, `DOCS_MCP_ACCEPT_MODEL_CHANGE` decides.
20103
+ * @param yargs - The command's builder.
20104
+ * @returns The builder, for chaining.
20105
+ */
20106
+ function withModelChangeOptions(yargs) {
20107
+ return yargs.option("accept-model-change", {
20108
+ type: "boolean",
20109
+ description: "Confirm a changed embedding model without a prompt; deletes all stored vectors",
20110
+ defaultDescription: "false",
20111
+ alias: "acceptModelChange"
20112
+ });
20113
+ }
20114
+ // src/cli/services.ts
19624
20115
  var activeAppServer = null;
19625
20116
  var activeMcpStdioServer = null;
19626
20117
  var activeBackend = null;
@@ -19653,10 +20144,9 @@ async function closeActiveBackend() {
19653
20144
  activeBackend = null;
19654
20145
  await backend?.close();
19655
20146
  }
19656
- //#endregion
19657
- //#region src/cli/commands/default.ts
20147
+ // src/cli/commands/default.ts
19658
20148
  function createDefaultAction(cli) {
19659
- cli.command(["$0", "server"], "Starts the Docs MCP server (Unified Mode)", (yargs) => withAuthOptions(withServerIdentityOptions(withPublicUrlOptions(yargs.option("protocol", {
20149
+ cli.command(["$0", "server"], "Starts the Docs MCP server (Unified Mode)", (yargs) => withAuthOptions(withServerIdentityOptions(withPublicUrlOptions(withModelChangeOptions(yargs).option("protocol", {
19660
20150
  type: "string",
19661
20151
  description: "Protocol for MCP server",
19662
20152
  choices: [
@@ -19711,7 +20201,7 @@ function createDefaultAction(cli) {
19711
20201
  appConfig,
19712
20202
  eventBus: getEventBus(argv),
19713
20203
  jobs: { interruptedJobs: appConfig.app.readOnly ? "leave" : argv.resume ? "recover" : "fail" },
19714
- onEmbeddingModelChange: handleEmbeddingModelChange
20204
+ onEmbeddingModelChange: (error, service) => handleEmbeddingModelChange(error, service, argv.acceptModelChange)
19715
20205
  });
19716
20206
  registerGlobalServices({ backend });
19717
20207
  if (resolvedProtocol === "stdio") {
@@ -19735,8 +20225,7 @@ function createDefaultAction(cli) {
19735
20225
  }
19736
20226
  });
19737
20227
  }
19738
- //#endregion
19739
- //#region src/cli/commands/fetchUrl.ts
20228
+ // src/cli/commands/fetchUrl.ts
19740
20229
  function createFetchUrlCommand(cli) {
19741
20230
  cli.command("fetch-url <url>", "Fetch a URL and transform it into Markdown format", (yargs) => {
19742
20231
  return yargs.positional("url", {
@@ -19777,6 +20266,7 @@ function createFetchUrlCommand(cli) {
19777
20266
  configPath: argv.config,
19778
20267
  searchDir: argv.storePath
19779
20268
  });
20269
+ ensurePlaywrightBrowsersInstalled();
19780
20270
  renderTextOutput(await new FetchUrlTool(new AutoDetectFetcher(appConfig.scraper), appConfig).execute({
19781
20271
  url,
19782
20272
  followRedirects: argv.followRedirects,
@@ -19785,8 +20275,7 @@ function createFetchUrlCommand(cli) {
19785
20275
  }));
19786
20276
  });
19787
20277
  }
19788
- //#endregion
19789
- //#region src/cli/commands/findVersion.ts
20278
+ // src/cli/commands/findVersion.ts
19790
20279
  function createFindVersionCommand(cli) {
19791
20280
  cli.command("find-version <library>", "Resolve and display the best matching documentation version for a library", (yargs) => {
19792
20281
  return yargs.version(false).positional("library", {
@@ -19834,8 +20323,7 @@ function createFindVersionCommand(cli) {
19834
20323
  }
19835
20324
  });
19836
20325
  }
19837
- //#endregion
19838
- //#region src/cli/commands/list.ts
20326
+ // src/cli/commands/list.ts
19839
20327
  function createListCommand(cli) {
19840
20328
  cli.command("list", "List all indexed libraries and their available versions", (yargs) => {
19841
20329
  return yargs.option("server-url", {
@@ -19866,10 +20354,9 @@ function createListCommand(cli) {
19866
20354
  }
19867
20355
  });
19868
20356
  }
19869
- //#endregion
19870
- //#region src/cli/commands/mcp.ts
20357
+ // src/cli/commands/mcp.ts
19871
20358
  function createMcpCommand(cli) {
19872
- cli.command("mcp", "Start the MCP server (Standalone Mode)", (yargs) => withAuthOptions(withServerIdentityOptions(withPublicUrlOptions(yargs.option("protocol", {
20359
+ cli.command("mcp", "Start the MCP server (Standalone Mode)", (yargs) => withAuthOptions(withServerIdentityOptions(withPublicUrlOptions(withModelChangeOptions(yargs).option("protocol", {
19873
20360
  type: "string",
19874
20361
  description: "Protocol for MCP server",
19875
20362
  choices: [
@@ -19919,6 +20406,7 @@ function createMcpCommand(cli) {
19919
20406
  quiet: argv.quiet
19920
20407
  });
19921
20408
  checkAuthForProtocol(appConfig.auth, resolvedProtocol, appConfig.server.ports.mcp);
20409
+ ensurePlaywrightBrowsersInstalled();
19922
20410
  try {
19923
20411
  const serverUrl = argv.serverUrl;
19924
20412
  const backend = await openBackend({
@@ -19926,7 +20414,7 @@ function createMcpCommand(cli) {
19926
20414
  eventBus: getEventBus(argv),
19927
20415
  serverUrl,
19928
20416
  jobs: { interruptedJobs: appConfig.app.readOnly ? "leave" : "fail" },
19929
- onEmbeddingModelChange: handleEmbeddingModelChange
20417
+ onEmbeddingModelChange: (error, service) => handleEmbeddingModelChange(error, service, argv.acceptModelChange)
19930
20418
  });
19931
20419
  registerGlobalServices({ backend });
19932
20420
  if (resolvedProtocol === "stdio") {
@@ -19954,8 +20442,7 @@ function createMcpCommand(cli) {
19954
20442
  }
19955
20443
  });
19956
20444
  }
19957
- //#endregion
19958
- //#region src/cli/JobOutputFollower.ts
20445
+ // src/cli/JobOutputFollower.ts
19959
20446
  /**
19960
20447
  * Passes a command the status and progress events of the job it submitted, and
19961
20448
  * no others. A shared worker runs jobs for several clients, and a job can start
@@ -20020,8 +20507,7 @@ function followJobLogs(eventBus, verb) {
20020
20507
  }
20021
20508
  });
20022
20509
  }
20023
- //#endregion
20024
- //#region src/cli/commands/refresh.ts
20510
+ // src/cli/commands/refresh.ts
20025
20511
  function createRefreshCommand(cli) {
20026
20512
  cli.command("refresh <library>", "Update an existing library version by re-scraping changed pages", (yargs) => {
20027
20513
  return yargs.version(false).positional("library", {
@@ -20060,6 +20546,7 @@ function createRefreshCommand(cli) {
20060
20546
  configPath: argv.config,
20061
20547
  searchDir: argv.storePath
20062
20548
  });
20549
+ if (!serverUrl) ensurePlaywrightBrowsersInstalled();
20063
20550
  const backend = await openBackend({
20064
20551
  serverUrl,
20065
20552
  eventBus: getEventBus(argv),
@@ -20088,8 +20575,7 @@ function createRefreshCommand(cli) {
20088
20575
  }
20089
20576
  });
20090
20577
  }
20091
- //#endregion
20092
- //#region src/cli/commands/remove.ts
20578
+ // src/cli/commands/remove.ts
20093
20579
  function createRemoveCommand(cli) {
20094
20580
  cli.command("remove <library>", "Remove a library version from the index, and the library with its last version", (yargs) => {
20095
20581
  return yargs.version(false).positional("library", {
@@ -20135,8 +20621,7 @@ function createRemoveCommand(cli) {
20135
20621
  }
20136
20622
  });
20137
20623
  }
20138
- //#endregion
20139
- //#region src/cli/commands/scrape.ts
20624
+ // src/cli/commands/scrape.ts
20140
20625
  function createScrapeCommand(cli) {
20141
20626
  cli.command("scrape <library> <url>", "Download and index documentation from a URL or local directory", (yargs) => {
20142
20627
  return yargs.version(false).positional("library", {
@@ -20261,6 +20746,7 @@ function createScrapeCommand(cli) {
20261
20746
  hasExcludePatterns: argv.excludePattern.length > 0,
20262
20747
  useServerUrl: !!serverUrl
20263
20748
  });
20749
+ if (!serverUrl) ensurePlaywrightBrowsersInstalled();
20264
20750
  const backend = await openBackend({
20265
20751
  serverUrl,
20266
20752
  eventBus: getEventBus(argv),
@@ -20305,8 +20791,7 @@ function createScrapeCommand(cli) {
20305
20791
  }
20306
20792
  });
20307
20793
  }
20308
- //#endregion
20309
- //#region src/cli/commands/search.ts
20794
+ // src/cli/commands/search.ts
20310
20795
  function createSearchCommand(cli) {
20311
20796
  cli.command("search <library> <query>", "Query the documentation index used by the MCP server", (yargs) => {
20312
20797
  return yargs.version(false).positional("library", {
@@ -20377,8 +20862,7 @@ function createSearchCommand(cli) {
20377
20862
  }
20378
20863
  });
20379
20864
  }
20380
- //#endregion
20381
- //#region src/cli/commands/web.ts
20865
+ // src/cli/commands/web.ts
20382
20866
  function createWebCommand(cli) {
20383
20867
  cli.command("web", "Start the web dashboard (Standalone Mode)", (yargs) => {
20384
20868
  return withPublicUrlOptions(yargs.option("port", {
@@ -20410,6 +20894,7 @@ function createWebCommand(cli) {
20410
20894
  configPath: argv.config,
20411
20895
  searchDir: argv.storePath
20412
20896
  });
20897
+ if (!serverUrl) ensurePlaywrightBrowsersInstalled();
20413
20898
  try {
20414
20899
  const backend = await openBackend({
20415
20900
  appConfig,
@@ -20433,11 +20918,10 @@ function createWebCommand(cli) {
20433
20918
  }
20434
20919
  });
20435
20920
  }
20436
- //#endregion
20437
- //#region src/cli/commands/worker.ts
20921
+ // src/cli/commands/worker.ts
20438
20922
  function createWorkerCommand(cli) {
20439
20923
  cli.command("worker", "Start a background worker for processing scraping jobs", (yargs) => {
20440
- return withPublicUrlOptions(yargs.option("port", {
20924
+ return withPublicUrlOptions(withModelChangeOptions(yargs).option("port", {
20441
20925
  type: "string",
20442
20926
  description: "Port for worker API"
20443
20927
  }).option("host", {
@@ -20473,7 +20957,8 @@ function createWorkerCommand(cli) {
20473
20957
  const backend = await openBackend({
20474
20958
  appConfig,
20475
20959
  eventBus: getEventBus(argv),
20476
- jobs: { interruptedJobs: argv.resume ?? true ? "recover" : "fail" }
20960
+ jobs: { interruptedJobs: argv.resume ?? true ? "recover" : "fail" },
20961
+ onEmbeddingModelChange: (error, service) => handleEmbeddingModelChange(error, service, argv.acceptModelChange)
20477
20962
  });
20478
20963
  registerGlobalServices({ backend });
20479
20964
  registerGlobalServices({ appServer: await startAppServer(backend, createAppServerConfig({
@@ -20491,8 +20976,7 @@ function createWorkerCommand(cli) {
20491
20976
  }
20492
20977
  });
20493
20978
  }
20494
- //#endregion
20495
- //#region src/cli/index.ts
20979
+ // src/cli/index.ts
20496
20980
  /**
20497
20981
  * Main CLI setup and command registration using Yargs.
20498
20982
  */
@@ -20562,7 +21046,7 @@ function registerGlobalOptions(cli) {
20562
21046
  function createCli(argv) {
20563
21047
  let globalEventBus = null;
20564
21048
  const commandStartTimes = /* @__PURE__ */ new Map();
20565
- const cli = registerGlobalOptions(yargs(hideBin(argv))).scriptName("docs-mcp-server").strict().usage("Usage: $0 <command> [options]").version("3.3.0").middleware(async (argv) => {
21049
+ const cli = registerGlobalOptions(yargs(hideBin(argv))).scriptName("docs-mcp-server").strict().usage("Usage: $0 <command> [options]").version("3.4.1").middleware(async (argv) => {
20566
21050
  if (argv.verbose && argv.quiet) throw new Error("Arguments verbose and quiet are mutually exclusive");
20567
21051
  applyGlobalCliOutputMode({
20568
21052
  verbose: argv.verbose,
@@ -20584,7 +21068,7 @@ function createCli(argv) {
20584
21068
  if (shouldEnableTelemetry() && telemetry.isEnabled()) {
20585
21069
  const commandName = argv._[0]?.toString() || "default";
20586
21070
  telemetry.setGlobalContext({
20587
- appVersion: "3.3.0",
21071
+ appVersion: "3.4.1",
20588
21072
  appPlatform: process.platform,
20589
21073
  appNodeVersion: process.version,
20590
21074
  appInterface: "cli",
@@ -20603,8 +21087,7 @@ function createCli(argv) {
20603
21087
  for (const registerCommand of COMMAND_FACTORIES) registerCommand(cli);
20604
21088
  return cli;
20605
21089
  }
20606
- //#endregion
20607
- //#region src/cli/main.ts
21090
+ // src/cli/main.ts
20608
21091
  /**
20609
21092
  * CLI main entry point with global shutdown and error handling.
20610
21093
  * Analytics is initialized immediately when imported for proper telemetry across all services.
@@ -20694,7 +21177,6 @@ async function runCli() {
20694
21177
  const appServer = getActiveAppServer();
20695
21178
  if (commandExecuted && !appServer) await cleanupCliCommand();
20696
21179
  }
20697
- //#endregion
20698
- export { cleanupCliCommand, runCli };
21180
+ export { runCli };
20699
21181
 
20700
- //# sourceMappingURL=main-BoABX2b0.js.map
21182
+ //# sourceMappingURL=main-Cb6JaTXM.js.map