@arabold/docs-mcp-server 3.4.1 → 3.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,7 +10,7 @@ import { Embeddings } from "@langchain/core/embeddings";
10
10
  import crypto, { randomUUID } from "node:crypto";
11
11
  import fs, { existsSync, statSync } from "node:fs";
12
12
  import path from "node:path";
13
- import { URL as URL$1, fileURLToPath } from "node:url";
13
+ import { URL as URL$1, fileURLToPath, pathToFileURL } from "node:url";
14
14
  import envPaths from "env-paths";
15
15
  import { PostHog } from "posthog-node";
16
16
  import yargs from "yargs";
@@ -26,7 +26,7 @@ import { lookup } from "node:dns/promises";
26
26
  import fs$1, { readFile } from "node:fs/promises";
27
27
  import net, { BlockList, isIP } from "node:net";
28
28
  import os from "node:os";
29
- import { Minimatch, minimatch } from "minimatch";
29
+ import { Minimatch } from "minimatch";
30
30
  import { HeaderGenerator } from "header-generator";
31
31
  import { chromium } from "playwright";
32
32
  import https from "node:https";
@@ -51,10 +51,11 @@ import { promisify } from "node:util";
51
51
  import { Readable } from "node:stream";
52
52
  import * as tar from "tar";
53
53
  import yauzl from "yauzl";
54
+ import ignore from "ignore";
54
55
  import Fuse from "fuse.js";
55
56
  import semver from "semver";
56
- import Database from "better-sqlite3";
57
57
  import * as sqliteVec from "sqlite-vec";
58
+ import Database from "better-sqlite3";
58
59
  import { createTRPCClient, createWSClient, httpBatchLink, splitLink, wsLink } from "@trpc/client";
59
60
  import superjson from "superjson";
60
61
  import { encode } from "@toon-format/toon";
@@ -270,6 +271,19 @@ var LibraryNotFoundInStoreError = class extends StoreError {
270
271
  }
271
272
  };
272
273
  /**
274
+ * Error thrown when a rename targets a library with an indexing job in flight.
275
+ * The rename is refused rather than letting the job keep writing under the old name.
276
+ */
277
+ var LibraryBusyError = class extends StoreError {
278
+ library;
279
+ activeStatuses;
280
+ constructor(library, activeStatuses) {
281
+ super(`Library ${escapeControlCharacters(library)} has an indexing job in flight (${activeStatuses.join(", ")}); retry the rename when it finishes. If no server or scrape command is indexing it anymore, the job was interrupted: starting the server resumes or fails it.`);
282
+ this.library = library;
283
+ this.activeStatuses = activeStatuses;
284
+ }
285
+ };
286
+ /**
273
287
  * Error thrown when a specific version of a library cannot be found in the store.
274
288
  * Includes the list of available versions for better context.
275
289
  */
@@ -380,6 +394,47 @@ var DimensionError = class extends StoreError {
380
394
  */
381
395
  var ConnectionError = class extends StoreError {};
382
396
  /**
397
+ * Error thrown when better-sqlite3's compiled binary cannot load. The package
398
+ * ships Node-API binaries for Windows, macOS and Linux (glibc and musl) on x64
399
+ * and arm64, which load under every supported Node.js version and under Bun.
400
+ * On another platform or architecture no binary exists, and on a damaged
401
+ * install the system cannot load it, so the package has to be reinstalled or
402
+ * built from source.
403
+ */
404
+ var NativeModuleUnavailableError = class extends StoreError {
405
+ constructor() {
406
+ super(`The SQLite native module (better-sqlite3) could not load on ${process.platform}-${process.arch}, so the database cannot open. better-sqlite3 ships prebuilt binaries for Windows, macOS and Linux on x64 and arm64. On one of those, reinstall the package. On another platform, build it from source with node-gyp: https://github.com/WiseLibs/better-sqlite3/blob/master/docs/compilation.md`);
407
+ }
408
+ };
409
+ /**
410
+ * Error thrown when the runtime provides an older Node-API version than
411
+ * better-sqlite3's binaries need. Node.js 22.0 to 22.13 provide Node-API 9,
412
+ * and loading the binary there crashes the process instead of throwing.
413
+ */
414
+ var NodeApiUnsupportedError = class extends StoreError {
415
+ available;
416
+ required;
417
+ constructor(available, required) {
418
+ super(`The SQLite native module (better-sqlite3) needs Node-API ${required}, but this runtime provides Node-API ${escapeControlCharacters(available)}, so the database cannot open. Update Node.js to 22.14 or later.`);
419
+ this.available = available;
420
+ this.required = required;
421
+ }
422
+ };
423
+ /**
424
+ * Tells whether an error means better-sqlite3's compiled binary failed to
425
+ * load: no binary exists for the platform, or the system could not load it.
426
+ * Node.js and Bun both report the path of the binary, which is either a
427
+ * compiled `build/Release/better_sqlite3.node` or a prebuilt
428
+ * `prebuilds/<platform>-<arch>.node` inside the package.
429
+ *
430
+ * @param error - The error thrown while opening the database
431
+ * @returns True when the error is about the binary
432
+ */
433
+ function isNativeModuleError(error) {
434
+ if (!(error instanceof Error) || !("code" in error)) return false;
435
+ return (error.code === "MODULE_NOT_FOUND" || error.code === "ERR_DLOPEN_FAILED") && /better-sqlite3[\\/](?:build|prebuilds)[\\/][^'"\s]*\.node/.test(error.message);
436
+ }
437
+ /**
383
438
  * Error thrown when the embedding provider fails to embed a page's chunks.
384
439
  * Nothing of the page is written when this is thrown.
385
440
  */
@@ -3566,16 +3621,22 @@ function isRegexPattern(pattern) {
3566
3621
  return pattern.length > 2 && pattern.startsWith("/") && pattern.endsWith("/");
3567
3622
  }
3568
3623
  /**
3569
- * Converts a pattern string to a RegExp instance (auto-detects glob/regex).
3570
- * For globs, uses minimatch's internal conversion.
3624
+ * Converts a regex pattern string (wrapped in `/.../`) to a RegExp instance.
3625
+ *
3626
+ * Glob patterns cannot be converted: minimatch v11 removed `makeRe`, and no
3627
+ * RegExp equivalent exists. Use {@link matchesAnyPattern} or
3628
+ * {@link matchesAnyHostPattern} for glob matching instead; this function is
3629
+ * only for the `/.../` regex form (its internal callers branch on
3630
+ * {@link isRegexPattern} first, so they never hit the glob branch).
3631
+ *
3632
+ * @param pattern The pattern to convert; must be a `/.../` regex pattern.
3633
+ * @returns A compiled RegExp for the pattern.
3571
3634
  */
3572
3635
  function patternToRegExp(pattern) {
3573
3636
  const cached = regExpCache.get(pattern);
3574
3637
  if (cached) return cached;
3575
- let re;
3576
- if (isRegexPattern(pattern)) re = new RegExp(pattern.slice(1, -1));
3577
- else re = minimatch.makeRe(pattern, { dot: true });
3578
- if (!re) throw new Error(`Invalid glob pattern: ${pattern}`);
3638
+ if (!isRegexPattern(pattern)) throw new Error(`Invalid regex pattern: ${pattern}. Glob patterns cannot be converted to RegExp (minimatch v11 removed makeRe); use matchesAnyPattern for glob matching.`);
3639
+ const re = new RegExp(pattern.slice(1, -1));
3579
3640
  regExpCache.set(pattern, re);
3580
3641
  return re;
3581
3642
  }
@@ -3584,18 +3645,20 @@ function patternToRegExp(pattern) {
3584
3645
  * Used to avoid prepending a `/` to inputs that are already full URLs.
3585
3646
  */
3586
3647
  var URL_WITH_PROTOCOL_RE = /^[a-z][a-z0-9+.-]*:\/\//i;
3648
+ function toMatchTarget(path) {
3649
+ const forRegex = URL_WITH_PROTOCOL_RE.test(path) || path.startsWith("/") ? path : `/${path}`;
3650
+ return {
3651
+ forRegex,
3652
+ forGlob: forRegex.replace(/^\//, "")
3653
+ };
3654
+ }
3587
3655
  /**
3588
- * Checks if a given path matches any pattern in the list.
3589
- * For globs, uses minimatch. For regex, uses RegExp.
3656
+ * Checks if a normalized path or URL matches one pattern: a regex wrapped in
3657
+ * `/.../`, or a glob, whose leading `/` is ignored like the path's.
3590
3658
  */
3591
- function matchesAnyPattern(path, patterns) {
3592
- if (!patterns || patterns.length === 0) return false;
3593
- const normalizedPath = URL_WITH_PROTOCOL_RE.test(path) || path.startsWith("/") ? path : `/${path}`;
3594
- return patterns.some((pattern) => {
3595
- if (isRegexPattern(pattern)) return patternToRegExp(pattern).test(normalizedPath);
3596
- const pathForMatch = normalizedPath.replace(/^\//, "");
3597
- return getGlobMatcher(pattern.startsWith("/") ? pattern.slice(1) : pattern).match(pathForMatch);
3598
- });
3659
+ function matchesTarget(target, pattern) {
3660
+ if (isRegexPattern(pattern)) return patternToRegExp(pattern).test(target.forRegex);
3661
+ return getGlobMatcher(pattern.startsWith("/") ? pattern.slice(1) : pattern).match(target.forGlob);
3599
3662
  }
3600
3663
  /**
3601
3664
  * Matches a flat string (hostname, label, etc.) against patterns without any
@@ -3611,42 +3674,65 @@ function matchesAnyHostPattern(value, patterns) {
3611
3674
  return getGlobMatcher(pattern.toLowerCase()).match(normalized);
3612
3675
  });
3613
3676
  }
3614
- /**
3615
- * Extracts the path and query from a URL string (no domain).
3616
- */
3617
- function extractPathAndQuery(url) {
3677
+ function getLinkTargets(url, rootDirectory) {
3678
+ let pathname;
3679
+ let search = "";
3680
+ let basename;
3618
3681
  try {
3619
3682
  const u = new URL(url);
3620
- return u.pathname + (u.search || "");
3683
+ pathname = u.pathname;
3684
+ search = u.search;
3685
+ if (u.protocol === "file:") basename = pathname.split("/").pop() || void 0;
3621
3686
  } catch {
3622
- return url;
3687
+ pathname = url.startsWith("/") ? url : `/${url}`;
3623
3688
  }
3689
+ const absolutePath = toMatchTarget(pathname + search);
3690
+ const relative = rootDirectory && pathname.startsWith(rootDirectory) ? toMatchTarget(pathname.slice(rootDirectory.length) + search) : absolutePath;
3691
+ return {
3692
+ anchored: [toMatchTarget(url), absolutePath],
3693
+ relative,
3694
+ basename: basename ? toMatchTarget(basename) : void 0
3695
+ };
3696
+ }
3697
+ /**
3698
+ * Whether a pattern matches a link. A glob starting with `**\/` means
3699
+ * "anywhere below the scrape root": as an exclude pattern it is matched only
3700
+ * against the path below the root, so a folder name at or above the root
3701
+ * (`/docs-inbox/test`) cannot reject every link. Every other pattern matches
3702
+ * the full URL or the absolute path. Globs also match a `file://` file name.
3703
+ */
3704
+ function matchesLink(targets, pattern, isExclude) {
3705
+ if (isRegexPattern(pattern)) return targets.anchored.some((target) => matchesTarget(target, pattern));
3706
+ return (isExclude && pattern.startsWith("**/") ? [targets.relative] : targets.anchored).some((target) => matchesTarget(target, pattern)) || targets.basename !== void 0 && matchesTarget(targets.basename, pattern);
3624
3707
  }
3625
3708
  /**
3626
- * Determines if a URL should be included based on include/exclude patterns.
3627
- * Exclude patterns take precedence. If no include patterns, all are included by default.
3709
+ * Decides whether a link passes the include and exclude patterns, and why not.
3628
3710
  *
3629
- * If no user exclude patterns are provided, default exclusion patterns are automatically applied.
3630
- * These defaults exclude common documentation files (CHANGELOG.md, LICENSE, etc.) and folders
3631
- * (archives, non-English locales, etc.).
3711
+ * Exclude patterns take precedence; with no include patterns, every link not
3712
+ * excluded is included. When `excludePatterns` is undefined the default
3713
+ * exclusions apply; any list, even an empty one, replaces them.
3632
3714
  *
3633
- * Patterns are matched against both the full URL and the pathname for maximum flexibility:
3634
- * - Full URL: `https://example.com/docs/v3/**` matches `https://example.com/docs/v3/guide`
3635
- * - Pathname: `/docs/v3/**` matches `https://example.com/docs/v3/guide`
3636
- */
3637
- function shouldIncludeUrl(url, includePatterns, excludePatterns) {
3638
- const path = extractPathAndQuery(url);
3639
- const normalizedPath = path.startsWith("/") ? path : `/${path}`;
3640
- let basename;
3641
- if (url.startsWith("file://")) try {
3642
- const u = new URL(url);
3643
- basename = u.pathname ? u.pathname.split("/").pop() : void 0;
3644
- } catch {}
3645
- const stripSlash = (patterns) => patterns?.map((p) => p.startsWith("/") ? p.slice(1) : p);
3646
- const effectiveExcludePatterns = getEffectiveExclusionPatterns(excludePatterns);
3647
- if (matchesAnyPattern(url, effectiveExcludePatterns) || matchesAnyPattern(normalizedPath, effectiveExcludePatterns) || basename && matchesAnyPattern(basename, stripSlash(effectiveExcludePatterns))) return false;
3648
- if (!includePatterns || includePatterns.length === 0) return true;
3649
- return matchesAnyPattern(url, includePatterns) || matchesAnyPattern(normalizedPath, includePatterns) || (basename ? matchesAnyPattern(basename, stripSlash(includePatterns)) : false);
3715
+ * Regexes and globs match the full URL or the absolute path with query; globs
3716
+ * also match a `file://` link's file name. Exclude globs starting with `**\/`
3717
+ * match the path below `rootDirectory` instead, so the root's own folder names
3718
+ * never exclude anything.
3719
+ *
3720
+ * @param url The link: a full URL, or a path relative to a repository root.
3721
+ * @param patterns The include and exclude patterns, and the scrape root folder
3722
+ * (a pathname ending in `/`). Without a root, the whole path is relative.
3723
+ * @returns Why the link is rejected, naming the exclude pattern that matched,
3724
+ * or null when the patterns admit it.
3725
+ */
3726
+ function evaluateUrlPatterns(url, patterns) {
3727
+ const targets = getLinkTargets(url, patterns.rootDirectory);
3728
+ const excludedBy = getEffectiveExclusionPatterns(patterns.excludePatterns).find((pattern) => matchesLink(targets, pattern, true));
3729
+ if (excludedBy !== void 0) return {
3730
+ check: "exclude",
3731
+ pattern: excludedBy
3732
+ };
3733
+ const { includePatterns } = patterns;
3734
+ if (!includePatterns || includePatterns.length === 0) return null;
3735
+ return includePatterns.some((pattern) => matchesLink(targets, pattern, false)) ? null : { check: "include" };
3650
3736
  }
3651
3737
  // src/utils/accessPolicy.ts
3652
3738
  var SPECIAL_USE_IPV4_CIDRS = [
@@ -5296,18 +5382,42 @@ var PageOutcome = /* @__PURE__ */ function(PageOutcome) {
5296
5382
  PageOutcome["Absent"] = "absent";
5297
5383
  /** Fetched successfully but yielded no content. The page exists and is empty. */
5298
5384
  PageOutcome["Empty"] = "empty";
5385
+ /**
5386
+ * The crawl's current options no longer admit this stored page — it now
5387
+ * matches an exclude pattern, say, or sits behind a file-access setting that
5388
+ * was turned off. Never fetched. During a refresh the stored page is deleted.
5389
+ */
5390
+ PageOutcome["Excluded"] = "excluded";
5299
5391
  /** No pipeline can read this content type, so the body was never downloaded. */
5300
5392
  PageOutcome["Skipped"] = "skipped";
5301
5393
  /** Processing failed and the error was ignored under `ignoreErrors`. */
5302
5394
  PageOutcome["Failed"] = "failed";
5303
5395
  return PageOutcome;
5304
5396
  }({});
5397
+ // src/scraper/utils/linkRejection.ts
5398
+ /**
5399
+ * Describes why a link was rejected, for logs and job warnings.
5400
+ *
5401
+ * @param rejection The rejection to describe.
5402
+ * @returns A short phrase such as ``excluded by pattern `**\/test/**` ``.
5403
+ */
5404
+ function describeLinkRejection(rejection) {
5405
+ switch (rejection.check) {
5406
+ case "scope": return `outside the "${rejection.scope}" scope`;
5407
+ case "exclude": return `excluded by pattern \`${rejection.pattern}\``;
5408
+ case "include": return "matching no include pattern";
5409
+ case "llms-companion": return "an llms.txt file, read only for its links";
5410
+ case "hidden": return "hidden";
5411
+ case "symlink": return "a symbolic link";
5412
+ case "gitignore": return "ignored by .gitignore";
5413
+ }
5414
+ }
5305
5415
  // src/scraper/utils/llmsTxtParser.ts
5306
5416
  var emptyLlmsTxtResult = () => ({
5307
5417
  sections: [],
5308
5418
  links: []
5309
5419
  });
5310
- var markdownLinkPattern = /^\s*[-*+•]\s+\[([^\]\n]+)]\(([^)\s]+)\)\s*(?::\s*(.+?)\s*)?$/;
5420
+ var markdownLinkPattern = /^\s*[-*+•]\s+\[([^\]\n]+)]\(([^)\s]+)\)\s*(?::(.+))?$/;
5311
5421
  var htmlDocumentPattern = /^\s*<(?:!doctype\s+html|html|body|head)(?:\s|>)/i;
5312
5422
  /**
5313
5423
  * Unwraps llms.txt content that a browser rendered as HTML.
@@ -5334,18 +5444,41 @@ function unwrapPlainTextPre(content) {
5334
5444
  return pre.text();
5335
5445
  }
5336
5446
  /**
5337
- * Returns true when a URL points to an llms.txt meta-file.
5447
+ * Returns the lower-cased last segment of a URL's path.
5338
5448
  * @param url The URL to inspect.
5339
- * @returns Whether the URL path basename is exactly llms.txt.
5449
+ * @returns The basename, or undefined for an unparsable URL or an empty path.
5340
5450
  */
5341
- function isLlmsTxtUrl(url) {
5451
+ function pathBasename(url) {
5342
5452
  try {
5343
- return new URL(url).pathname.split("/").filter(Boolean).at(-1)?.toLowerCase() === "llms.txt";
5453
+ return new URL(url).pathname.split("/").filter(Boolean).at(-1)?.toLowerCase();
5344
5454
  } catch {
5345
- return false;
5455
+ return;
5346
5456
  }
5347
5457
  }
5348
5458
  /**
5459
+ * Returns true when a URL points to an llms.txt meta-file.
5460
+ * @param url The URL to inspect.
5461
+ * @returns Whether the URL path basename is exactly llms.txt.
5462
+ */
5463
+ function isLlmsTxtUrl(url) {
5464
+ return pathBasename(url) === "llms.txt";
5465
+ }
5466
+ /**
5467
+ * Returns true when a URL points to a companion of llms.txt, such as
5468
+ * `llms-full.txt`, `llms-small.txt`, `llms-medium.txt` or `llms-ctx.txt`.
5469
+ *
5470
+ * The llms.txt proposal defines none of these. They are conventions that
5471
+ * documentation generators follow: the site's docs, complete, abridged or
5472
+ * expanded from the index, joined into one Markdown document whatever content
5473
+ * type the server sends.
5474
+ *
5475
+ * @param url The URL to inspect.
5476
+ * @returns Whether the URL path basename is `llms-<anything>.txt`.
5477
+ */
5478
+ function isLlmsTxtCompanionUrl(url) {
5479
+ return /^llms-.+\.txt$/.test(pathBasename(url) ?? "");
5480
+ }
5481
+ /**
5349
5482
  * Parses llms.txt Markdown into project metadata and curated links.
5350
5483
  * @param content The llms.txt Markdown content.
5351
5484
  * @returns Parsed llms.txt metadata and links, or an empty result for invalid content.
@@ -5374,7 +5507,7 @@ function parseLlmsTxt(content) {
5374
5507
  collectingSummary = false;
5375
5508
  continue;
5376
5509
  }
5377
- const h2Match = /^##\s+(.+?)\s*$/.exec(line);
5510
+ const h2Match = /^##\s(.+)$/.exec(line);
5378
5511
  if (h2Match) {
5379
5512
  collectingSummary = false;
5380
5513
  const title = h2Match[1].trim();
@@ -5449,6 +5582,22 @@ function computeBaseDirectory(pathname) {
5449
5582
  return `${pathname}/`;
5450
5583
  }
5451
5584
  /**
5585
+ * Returns the folder that root-relative exclude patterns are measured from.
5586
+ *
5587
+ * A URL naming a page or file (see {@link isFileLikePath}) yields its parent
5588
+ * folder; any other URL is a folder itself, as {@link computeBaseDirectory}
5589
+ * treats it. So `file:///docs/test` and `https://example.com/old/guide.html`
5590
+ * yield `/docs/test/` and `/old/`.
5591
+ *
5592
+ * @param baseUrl The scope base URL: the start URL after any depth-0 redirect.
5593
+ * @returns The root folder's pathname, always ending in `/`.
5594
+ */
5595
+ function patternRootDirectory(baseUrl) {
5596
+ const pathname = baseUrl.pathname;
5597
+ if (isFileLikePath(pathname)) return pathname.replace(/\/[^/]*$/, "/");
5598
+ return computeBaseDirectory(pathname);
5599
+ }
5600
+ /**
5452
5601
  * Returns true when `childPath` is the same as `parentPath` or is a path-descendant of it.
5453
5602
  * `parentPath` is normalized to end with "/" before comparison so directory semantics apply.
5454
5603
  *
@@ -5546,8 +5695,26 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5546
5695
  /** URLs admitted to the queue, clamped at where the crawl will stop. */
5547
5696
  effectiveTotal = 0;
5548
5697
  canonicalBaseUrl;
5698
+ /**
5699
+ * The start URL after a depth-0 redirect, path included, when a strategy
5700
+ * follows one. Patterns are measured from its directory; the scope keeps
5701
+ * the requested path in {@link canonicalBaseUrl}.
5702
+ */
5703
+ redirectedStartUrl;
5704
+ /**
5705
+ * The start page as this crawl resolved it: normalized URLs the requested
5706
+ * root was stored under, and a promise that settles once the root has been
5707
+ * processed. A start URL that redirects is stored under its target, which
5708
+ * the patterns must not judge either.
5709
+ */
5710
+ startPage = {
5711
+ urls: /* @__PURE__ */ new Set(),
5712
+ settled: Promise.resolve()
5713
+ };
5549
5714
  completedChildPageAttempts = 0;
5550
5715
  failedChildPages = 0;
5716
+ /** Rejected links during the current crawl, keyed by their described reason. */
5717
+ linkRejections = /* @__PURE__ */ new Map();
5551
5718
  /**
5552
5719
  * The point at which the crawl stops, expressed in processed items.
5553
5720
  *
@@ -5614,8 +5781,9 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5614
5781
  return this.canonicalBaseUrl ?? new URL$1(options.url);
5615
5782
  }
5616
5783
  /**
5617
- * Determines if a URL should be processed based on scope and include/exclude patterns in ScraperOptions.
5618
- * Scope is checked first, then patterns.
5784
+ * Applies the checks that depend on where the crawl started: the llms.txt
5785
+ * rule and the scope. Patterns are left to {@link getExclusion}, so every
5786
+ * link is judged by them in one place.
5619
5787
  *
5620
5788
  * `internalAllowedFileRoots` opts a queue item out of the protocol-strict
5621
5789
  * scope check: when a web URL has been accepted as an archive root and the
@@ -5627,18 +5795,147 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5627
5795
  * sandbox via this path. Downstream `resolveFileAccess` enforces the same
5628
5796
  * rule, but rejecting early here keeps unrelated `file://` URLs out of the
5629
5797
  * crawl queue entirely.
5798
+ *
5799
+ * @param url The discovered URL.
5800
+ * @param options Scraper options for this crawl.
5801
+ * @param context Internal allowlist roots the item carries.
5802
+ * @returns Why the URL is rejected, or null when it passes.
5630
5803
  */
5631
- shouldProcessUrl(url, options, context = {}) {
5632
- if (isLlmsTxtUrl(url)) return false;
5633
- if (!(url.startsWith("file://") && isFileUrlInsideRoots(url, context.internalAllowedFileRoots))) {
5634
- const scope = options.scope ?? "subpages";
5635
- try {
5636
- if (!isInScope(this.getScopeBaseUrl(options), new URL$1(url), scope)) return false;
5637
- } catch {
5638
- return false;
5639
- }
5804
+ getScopeRejection(url, options, context = {}) {
5805
+ if (isLlmsTxtUrl(url) || isLlmsTxtCompanionUrl(url)) return { check: "llms-companion" };
5806
+ if (findContainingFileRoot(url, context.internalAllowedFileRoots) !== void 0) return null;
5807
+ const scope = options.scope ?? "subpages";
5808
+ try {
5809
+ return isInScope(this.getScopeBaseUrl(options), new URL$1(url), scope) ? null : {
5810
+ check: "scope",
5811
+ scope
5812
+ };
5813
+ } catch {
5814
+ return {
5815
+ check: "scope",
5816
+ scope
5817
+ };
5640
5818
  }
5641
- return shouldIncludeUrl(url, options.includePatterns, options.excludePatterns);
5819
+ }
5820
+ /**
5821
+ * Admission hook: decides whether the crawl's current options shut `url` out.
5822
+ *
5823
+ * Runs at enqueue, on every discovered link that passed
5824
+ * {@link getScopeRejection}, and at dequeue on refresh items — stored pages,
5825
+ * which carry a `pageId` and reach the queue without passing any filter. A
5826
+ * stored page that is excluded is not fetched: it is reported as
5827
+ * {@link PageOutcome.Excluded} and the store deletes it. Without this, a page
5828
+ * that a crawl would no longer admit stays in the index after the options
5829
+ * change, and strategies that want it gone have to pretend it answered 404.
5830
+ *
5831
+ * This is the only place the include and exclude patterns are applied. The
5832
+ * base implementation matches them against the URL, measuring match-anywhere
5833
+ * exclude globs from the scrape root. Scope is deliberately left to
5834
+ * {@link getScopeRejection}: it is measured from the root after its
5835
+ * redirects, which a refresh only learns once the root has been fetched, so
5836
+ * judging stored pages by it could delete pages that are in scope. Overrides
5837
+ * add the filters a strategy applies while discovering pages, or judge a URL
5838
+ * by another path, and call `super` or `evaluateUrlPatterns`.
5839
+ *
5840
+ * The URL the user asked for is never judged by this hook, during a scrape
5841
+ * or a refresh, matching a scrape where the start URL is always processed.
5842
+ *
5843
+ * @param url The URL to judge.
5844
+ * @param options Scraper options for this crawl.
5845
+ * @param context Internal allowlist roots the item carries. An archive
5846
+ * member below one is measured from that root rather than the scrape root.
5847
+ * @returns Why the crawl must not admit the URL, or null when it may.
5848
+ */
5849
+ async getExclusion(url, options, context) {
5850
+ return evaluateUrlPatterns(url, {
5851
+ includePatterns: options.includePatterns,
5852
+ excludePatterns: options.excludePatterns,
5853
+ rootDirectory: this.getPatternRootDirectory(url, options, context)
5854
+ });
5855
+ }
5856
+ /**
5857
+ * Returns the directory match-anywhere exclude globs are measured from for
5858
+ * `url`: the internal root holding it, for an archive member, or else the
5859
+ * directory of the start URL after any depth-0 redirect.
5860
+ *
5861
+ * @param url The URL to judge.
5862
+ * @param options Scraper options for this crawl.
5863
+ * @param context Internal allowlist roots the item carries.
5864
+ * @returns An absolute path ending in `/`.
5865
+ */
5866
+ getPatternRootDirectory(url, options, context) {
5867
+ const archiveRoot = findContainingFileRoot(url, context.internalAllowedFileRoots);
5868
+ return archiveRoot ? pathToFileURL(`${archiveRoot}/`).pathname : patternRootDirectory(this.redirectedStartUrl ?? this.getScopeBaseUrl(options));
5869
+ }
5870
+ /**
5871
+ * Decides whether a discovered link joins the queue, applying the scope
5872
+ * checks and then {@link getExclusion}. A rejected link is logged with its
5873
+ * reason and counted for the scrape summary.
5874
+ *
5875
+ * @param url The discovered URL.
5876
+ * @param options Scraper options for this crawl.
5877
+ * @param context Internal allowlist roots the item carries.
5878
+ * @returns True when the link may be queued.
5879
+ */
5880
+ async admitLink(url, options, context = {}) {
5881
+ const rejection = this.getScopeRejection(url, options, context) ?? await this.getExclusion(url, options, context);
5882
+ if (!rejection) return true;
5883
+ this.recordRejection(rejection, `Skipping link`, url);
5884
+ return false;
5885
+ }
5886
+ /** Logs a rejection at debug level and counts it for the scrape summary. */
5887
+ recordRejection(rejection, action, url) {
5888
+ const reason = describeLinkRejection(rejection);
5889
+ const tally = this.linkRejections.get(reason);
5890
+ if (tally) tally.count++;
5891
+ else this.linkRejections.set(reason, {
5892
+ rejection,
5893
+ count: 1
5894
+ });
5895
+ logger.debug(`${action} ${reason}: ${url}`);
5896
+ }
5897
+ /**
5898
+ * Decides whether a page stored under `urls` is one the options do not admit.
5899
+ *
5900
+ * A stored page has two URLs when its content came from a representation:
5901
+ * the one it is fetched from (`/guide/index.html.md`) and the identity it is
5902
+ * recorded under (`/guide`). The crawl may have admitted it by either, so the
5903
+ * page is excluded only when the options admit neither. The start page is
5904
+ * never excluded, under the URL the scrape started from or wherever that URL
5905
+ * redirected; the latter is only known once the root has been processed, so
5906
+ * a page about to be excluded waits for it.
5907
+ *
5908
+ * A refresh asks this of every stored page before fetching it, and a crawl
5909
+ * asks it of every page stored under another URL than the one it queued, so
5910
+ * a scrape and a refresh store the same pages.
5911
+ *
5912
+ * @param urls The URLs the page is stored under.
5913
+ * @param item The queue item the page came from.
5914
+ * @param options Scraper options for this crawl.
5915
+ * @returns True when the page is not to be stored, or is to be deleted.
5916
+ */
5917
+ async isStoredPageExcluded(urls, item, options) {
5918
+ if (urls.some((url) => this.isRequestedRoot({
5919
+ ...item,
5920
+ url
5921
+ }, options))) return false;
5922
+ const context = { internalAllowedFileRoots: item.internalAllowedFileRoots };
5923
+ const judge = async () => {
5924
+ let rejection = null;
5925
+ for (const url of urls) {
5926
+ rejection = await this.getExclusion(url, options, context);
5927
+ if (!rejection) return null;
5928
+ }
5929
+ return rejection;
5930
+ };
5931
+ if (!await judge()) return false;
5932
+ await this.startPage.settled;
5933
+ const normalizerOptions = this.getUrlNormalizerOptions(options);
5934
+ if (urls.some((url) => this.startPage.urls.has(normalizeUrl(url, normalizerOptions)))) return false;
5935
+ const rejection = await judge();
5936
+ if (!rejection) return false;
5937
+ this.recordRejection(rejection, "Excluding stored page", urls[0]);
5938
+ return true;
5642
5939
  }
5643
5940
  shouldCountTowardFailureThreshold(item, options, result) {
5644
5941
  if (item.fromLlmsTxt) return false;
@@ -5743,6 +6040,12 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5743
6040
  }
5744
6041
  };
5745
6042
  try {
6043
+ if (item.pageId !== void 0 && await this.isStoredPageExcluded([item.url, ...item.identityUrl ? [item.identityUrl] : []], item, options)) {
6044
+ throwIfCrawlAborted();
6045
+ logger.debug(`Page excluded by the scrape options: ${item.url}`);
6046
+ await report(PageOutcome.Excluded, { deleted: true });
6047
+ return [];
6048
+ }
5746
6049
  const result = await this.processItem(item, options, signal);
5747
6050
  throwIfCrawlAborted();
5748
6051
  if (result.status === FetchStatus.NOT_MODIFIED) {
@@ -5786,6 +6089,17 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5786
6089
  }
5787
6090
  const finalUrl = this.canonicalizeStoredUrl(result.url || item.url, options);
5788
6091
  this.visited.add(normalizeUrl(finalUrl, this.getUrlNormalizerOptions(options)));
6092
+ if (this.isRequestedRoot(item, options)) this.startPage.urls.add(normalizeUrl(finalUrl, this.getUrlNormalizerOptions(options)));
6093
+ const storedUrls = [result.contentUrl ?? (result.url && result.url !== finalUrl ? result.url : void 0) ?? finalUrl, finalUrl];
6094
+ if (!this.isRequestedRoot(item, options) && !storedUrls.includes(item.url) && await this.isStoredPageExcluded(storedUrls, item, options)) {
6095
+ throwIfCrawlAborted();
6096
+ logger.debug(`Redirect target excluded by the scrape options: ${finalUrl}`);
6097
+ await report(PageOutcome.Excluded, item.pageId !== void 0 ? {
6098
+ currentUrl: finalUrl,
6099
+ deleted: true
6100
+ } : { currentUrl: finalUrl });
6101
+ return [];
6102
+ }
5789
6103
  const producedContent = !!result.content?.textContent?.trim();
5790
6104
  if (result.content && producedContent) {
5791
6105
  await report(PageOutcome.Stored, {
@@ -5830,20 +6144,23 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5830
6144
  ensureFailureRateWithinThreshold();
5831
6145
  throwIfCrawlAborted();
5832
6146
  const childDepth = item.depth + 1;
5833
- const linkQueueItems = (childDepth > maxDepth ? [] : nextItems).map((value) => {
6147
+ const context = { internalAllowedFileRoots };
6148
+ const linkQueueItems = (await Promise.all((childDepth > maxDepth ? [] : nextItems).map(async (value) => {
6149
+ let targetUrl;
5834
6150
  try {
5835
- const targetUrl = new URL$1(value, linkBaseUrl);
5836
- if (!this.shouldProcessUrl(targetUrl.href, options, { internalAllowedFileRoots })) return null;
5837
- return {
5838
- url: targetUrl.href,
5839
- depth: childDepth,
5840
- ...internalAllowedFileRoots ? { internalAllowedFileRoots } : {}
5841
- };
6151
+ targetUrl = new URL$1(value, linkBaseUrl);
5842
6152
  } catch (_error) {
5843
6153
  logger.warn(`❌ Invalid URL: ${value}`);
6154
+ return null;
5844
6155
  }
5845
- return null;
5846
- }).filter((item) => item !== null);
6156
+ if (!await this.admitLink(targetUrl.href, options, context)) return null;
6157
+ return {
6158
+ url: targetUrl.href,
6159
+ depth: childDepth,
6160
+ ...internalAllowedFileRoots ? { internalAllowedFileRoots } : {}
6161
+ };
6162
+ }))).filter((candidate) => candidate !== null);
6163
+ throwIfCrawlAborted();
5847
6164
  return [...result.queueItems ?? [], ...linkQueueItems];
5848
6165
  } catch (error) {
5849
6166
  if (error instanceof FailureThresholdExceededError || error instanceof CancellationError) throw error;
@@ -5881,6 +6198,7 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5881
6198
  }
5882
6199
  async scrape(options, progressCallback, signal) {
5883
6200
  this.visited.clear();
6201
+ this.linkRejections = /* @__PURE__ */ new Map();
5884
6202
  this.storedIdentities.clear();
5885
6203
  this.pageCount = 0;
5886
6204
  this.pagesIndexed = 0;
@@ -5889,12 +6207,13 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5889
6207
  const initialQueue = options.initialQueue || [];
5890
6208
  const isRefreshMode = initialQueue.length > 0;
5891
6209
  this.canonicalBaseUrl = new URL$1(options.url);
6210
+ this.redirectedStartUrl = void 0;
5892
6211
  let baseUrl = this.canonicalBaseUrl;
5893
6212
  const queue = [];
5894
6213
  const normalizedRootUrl = normalizeUrl(options.url, this.getUrlNormalizerOptions(options));
5895
6214
  if (isRefreshMode) {
5896
6215
  logger.debug(`Starting refresh mode with ${initialQueue.length} pre-populated pages`);
5897
- for (const item of initialQueue) {
6216
+ for (const { internalAllowedFileRoots: _callerRoots, ...item } of initialQueue) {
5898
6217
  const normalizedUrl = normalizeUrl(item.url, this.getUrlNormalizerOptions(options));
5899
6218
  if (!this.visited.has(normalizedUrl)) {
5900
6219
  this.visited.add(normalizedUrl);
@@ -5902,13 +6221,22 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5902
6221
  }
5903
6222
  }
5904
6223
  }
5905
- if (!this.visited.has(normalizedRootUrl)) {
6224
+ const storedRootIndex = queue.findIndex((item) => normalizeUrl(item.url, this.getUrlNormalizerOptions(options)) === normalizedRootUrl);
6225
+ if (storedRootIndex > 0) queue.unshift(...queue.splice(storedRootIndex, 1));
6226
+ else if (storedRootIndex === -1) {
5906
6227
  this.visited.add(normalizedRootUrl);
5907
6228
  queue.unshift({
5908
6229
  url: options.url,
5909
6230
  depth: 0
5910
6231
  });
5911
6232
  }
6233
+ let settleStartPage = () => {};
6234
+ this.startPage = {
6235
+ urls: /* @__PURE__ */ new Set(),
6236
+ settled: new Promise((resolve) => {
6237
+ settleStartPage = resolve;
6238
+ })
6239
+ };
5912
6240
  const maxPages = options.maxPages ?? this.config.scraper.maxPages;
5913
6241
  const maxConcurrency = options.maxConcurrency ?? this.config.scraper.maxConcurrency;
5914
6242
  this.totalDiscovered = queue.length;
@@ -5932,7 +6260,9 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5932
6260
  if (!item) break;
5933
6261
  const seq = nextSeq++;
5934
6262
  baseUrl = this.canonicalBaseUrl ?? baseUrl;
5935
- running.set(seq, this.processQueueItem(item, baseUrl, options, progressCallback, crawl, items.signal).then((offered) => {
6263
+ const processing = this.processQueueItem(item, baseUrl, options, progressCallback, crawl, items.signal);
6264
+ if (seq === 0) processing.then(settleStartPage, settleStartPage);
6265
+ running.set(seq, processing.then((offered) => {
5936
6266
  finished.set(seq, offered);
5937
6267
  return seq;
5938
6268
  }));
@@ -5952,6 +6282,7 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5952
6282
  } finally {
5953
6283
  signal?.removeEventListener("abort", abortItems);
5954
6284
  }
6285
+ return { rejections: [...this.linkRejections.values()].sort((a, b) => b.count - a.count) };
5955
6286
  }
5956
6287
  /**
5957
6288
  * Cleanup resources used by this strategy.
@@ -5960,24 +6291,24 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5960
6291
  async cleanup() {}
5961
6292
  };
5962
6293
  /**
5963
- * Returns true if `url` is a `file://` URL whose resolved filesystem path lies
5964
- * inside one of the supplied internal roots. Used by the queue-time scope
5965
- * bypass for archive-member URLs so that arbitrary `file://` links injected
5966
- * into archive content cannot escape the archive sandbox.
6294
+ * Finds the internal root that holds a `file://` URL's resolved filesystem
6295
+ * path. Used by the queue-time scope bypass for archive-member URLs, so that
6296
+ * arbitrary `file://` links injected into archive content cannot escape the
6297
+ * archive sandbox, and to measure exclude patterns from the archive's root.
6298
+ *
6299
+ * @returns The resolved root, or undefined when no root holds the URL.
5967
6300
  */
5968
- function isFileUrlInsideRoots(url, roots) {
5969
- if (!roots || roots.length === 0) return false;
6301
+ function findContainingFileRoot(url, roots) {
6302
+ if (!roots || roots.length === 0 || !url.startsWith("file://")) return void 0;
5970
6303
  let target;
5971
6304
  try {
5972
6305
  target = path.resolve(fileUrlToPathLoose(url));
5973
6306
  } catch {
5974
- return false;
6307
+ return;
5975
6308
  }
5976
- return roots.some((root) => {
5977
- const resolvedRoot = path.resolve(root);
5978
- if (resolvedRoot === target) return true;
5979
- const relative = path.relative(resolvedRoot, target);
5980
- return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
6309
+ return roots.map((root) => path.resolve(root)).find((root) => {
6310
+ const relative = path.relative(root, target);
6311
+ return !relative.startsWith("..") && !path.isAbsolute(relative);
5981
6312
  });
5982
6313
  }
5983
6314
  // src/utils/dom.ts
@@ -6156,140 +6487,105 @@ var MinimumChunkSizeError = class extends SplitterError {
6156
6487
  * Generic error for content splitting failures
6157
6488
  */
6158
6489
  var ContentSplitterError = class extends SplitterError {};
6159
- // src/splitter/splitters/CodeContentSplitter.ts
6490
+ // src/splitter/splitters/fenceState.ts
6160
6491
  /**
6161
- * Splits code content while preserving language information and formatting.
6162
- * Uses line boundaries for splitting and ensures each chunk is properly
6163
- * wrapped with language-specific code block markers.
6492
+ * Tracks whether a markdown string ends inside an open fenced code block. Used
6493
+ * by content splitters to avoid cutting chunks in the middle of a fence, which
6494
+ * would leave one chunk with an unmatched opener and the next chunk with an
6495
+ * unmatched closer.
6496
+ *
6497
+ * Follows CommonMark fence semantics for the cases that matter to us: a fence
6498
+ * is a line whose only leading non-whitespace content is three or more
6499
+ * identical backticks or three or more identical tildes. The closing fence
6500
+ * must use the same character and at least as many of them as the opener.
6501
+ * Backticks and tildes do not pair across types.
6164
6502
  */
6165
- var CodeContentSplitter = class {
6166
- options;
6167
- constructor(options) {
6168
- this.options = options;
6169
- }
6170
- async split(content) {
6171
- const infoString = (content.match(/^```([^\n]*)\n/)?.[1] ?? "").trimEnd();
6172
- const lines = content.replace(/^```[^\n]*\n/, "").replace(/```\s*$/, "").split("\n");
6173
- const chunks = [];
6174
- let currentChunkLines = [];
6175
- for (const line of lines) {
6176
- const singleLineSize = this.wrap(line, infoString).length;
6177
- if (singleLineSize > this.options.chunkSize) throw new MinimumChunkSizeError(singleLineSize, this.options.chunkSize);
6178
- currentChunkLines.push(line);
6179
- if (this.wrap(currentChunkLines.join("\n"), infoString).length > this.options.chunkSize && currentChunkLines.length > 1) {
6180
- const lastLine = currentChunkLines.pop();
6181
- chunks.push(this.wrap(currentChunkLines.join("\n"), infoString));
6182
- currentChunkLines = [lastLine];
6183
- }
6184
- }
6185
- if (currentChunkLines.length > 0) chunks.push(this.wrap(currentChunkLines.join("\n"), infoString));
6186
- return chunks;
6187
- }
6188
- wrap(content, infoString) {
6189
- return `\`\`\`${infoString || ""}\n${content.replace(/\n+$/, "")}\n\`\`\``;
6190
- }
6191
- };
6192
- // src/splitter/splitters/fenceState.ts
6193
6503
  var FENCE_PREFIX = "[ \\t]*(?:>[ \\t]*)*";
6194
- var FENCE_OPENER = new RegExp(`^${FENCE_PREFIX}(\`{3,}|~{3,})`);
6195
- function splitLinesWithOffsets(text) {
6196
- const lines = [];
6197
- let offset = 0;
6198
- while (offset <= text.length) {
6199
- const nlIndex = text.indexOf("\n", offset);
6200
- if (nlIndex === -1) {
6201
- if (offset < text.length) lines.push({
6202
- content: text.slice(offset),
6203
- offset,
6204
- newlineLength: 0
6205
- });
6206
- return lines;
6207
- }
6208
- lines.push({
6209
- content: text.slice(offset, nlIndex),
6210
- offset,
6211
- newlineLength: 1
6212
- });
6213
- offset = nlIndex + 1;
6214
- }
6215
- return lines;
6216
- }
6217
- function isClosingFence(line, delimiter, openerCount) {
6218
- return new RegExp(`^${FENCE_PREFIX}\\${delimiter}{${openerCount},}[ \\t]*$`).test(line);
6219
- }
6504
+ var FENCE_OPENER = new RegExp(`^(${FENCE_PREFIX})(\`{3,}|~{3,})`);
6220
6505
  /**
6221
- * Scan the input and return non-overlapping fence regions. Each region covers
6222
- * the line containing the opener through the line containing the matching
6223
- * closer (inclusive of trailing newlines). Unclosed openers produce a region
6224
- * extending to the end of input.
6506
+ * Reads a fence opener from one line.
6507
+ *
6508
+ * @param line A single line, without its newline.
6509
+ * @returns The opener's parts, or null when the line does not open a fence.
6225
6510
  */
6226
- function findFenceRegions(text) {
6227
- const regions = [];
6228
- const lines = splitLinesWithOffsets(text);
6229
- let i = 0;
6230
- while (i < lines.length) {
6231
- const opener = FENCE_OPENER.exec(lines[i].content);
6232
- if (!opener) {
6233
- i += 1;
6234
- continue;
6235
- }
6236
- const delimiter = opener[1][0];
6237
- const count = opener[1].length;
6238
- const startOffset = lines[i].offset;
6239
- let closerLineIndex = -1;
6240
- for (let j = i + 1; j < lines.length; j++) if (isClosingFence(lines[j].content, delimiter, count)) {
6241
- closerLineIndex = j;
6242
- break;
6243
- }
6244
- if (closerLineIndex === -1) {
6245
- regions.push({
6246
- startOffset,
6247
- endOffset: text.length
6248
- });
6249
- break;
6250
- }
6251
- const closerLine = lines[closerLineIndex];
6252
- const endOffset = closerLine.offset + closerLine.content.length + closerLine.newlineLength;
6253
- regions.push({
6254
- startOffset,
6255
- endOffset
6256
- });
6257
- i = closerLineIndex + 1;
6258
- }
6259
- return regions;
6511
+ function parseFenceOpener(line) {
6512
+ const match = FENCE_OPENER.exec(line);
6513
+ if (!match) return null;
6514
+ return {
6515
+ prefix: match[1],
6516
+ delimiter: match[2][0],
6517
+ length: match[2].length
6518
+ };
6260
6519
  }
6261
6520
  /**
6262
- * Returns true if `chunk` ends while inside an open fence — i.e. its triple-
6263
- * backtick/tilde count is odd in a way that leaves a dangling opener.
6521
+ * Builds the pattern for the line that closes a fence: the same character, at
6522
+ * least as many of them, and as permissive about the prefix as the opener.
6264
6523
  */
6265
- function hasOpenFenceAtEnd(chunk) {
6266
- const regions = findFenceRegions(chunk);
6267
- if (regions.length === 0) return false;
6268
- const last = regions[regions.length - 1];
6269
- if (last.endOffset !== chunk.length) return false;
6270
- const lines = splitLinesWithOffsets(chunk.slice(last.startOffset));
6271
- if (lines.length < 2) return true;
6272
- const opener = FENCE_OPENER.exec(lines[0].content);
6273
- if (!opener) return false;
6274
- return !isClosingFence(lines[lines.length - 1].content, opener[1][0], opener[1].length);
6524
+ function closingFencePattern(opener) {
6525
+ return new RegExp(`^${FENCE_PREFIX}\\${opener.delimiter}{${opener.length},}[ \\t]*$`);
6275
6526
  }
6527
+ /**
6528
+ * Follows fence state across consecutive pieces of one text.
6529
+ *
6530
+ * Callers that join pieces in order can ask whether the text so far ends
6531
+ * inside a fence without rescanning it, which keeps a document with a long or
6532
+ * unclosed fence linear instead of quadratic.
6533
+ */
6534
+ var FenceTracker = class {
6535
+ /** Matches the line that closes the open fence, or null while none is open. */
6536
+ closer = null;
6537
+ partialLine = "";
6538
+ /**
6539
+ * Adds the next piece of the text.
6540
+ *
6541
+ * @param text The piece, joined directly after the previous one.
6542
+ */
6543
+ feed(text) {
6544
+ const lines = `${this.partialLine}${text}`.split("\n");
6545
+ this.partialLine = lines.pop() ?? "";
6546
+ for (const line of lines) this.closer = this.next(this.closer, line);
6547
+ }
6548
+ /**
6549
+ * Reports whether the text fed so far ends inside an open fence. A trailing
6550
+ * line without its newline counts as a whole line.
6551
+ *
6552
+ * @returns True when a fence is open at the end of the text.
6553
+ */
6554
+ isOpen() {
6555
+ return (this.partialLine ? this.next(this.closer, this.partialLine) : this.closer) !== null;
6556
+ }
6557
+ next(closer, line) {
6558
+ if (closer === null) {
6559
+ const opener = parseFenceOpener(line);
6560
+ return opener ? closingFencePattern(opener) : null;
6561
+ }
6562
+ return closer.test(line) ? null : closer;
6563
+ }
6564
+ };
6276
6565
  // src/splitter/splitters/TextContentSplitter.ts
6277
6566
  /**
6278
6567
  * Splits text content using a hierarchical approach:
6279
6568
  * 1. Try splitting by paragraphs (double newlines)
6280
- * 2. If chunks still too large, split by single newlines
6281
- * 3. Finally, use word boundaries via LangChain's splitter
6569
+ * 2. If chunks still too large, split by single newlines and merge them back
6570
+ * up to the chunk size
6571
+ * 3. Split only the lines that are still too large, at word boundaries
6282
6572
  *
6283
- * Across all strategies the splitter preserves fenced code block balance: if
6284
- * splitting would leave a chunk ending inside an open ``` or ~~~ fence, that
6285
- * chunk is merged with the following chunk until the fence closes. When this
6286
- * merging forces a chunk past `chunkSize`, the splitter accepts the oversize
6287
- * chunk and emits a warning rather than break the fence.
6573
+ * Text is split to stay within `chunkSize`. Across all strategies the splitter
6574
+ * also preserves fenced code block balance: a chunk never ends inside an open
6575
+ * ``` or ~~~ fence. A fenced block stays whole up to `maxChunkSize`, even when
6576
+ * that is larger than `chunkSize`. A block larger than `maxChunkSize` is cut at
6577
+ * line boundaries. With `rewrapFences`, each piece is closed and reopened with
6578
+ * the block's own opener line, the same way the Markdown code splitter re-wraps
6579
+ * a long code block; without it, nothing is added and the chunks join back to
6580
+ * the input. No chunk exceeds `maxChunkSize`, because an oversized chunk cannot
6581
+ * be embedded.
6288
6582
  */
6289
6583
  var TextContentSplitter = class {
6290
6584
  options;
6585
+ maxChunkSize;
6291
6586
  constructor(options) {
6292
6587
  this.options = options;
6588
+ this.maxChunkSize = Math.max(options.maxChunkSize ?? 0, options.chunkSize);
6293
6589
  }
6294
6590
  /**
6295
6591
  * Splits text content into chunks while trying to preserve semantic boundaries.
@@ -6298,28 +6594,38 @@ var TextContentSplitter = class {
6298
6594
  */
6299
6595
  async split(content) {
6300
6596
  if (content.length <= this.options.chunkSize) return [content];
6301
- const longestWord = content.split(/\s+/).reduce((max, word) => word.length > max.length ? word : max);
6302
- if (longestWord.length > this.options.chunkSize) throw new MinimumChunkSizeError(longestWord.length, this.options.chunkSize);
6303
- const paragraphChunks = this.mergeForFenceBalance(this.splitByParagraphs(content), "");
6597
+ const paragraphChunks = this.mergeForFenceBalance(this.splitByParagraphs(content));
6304
6598
  if (this.areChunksValid(paragraphChunks)) return paragraphChunks;
6305
- const lineChunks = this.mergeForFenceBalance(this.splitByLines(content), "");
6306
- if (this.areChunksValid(lineChunks)) return this.mergeChunks(lineChunks, "");
6307
- const wordChunks = this.mergeForFenceBalance(await this.splitByWords(content), " ");
6308
- const merged = this.mergeChunks(wordChunks, " ");
6309
- this.warnOversize(merged);
6310
- return merged;
6599
+ const units = this.mergeForFenceBalance(this.splitByLines(content)).flatMap((unit) => this.fitUnit(unit));
6600
+ return this.mergeChunks(units);
6601
+ }
6602
+ /**
6603
+ * Returns a line unit whole when it fits, or the pieces it is cut into. A
6604
+ * unit is either one fenced block, which may use up to `maxChunkSize`, or
6605
+ * one line with no fence in it, which is held to `chunkSize`.
6606
+ */
6607
+ fitUnit(unit) {
6608
+ if (unit.length <= this.options.chunkSize) return [unit];
6609
+ const firstLineEnd = unit.indexOf("\n");
6610
+ const opener = firstLineEnd === -1 ? null : parseFenceOpener(unit.slice(0, firstLineEnd));
6611
+ if (opener === null) return splitLongLine(unit, this.options.chunkSize, this.maxChunkSize);
6612
+ if (unit.length <= this.maxChunkSize) return [unit];
6613
+ return this.splitFencedBlock(unit, unit.slice(0, firstLineEnd + 1), opener);
6311
6614
  }
6312
6615
  /**
6313
6616
  * Walks `chunks` left to right and merges adjacent chunks whenever the running
6314
6617
  * buffer ends inside an open fenced code block. Guarantees that every emitted
6315
- * chunk has balanced fences (i.e. `hasOpenFenceAtEnd` returns false).
6618
+ * chunk has balanced fences, except a trailing fence the input never closes.
6619
+ * The chunks must be consecutive pieces of one text, joined without a separator.
6316
6620
  */
6317
- mergeForFenceBalance(chunks, separator) {
6621
+ mergeForFenceBalance(chunks) {
6318
6622
  const result = [];
6623
+ const fences = new FenceTracker();
6319
6624
  let buffer = "";
6320
6625
  for (const chunk of chunks) {
6321
- buffer = buffer ? `${buffer}${separator}${chunk}` : chunk;
6322
- if (!hasOpenFenceAtEnd(buffer)) {
6626
+ buffer += chunk;
6627
+ fences.feed(chunk);
6628
+ if (!fences.isOpen()) {
6323
6629
  result.push(buffer);
6324
6630
  buffer = "";
6325
6631
  }
@@ -6327,8 +6633,29 @@ var TextContentSplitter = class {
6327
6633
  if (buffer) result.push(buffer);
6328
6634
  return result;
6329
6635
  }
6330
- warnOversize(chunks) {
6331
- for (const chunk of chunks) if (chunk.length > this.options.chunkSize) logger.warn(`⚠ TextContentSplitter emitted oversize chunk to preserve fence balance: ${chunk.length} > ${this.options.chunkSize}`);
6636
+ /**
6637
+ * Cuts a fenced block larger than `maxChunkSize` into pieces within it. With
6638
+ * `rewrapFences` each piece is wrapped in the block's own fences; otherwise
6639
+ * the pieces are plain cuts that join back to the block.
6640
+ */
6641
+ splitFencedBlock(unit, openerLine, opener) {
6642
+ const closerLine = `${opener.prefix}${opener.delimiter.repeat(opener.length)}\n`;
6643
+ const room = this.maxChunkSize - openerLine.length - closerLine.length - 1;
6644
+ if (!this.options.rewrapFences || room <= 0) return this.packLines(unit, this.maxChunkSize);
6645
+ const pieces = this.packLines(unit.slice(openerLine.length), room);
6646
+ logger.debug(`Split a ${unit.length}-char fenced block into ${pieces.length} chunks of at most ${this.maxChunkSize} chars`);
6647
+ return pieces.map((piece, index) => {
6648
+ if (index === pieces.length - 1) return `${openerLine}${piece}`;
6649
+ return `${openerLine}${piece}${piece.endsWith("\n") ? closerLine : `\n${closerLine}`}`;
6650
+ });
6651
+ }
6652
+ /**
6653
+ * Cuts text at line boundaries into pieces of at most `limit` characters,
6654
+ * cutting a longer line with `splitLongLine`. The pieces join back to the text.
6655
+ */
6656
+ packLines(text, limit) {
6657
+ const lines = this.splitByLines(text).flatMap((line) => line.length <= limit ? [line] : splitLongLine(line, limit));
6658
+ return this.mergeChunks(lines, limit);
6332
6659
  }
6333
6660
  /**
6334
6661
  * Checks if all chunks are within the maximum size limit
@@ -6374,19 +6701,11 @@ var TextContentSplitter = class {
6374
6701
  return chunks;
6375
6702
  }
6376
6703
  /**
6377
- * Uses LangChain's recursive splitter for word-based splitting as a last resort
6378
- */
6379
- async splitByWords(text) {
6380
- return await new RecursiveCharacterTextSplitter({
6381
- chunkSize: this.options.chunkSize,
6382
- chunkOverlap: 0
6383
- }).splitText(text);
6384
- }
6385
- /**
6386
6704
  * Attempts to merge small chunks with previous chunks to minimize fragmentation.
6387
- * Only merges if combined size is within maxChunkSize.
6705
+ * Only merges if the combined size is within `limit`, which defaults to `chunkSize`.
6706
+ * The chunks are joined as they are, since each keeps its own newlines.
6388
6707
  */
6389
- mergeChunks(chunks, separator) {
6708
+ mergeChunks(chunks, limit = this.options.chunkSize) {
6390
6709
  const mergedChunks = [];
6391
6710
  let currentChunk = null;
6392
6711
  for (const chunk of chunks) {
@@ -6394,7 +6713,7 @@ var TextContentSplitter = class {
6394
6713
  currentChunk = chunk;
6395
6714
  continue;
6396
6715
  }
6397
- if (this.getChunkSize(currentChunk) + this.getChunkSize(chunk) + separator.length <= this.options.chunkSize) currentChunk = `${currentChunk}${separator}${chunk}`;
6716
+ if (this.getChunkSize(currentChunk) + this.getChunkSize(chunk) <= limit) currentChunk = `${currentChunk}${chunk}`;
6398
6717
  else {
6399
6718
  mergedChunks.push(currentChunk);
6400
6719
  currentChunk = chunk;
@@ -6410,13 +6729,82 @@ var TextContentSplitter = class {
6410
6729
  return content;
6411
6730
  }
6412
6731
  };
6732
+ /**
6733
+ * Cuts a line that is too long into pieces that join back to it.
6734
+ *
6735
+ * Each piece ends after the last space or tab within `limit`. When there is no
6736
+ * space to cut at, the line starts with one long token: it stays whole up to
6737
+ * `hardLimit`, and is cut inside only when it is longer still. A cut inside a
6738
+ * token is the last resort, used only when nothing else stays within the limit.
6739
+ *
6740
+ * @param line The line to cut.
6741
+ * @param limit The size each piece should stay within.
6742
+ * @param hardLimit The size no piece may exceed; defaults to `limit`.
6743
+ * @returns The pieces, in order.
6744
+ */
6745
+ function splitLongLine(line, limit, hardLimit = limit) {
6746
+ const hard = Math.max(hardLimit, limit);
6747
+ const pieces = [];
6748
+ let start = 0;
6749
+ while (line.length - start > limit) {
6750
+ const window = line.slice(start, start + limit);
6751
+ const lastSpace = Math.max(window.lastIndexOf(" "), window.lastIndexOf(" "));
6752
+ let cut;
6753
+ if (lastSpace > 0) cut = lastSpace + 1;
6754
+ else {
6755
+ const spaceAfter = line.slice(start + limit, start + hard).search(/[ \t]/);
6756
+ cut = spaceAfter === -1 ? Math.min(hard, line.length - start) : limit + spaceAfter + 1;
6757
+ }
6758
+ pieces.push(line.slice(start, start + cut));
6759
+ start += cut;
6760
+ }
6761
+ if (start < line.length) pieces.push(line.slice(start));
6762
+ return pieces;
6763
+ }
6764
+ // src/splitter/splitters/CodeContentSplitter.ts
6765
+ /**
6766
+ * Splits code content while preserving language information and formatting.
6767
+ * Uses line boundaries for splitting and ensures each chunk is properly
6768
+ * wrapped with language-specific code block markers.
6769
+ */
6770
+ var CodeContentSplitter = class {
6771
+ options;
6772
+ constructor(options) {
6773
+ this.options = options;
6774
+ }
6775
+ async split(content) {
6776
+ const infoString = (content.match(/^```([^\n]*)\n/)?.[1] ?? "").trimEnd();
6777
+ const strippedContent = content.replace(/^```[^\n]*\n/, "").replace(/```\s*$/, "");
6778
+ const room = this.options.chunkSize - this.wrap("", infoString).length;
6779
+ if (room <= 0) throw new MinimumChunkSizeError(this.wrap("", infoString).length, this.options.chunkSize);
6780
+ const lines = strippedContent.split("\n").flatMap((line) => line.length <= room ? [line] : splitLongLine(line, room));
6781
+ const chunks = [];
6782
+ let currentChunkLines = [];
6783
+ for (const line of lines) {
6784
+ currentChunkLines.push(line);
6785
+ if (this.wrap(currentChunkLines.join("\n"), infoString).length > this.options.chunkSize && currentChunkLines.length > 1) {
6786
+ const lastLine = currentChunkLines.pop();
6787
+ chunks.push(this.wrap(currentChunkLines.join("\n"), infoString));
6788
+ currentChunkLines = [lastLine];
6789
+ }
6790
+ }
6791
+ if (currentChunkLines.length > 0) chunks.push(this.wrap(currentChunkLines.join("\n"), infoString));
6792
+ return chunks;
6793
+ }
6794
+ wrap(content, infoString) {
6795
+ return `\`\`\`${infoString || ""}\n${content.replace(/\n+$/, "")}\n\`\`\``;
6796
+ }
6797
+ };
6413
6798
  // src/splitter/splitters/ListContentSplitter.ts
6414
6799
  var ListContentSplitter = class {
6415
6800
  options;
6416
6801
  textSplitter;
6417
6802
  constructor(options) {
6418
6803
  this.options = options;
6419
- this.textSplitter = new TextContentSplitter(options);
6804
+ this.textSplitter = new TextContentSplitter({
6805
+ rewrapFences: true,
6806
+ ...options
6807
+ });
6420
6808
  }
6421
6809
  async split(content) {
6422
6810
  if (content.length <= this.options.chunkSize) return [content];
@@ -6595,10 +6983,17 @@ var SemanticMarkdownSplitter = class SemanticMarkdownSplitter {
6595
6983
  return markdown;
6596
6984
  }
6597
6985
  });
6598
- this.textSplitter = new TextContentSplitter({ chunkSize: this.preferredChunkSize });
6986
+ this.textSplitter = new TextContentSplitter({
6987
+ chunkSize: this.preferredChunkSize,
6988
+ maxChunkSize: this.maxChunkSize,
6989
+ rewrapFences: true
6990
+ });
6599
6991
  this.codeSplitter = new CodeContentSplitter({ chunkSize: this.maxChunkSize });
6600
6992
  this.tableSplitter = new TableContentSplitter({ chunkSize: this.maxChunkSize });
6601
- this.listSplitter = new ListContentSplitter({ chunkSize: this.preferredChunkSize });
6993
+ this.listSplitter = new ListContentSplitter({
6994
+ chunkSize: this.preferredChunkSize,
6995
+ maxChunkSize: this.maxChunkSize
6996
+ });
6602
6997
  }
6603
6998
  /**
6604
6999
  * Main entry point for splitting markdown content
@@ -6705,7 +7100,7 @@ var SemanticMarkdownSplitter = class SemanticMarkdownSplitter {
6705
7100
  let currentSection = this.createRootSection();
6706
7101
  const sections = [];
6707
7102
  const stack = [currentSection];
6708
- for (const element of Array.from(body.children)) {
7103
+ for (let element = body.firstElementChild; element !== null; element = element.nextElementSibling) {
6709
7104
  const headingMatch = element.tagName.match(/H([1-6])/);
6710
7105
  if (headingMatch) {
6711
7106
  const level = Number.parseInt(headingMatch[1], 10);
@@ -9184,7 +9579,7 @@ var TextDocumentSplitter = class {
9184
9579
  }
9185
9580
  }));
9186
9581
  } catch (error) {
9187
- if (!(error instanceof MinimumChunkSizeError) && error instanceof Error) console.warn(`Unexpected text splitting error: ${error.message}. Forcing character-based split.`);
9582
+ console.warn(`Unexpected text splitting error: ${error instanceof Error ? error.message : String(error)}. Forcing character-based split.`);
9188
9583
  const chunks = [];
9189
9584
  let offset = 0;
9190
9585
  while (offset < content.length) {
@@ -9545,29 +9940,29 @@ var MarkdownLinkExtractorMiddleware = class {
9545
9940
  */
9546
9941
  async process(context, next) {
9547
9942
  if (!Array.isArray(context.links)) context.links = [];
9548
- for (const link of extractMarkdownLinks(context.content)) if (!context.links.includes(link)) context.links.push(link);
9943
+ const seen = new Set(context.links);
9944
+ for (const link of extractMarkdownLinks(context.content)) if (!seen.has(link)) {
9945
+ seen.add(link);
9946
+ context.links.push(link);
9947
+ }
9549
9948
  await next();
9550
9949
  }
9551
9950
  };
9552
9951
  function extractMarkdownLinks(content) {
9553
- const links = [];
9952
+ const links = /* @__PURE__ */ new Set();
9554
9953
  const referenceDefinitions = /* @__PURE__ */ new Map();
9555
9954
  for (const match of content.matchAll(referenceDefinitionPattern)) {
9556
9955
  const label = normalizeReferenceLabel(match[1]);
9557
9956
  const target = cleanReferenceTarget(match[2]);
9558
9957
  if (label && target && !referenceDefinitions.has(label)) referenceDefinitions.set(label, target);
9559
9958
  }
9560
- for (const match of content.matchAll(inlineLinkPattern)) addUniqueLink(links, match[2]);
9959
+ for (const match of content.matchAll(inlineLinkPattern)) if (match[2]) links.add(match[2]);
9561
9960
  for (const match of content.matchAll(referenceLinkPattern)) {
9562
9961
  const target = referenceDefinitions.get(normalizeReferenceLabel(match[2]));
9563
- if (target) addUniqueLink(links, target);
9962
+ if (target) links.add(target);
9564
9963
  }
9565
9964
  return links;
9566
9965
  }
9567
- function addUniqueLink(links, target) {
9568
- if (!target || links.includes(target)) return;
9569
- links.push(target);
9570
- }
9571
9966
  function normalizeReferenceLabel(label) {
9572
9967
  return label?.trim().replace(/\s+/g, " ").toLowerCase() ?? "";
9573
9968
  }
@@ -10745,20 +11140,6 @@ var GitHubWikiProcessor = class {
10745
11140
  };
10746
11141
  }
10747
11142
  /**
10748
- * Determines if a URL should be processed within the wiki scope.
10749
- */
10750
- shouldProcessUrl(url, options) {
10751
- try {
10752
- const parsedUrl = new URL(url);
10753
- const baseWikiInfo = this.parseGitHubWikiUrl(options.url);
10754
- const expectedWikiPath = `/${baseWikiInfo.owner}/${baseWikiInfo.repo}/wiki`;
10755
- if (!parsedUrl.pathname.startsWith(expectedWikiPath)) return false;
10756
- return shouldIncludeUrl(parsedUrl.pathname.replace(expectedWikiPath, "").replace(/^\//, "") || "Home", options.includePatterns, options.excludePatterns);
10757
- } catch {
10758
- return false;
10759
- }
10760
- }
10761
- /**
10762
11143
  * Processes a single GitHub wiki page.
10763
11144
  */
10764
11145
  async process(item, options, headers, signal) {
@@ -11081,6 +11462,21 @@ var COMMON_TEXT_FILES = [
11081
11462
  ".nvmrc",
11082
11463
  ".npmrc"
11083
11464
  ];
11465
+ /** Removes leading and trailing slashes from a repository path. */
11466
+ function trimSlashes(value) {
11467
+ return value.replace(/^\/+|\/+$/g, "");
11468
+ }
11469
+ /**
11470
+ * Decodes a repository path taken from a blob URL. Discovery builds those URLs
11471
+ * from raw tree paths, so `docs/100%.md` arrives unescaped and is kept as it is.
11472
+ */
11473
+ function decodeRepoPath(urlPath) {
11474
+ try {
11475
+ return decodeURIComponent(urlPath);
11476
+ } catch {
11477
+ return urlPath;
11478
+ }
11479
+ }
11084
11480
  /**
11085
11481
  * GitHubScraperStrategy is a discovery strategy that orchestrates the scraping of both
11086
11482
  * GitHub repository code and wiki pages. When given a GitHub repository URL, it will:
@@ -11111,6 +11507,8 @@ var GitHubScraperStrategy = class extends BaseScraperStrategy {
11111
11507
  repoProcessor;
11112
11508
  resolvedAuthHeaders;
11113
11509
  resolvedAuthKey;
11510
+ /** Folder a `/tree/<branch>/<path>` start URL names, measured from the repo root. */
11511
+ treeRootDirectory;
11114
11512
  constructor(config) {
11115
11513
  super(config);
11116
11514
  this.httpFetcher = new HttpFetcher(config.scraper);
@@ -11223,9 +11621,10 @@ var GitHubScraperStrategy = class extends BaseScraperStrategy {
11223
11621
  };
11224
11622
  }
11225
11623
  /**
11226
- * Determines if a file should be processed based on its path and type.
11624
+ * Determines if a file is a type the crawl can index. Include and exclude
11625
+ * patterns are left to {@link getExclusion}, which judges every link.
11227
11626
  */
11228
- shouldProcessFile(item, options) {
11627
+ shouldProcessFile(item) {
11229
11628
  if (item.type !== "blob") return false;
11230
11629
  const filePath = item.path;
11231
11630
  const pathLower = filePath.toLowerCase();
@@ -11236,22 +11635,16 @@ var GitHubScraperStrategy = class extends BaseScraperStrategy {
11236
11635
  const hasCompoundExtension = pathLower.includes(".env.") || pathLower.endsWith(".env") || pathLower.includes(".config.") || pathLower.includes(".lock");
11237
11636
  const fileNameLower = (filePath.split("/").pop() || "").toLowerCase();
11238
11637
  const isCommonTextFile = COMMON_TEXT_FILES.some((name) => fileNameLower === name || fileNameLower.startsWith(`${name}.`));
11239
- if (hasTextExtension || hasDocumentExtension || hasCompoundExtension || isCommonTextFile) return shouldIncludeUrl(filePath, options.includePatterns, options.excludePatterns);
11240
- const mimeType = MimeTypeUtils.detectMimeTypeFromPath(filePath);
11241
- if (mimeType?.startsWith("text/")) {
11242
- logger.debug(`Including file with text MIME type: ${filePath} (${mimeType})`);
11243
- return shouldIncludeUrl(filePath, options.includePatterns, options.excludePatterns);
11244
- }
11245
- return false;
11638
+ return hasTextExtension || hasDocumentExtension || hasCompoundExtension || isCommonTextFile || MimeTypeUtils.detectMimeTypeFromPath(filePath)?.startsWith("text/") === true;
11246
11639
  }
11247
11640
  /**
11248
11641
  * Checks if a path is within the specified subpath.
11249
11642
  */
11250
11643
  isWithinSubPath(path, subPath) {
11251
11644
  if (!subPath) return true;
11252
- const trimmedSubPath = subPath.replace(/^\/+/, "").replace(/\/+$/, "");
11645
+ const trimmedSubPath = trimSlashes(subPath);
11253
11646
  if (trimmedSubPath.length === 0) return true;
11254
- const normalizedPath = path.replace(/^\/+/, "").replace(/\/+$/, "");
11647
+ const normalizedPath = trimSlashes(path);
11255
11648
  if (normalizedPath === trimmedSubPath) return true;
11256
11649
  return normalizedPath.startsWith(`${trimmedSubPath}/`);
11257
11650
  }
@@ -11291,6 +11684,40 @@ var GitHubScraperStrategy = class extends BaseScraperStrategy {
11291
11684
  const { owner, repo } = this.parseGitHubUrl(options.url);
11292
11685
  return new URL(`/${owner}/${repo}`, options.url);
11293
11686
  }
11687
+ /**
11688
+ * Judges repository files by their path in the repository, as discovery
11689
+ * does, rather than by their blob URL: a pattern such as `docs/internal/**`
11690
+ * names `docs/internal/guide.md`, not
11691
+ * `https://github.com/owner/repo/blob/main/docs/internal/guide.md`. An
11692
+ * exclude pattern that names the blob URL excludes the file too. Other URLs,
11693
+ * such as wiki pages, are judged by the base patterns.
11694
+ *
11695
+ * Match-anywhere exclude globs are measured from the folder a `/tree/`
11696
+ * start URL names, so scraping `tree/main/test` is not emptied by `**\/test/**`.
11697
+ *
11698
+ * @param url The URL to judge.
11699
+ * @param options Scraper options for this crawl.
11700
+ * @param context Internal allowlist roots the item carries.
11701
+ * @returns Why the crawl must not admit the URL, or null when it may.
11702
+ */
11703
+ async getExclusion(url, options, context) {
11704
+ let filePath;
11705
+ try {
11706
+ const info = this.parseGitHubUrl(url);
11707
+ filePath = info.isBlob ? info.filePath : void 0;
11708
+ } catch {}
11709
+ if (filePath === void 0) return super.getExclusion(url, options, context);
11710
+ const { pathname } = new URL(url);
11711
+ const blobRoot = pathname.endsWith(filePath) ? `${pathname.slice(0, pathname.length - filePath.length)}${this.treeRootDirectory?.slice(1) ?? ""}` : void 0;
11712
+ return evaluateUrlPatterns(decodeRepoPath(filePath), {
11713
+ includePatterns: options.includePatterns,
11714
+ excludePatterns: options.excludePatterns,
11715
+ rootDirectory: this.treeRootDirectory
11716
+ }) ?? evaluateUrlPatterns(url, {
11717
+ excludePatterns: options.excludePatterns,
11718
+ rootDirectory: blobRoot
11719
+ });
11720
+ }
11294
11721
  async processItem(item, options, signal) {
11295
11722
  if (item.url.startsWith("github-file://")) {
11296
11723
  logger.info(`🗑️ Legacy github-file:// URL detected, marking as deleted: ${item.url}`);
@@ -11320,7 +11747,7 @@ var GitHubScraperStrategy = class extends BaseScraperStrategy {
11320
11747
  logger.debug(`Discovered wiki URL: ${wikiUrl}`);
11321
11748
  }
11322
11749
  const { tree, resolvedBranch } = await this.fetchRepositoryTree(repoInfo, headers, signal);
11323
- const fileItems = tree.tree.filter((treeItem) => this.isWithinSubPath(treeItem.path, repoInfo.subPath)).filter((treeItem) => this.shouldProcessFile(treeItem, options));
11750
+ const fileItems = tree.tree.filter((treeItem) => this.isWithinSubPath(treeItem.path, repoInfo.subPath)).filter((treeItem) => this.shouldProcessFile(treeItem));
11324
11751
  logger.debug(`Discovered ${fileItems.length} processable files in repository (branch: ${resolvedBranch})`);
11325
11752
  const fileUrls = fileItems.map((treeItem) => `https://github.com/${owner}/${repo}/blob/${resolvedBranch}/${treeItem.path}`);
11326
11753
  discoveredLinks.push(...fileUrls);
@@ -11357,7 +11784,13 @@ var GitHubScraperStrategy = class extends BaseScraperStrategy {
11357
11784
  if (!new URL(options.url).hostname.includes("github.com")) throw new Error("URL must be a GitHub URL");
11358
11785
  await this.getResolvedAuthHeaders(options.headers);
11359
11786
  try {
11360
- await super.scrape(options, progressCallback, signal);
11787
+ const subPath = trimSlashes(this.parseGitHubUrl(options.url).subPath ?? "");
11788
+ this.treeRootDirectory = subPath ? `/${subPath}/` : void 0;
11789
+ } catch {
11790
+ this.treeRootDirectory = void 0;
11791
+ }
11792
+ try {
11793
+ return await super.scrape(options, progressCallback, signal);
11361
11794
  } finally {
11362
11795
  this.resolvedAuthHeaders = void 0;
11363
11796
  this.resolvedAuthKey = void 0;
@@ -11552,6 +11985,143 @@ async function getArchiveAdapter(filePath) {
11552
11985
  if (ext === ".tar" || ext === ".gz" || ext === ".tgz") return new TarAdapter(filePath);
11553
11986
  return null;
11554
11987
  }
11988
+ // src/scraper/utils/gitignore.ts
11989
+ /** Repository metadata directory, which Git never walks and never lets a pattern re-include. */
11990
+ var GIT_DIRECTORY = ".git";
11991
+ /**
11992
+ * Matches paths against `.gitignore` files from a local crawl root down to the
11993
+ * candidate path. Each directory keeps its own pattern base and overrides
11994
+ * ancestor decisions according to Git ignore ordering.
11995
+ */
11996
+ var GitignoreFilter = class {
11997
+ rootDirectory;
11998
+ ignoreCaseOverride;
11999
+ /**
12000
+ * The combined rules that apply inside each directory, or null for a
12001
+ * directory inside an ignored one, whose whole content is ignored.
12002
+ */
12003
+ matcherCache = /* @__PURE__ */ new Map();
12004
+ constructor(rootDirectory, options = {}) {
12005
+ this.rootDirectory = path.resolve(rootDirectory);
12006
+ this.ignoreCaseOverride = options.ignoreCase;
12007
+ }
12008
+ /**
12009
+ * Returns whether a path is ignored by the applicable `.gitignore` cascade.
12010
+ * `.git` and everything under it is always ignored, as in Git.
12011
+ * @param targetPath Absolute filesystem path to test.
12012
+ * @param isDirectory Whether the target is a directory.
12013
+ * @returns True when the path should be skipped.
12014
+ */
12015
+ async isIgnored(targetPath, isDirectory) {
12016
+ const resolvedTarget = path.resolve(targetPath);
12017
+ const relativePath = path.relative(this.rootDirectory, resolvedTarget);
12018
+ if (!relativePath || isOutsideDirectory(relativePath)) return false;
12019
+ const segments = relativePath.split(path.sep);
12020
+ if (segments.some((segment) => segment.toLowerCase() === GIT_DIRECTORY)) return true;
12021
+ const matcher = await this.getMatcher(path.dirname(resolvedTarget));
12022
+ return matcher === null || matches(matcher, segments, isDirectory);
12023
+ }
12024
+ getMatcher(directory) {
12025
+ let matcher = this.matcherCache.get(directory);
12026
+ if (!matcher) {
12027
+ matcher = this.buildMatcher(directory);
12028
+ this.matcherCache.set(directory, matcher);
12029
+ }
12030
+ return matcher;
12031
+ }
12032
+ async buildMatcher(directory) {
12033
+ const relativeDirectory = path.relative(this.rootDirectory, directory);
12034
+ let parent;
12035
+ if (relativeDirectory) {
12036
+ parent = await this.getMatcher(path.dirname(directory));
12037
+ if (parent === null || matches(parent, relativeDirectory.split(path.sep), true)) return null;
12038
+ } else parent = ignore({ ignorecase: this.ignoreCaseOverride ?? false });
12039
+ const loaded = await this.loadPatterns(directory, relativeDirectory);
12040
+ return loaded ? ignore({ ignorecase: loaded.ignoreCase }).add(parent).add(loaded.patterns) : parent;
12041
+ }
12042
+ /**
12043
+ * Reads a directory's `.gitignore`, with nested rules rewritten relative to
12044
+ * the root. A file that cannot be read is skipped with a warning.
12045
+ */
12046
+ async loadPatterns(directory, relativeDirectory) {
12047
+ const ignorePath = path.join(directory, ".gitignore");
12048
+ try {
12049
+ const stats = await fs$1.lstat(ignorePath);
12050
+ if (!stats.isFile()) return null;
12051
+ const lines = (await fs$1.readFile(ignorePath, "utf8")).replace(/^\uFEFF/, "").split(/\r?\n/);
12052
+ const base = relativeDirectory.split(path.sep).join("/");
12053
+ return {
12054
+ patterns: base ? lines.map((line) => scopePatternToRoot(line, base)) : lines,
12055
+ ignoreCase: await this.resolveIgnoreCase(ignorePath, stats)
12056
+ };
12057
+ } catch (error) {
12058
+ if (!isMissingPathError(error)) logger.warn(`⚠️ Could not read ${ignorePath}, so its rules are not applied: ${error}`);
12059
+ return null;
12060
+ }
12061
+ }
12062
+ /** Probes whether the volume is case-insensitive: `.GITIGNORE` then is the same file. */
12063
+ async resolveIgnoreCase(ignorePath, stats) {
12064
+ if (this.ignoreCaseOverride !== void 0) return this.ignoreCaseOverride;
12065
+ try {
12066
+ const alternateStats = await fs$1.lstat(path.join(path.dirname(ignorePath), ".GITIGNORE"));
12067
+ return alternateStats.dev === stats.dev && alternateStats.ino === stats.ino;
12068
+ } catch (error) {
12069
+ if (isMissingPathError(error)) return false;
12070
+ throw error;
12071
+ }
12072
+ }
12073
+ };
12074
+ /**
12075
+ * Finds the Git repository root above `directory`, to warn that a crawl rooted
12076
+ * below it cannot see that repository's ignore rules. Only probes for a `.git`
12077
+ * entry in ancestor directories and never reads anything.
12078
+ * @param directory Absolute path of the crawl root.
12079
+ * @returns The repository root above `directory`, or null when there is none.
12080
+ */
12081
+ async function findRepositoryRootAbove(directory) {
12082
+ let current = path.dirname(path.resolve(directory));
12083
+ while (true) {
12084
+ try {
12085
+ await fs$1.lstat(path.join(current, GIT_DIRECTORY));
12086
+ return current;
12087
+ } catch {}
12088
+ const parent = path.dirname(current);
12089
+ if (parent === current) return null;
12090
+ current = parent;
12091
+ }
12092
+ }
12093
+ /**
12094
+ * Whether a filesystem error means the path does not exist.
12095
+ * @param error The error thrown by a `fs` call.
12096
+ * @returns True for `ENOENT` and `ENOTDIR`.
12097
+ */
12098
+ function isMissingPathError(error) {
12099
+ const code = error.code;
12100
+ return code === "ENOENT" || code === "ENOTDIR";
12101
+ }
12102
+ function matches(matcher, segments, isDirectory) {
12103
+ const candidate = segments.join("/");
12104
+ return matcher.test(isDirectory ? `${candidate}/` : candidate).ignored;
12105
+ }
12106
+ /**
12107
+ * Rewrites a rule from a nested `.gitignore` so it matches from the crawl root.
12108
+ * The `ignore` package checks parent directories against the same rules, so
12109
+ * nested files cannot get matchers of their own and must join the root's.
12110
+ */
12111
+ function scopePatternToRoot(pattern, base) {
12112
+ if (!pattern.trim() || pattern.startsWith("#")) return pattern;
12113
+ const negative = pattern.startsWith("!");
12114
+ const body = negative ? pattern.slice(1) : pattern;
12115
+ const significant = body.replace(/ +$/, "");
12116
+ if (!significant.trim() || significant === "/") return pattern;
12117
+ const marker = negative ? "!" : "";
12118
+ const escapedBase = base.replace(/[\\*?[\]!#]/g, "\\$&");
12119
+ if (body.startsWith("/")) return `${marker}${escapedBase}/${body.slice(1)}`;
12120
+ return `${marker}${escapedBase}${(significant.endsWith("/") ? significant.slice(0, -1) : significant).includes("/") ? "/" : "/**/"}${body}`;
12121
+ }
12122
+ function isOutsideDirectory(relativePath) {
12123
+ return relativePath === ".." || relativePath.startsWith(`..${path.sep}`) || path.isAbsolute(relativePath);
12124
+ }
11555
12125
  // src/scraper/strategies/LocalFileStrategy.ts
11556
12126
  /**
11557
12127
  * Orders two names by Unicode code point, which is the byte order of their
@@ -11561,6 +12131,26 @@ function compareCodePoints(a, b) {
11561
12131
  return Buffer.compare(Buffer.from(a), Buffer.from(b));
11562
12132
  }
11563
12133
  /**
12134
+ * Returns the `file:///` URL the crawl records for a local path.
12135
+ */
12136
+ function toFileUrl(filePath) {
12137
+ const url = new URL(`file://${filePath.replace(/\\/g, "/")}`);
12138
+ if (url.hostname !== "") {
12139
+ url.pathname = `/${url.hostname}${url.pathname}`;
12140
+ url.hostname = "";
12141
+ }
12142
+ return url.href;
12143
+ }
12144
+ /**
12145
+ * Returns the path segments of `target` below `root`, an empty list when they
12146
+ * are the same path, or null when `target` is not inside `root`.
12147
+ */
12148
+ function relativeSegments(root, target) {
12149
+ const relative = path.relative(root, target);
12150
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) return null;
12151
+ return relative.split(path.sep).filter(Boolean);
12152
+ }
12153
+ /**
11564
12154
  * LocalFileStrategy handles crawling and scraping of local files and folders using file:// URLs.
11565
12155
  *
11566
12156
  * Files are routed to the appropriate pipeline based on their detected MIME type:
@@ -11576,6 +12166,13 @@ var LocalFileStrategy = class extends BaseScraperStrategy {
11576
12166
  fileFetcher;
11577
12167
  pipelines;
11578
12168
  accessPolicy;
12169
+ /**
12170
+ * Each path's own entry, per crawl. Siblings share their ancestors, so each
12171
+ * directory is looked at once rather than once for every entry below it.
12172
+ */
12173
+ entryLookups = /* @__PURE__ */ new Map();
12174
+ /** The `.gitignore` rules of this crawl, when `respectGitignore` is on. */
12175
+ gitignoreFilter = null;
11579
12176
  constructor(config) {
11580
12177
  super(config);
11581
12178
  this.fileFetcher = new FileFetcher(config.scraper);
@@ -11583,7 +12180,7 @@ var LocalFileStrategy = class extends BaseScraperStrategy {
11583
12180
  this.accessPolicy = new ScraperAccessPolicy(config.scraper.security);
11584
12181
  }
11585
12182
  async processItem(item, options, _signal) {
11586
- const filePath = (await this.accessPolicy.resolveFileAccess(item.url, options.internalAllowedFileRoots)).filePath;
12183
+ const filePath = (await this.accessPolicy.resolveFileAccess(item.url, item.internalAllowedFileRoots)).filePath;
11587
12184
  let stats = null;
11588
12185
  let archivePath = null;
11589
12186
  let innerPath = null;
@@ -11610,25 +12207,10 @@ var LocalFileStrategy = class extends BaseScraperStrategy {
11610
12207
  } else throw error;
11611
12208
  }
11612
12209
  if (stats?.isDirectory()) {
11613
- const contents = (await fs$1.readdir(filePath)).sort(compareCodePoints);
11614
- const visibleContents = this.config.scraper.security.fileAccess.includeHidden ? contents : contents.filter((name) => !name.startsWith("."));
11615
- const links = (await Promise.all(visibleContents.map(async (name) => {
11616
- const entryPath = path.join(filePath, name);
11617
- if (!this.config.scraper.security.fileAccess.followSymlinks) {
11618
- if ((await fs$1.lstat(entryPath).catch(() => null))?.isSymbolicLink()) return null;
11619
- }
11620
- const url = new URL(`file://${entryPath.replace(/\\/g, "/")}`);
11621
- if (url.hostname !== "") {
11622
- url.pathname = `/${url.hostname}${url.pathname}`;
11623
- url.hostname = "";
11624
- }
11625
- return url.href;
11626
- }))).filter((url) => Boolean(url)).filter((url) => {
11627
- const allowed = this.shouldProcessUrl(url, options);
11628
- if (!allowed) logger.debug(`Skipping out-of-scope link: ${url}`);
11629
- return allowed;
12210
+ const links = (await fs$1.readdir(filePath)).sort(compareCodePoints).map((name) => {
12211
+ return toFileUrl(path.join(filePath, name));
11630
12212
  });
11631
- logger.debug(`Found ${links.length} files in ${filePath} (from ${visibleContents.length} entries)`);
12213
+ logger.debug(`Found ${links.length} entries in ${filePath}`);
11632
12214
  return {
11633
12215
  url: item.url,
11634
12216
  links,
@@ -11649,12 +12231,7 @@ var LocalFileStrategy = class extends BaseScraperStrategy {
11649
12231
  }
11650
12232
  const entryPath = entry.path.replace(/^\//, "");
11651
12233
  const fullVirtualPath = path.join(filePath, entryPath).replace(/\\/g, "/");
11652
- const virtualUrl = new URL(`file://${fullVirtualPath}`);
11653
- if (virtualUrl.hostname !== "") {
11654
- virtualUrl.pathname = `/${virtualUrl.hostname}${virtualUrl.pathname}`;
11655
- virtualUrl.hostname = "";
11656
- }
11657
- if (this.shouldProcessUrl(virtualUrl.href, options) && this.isVisibleArchiveEntry(entry.path)) links.push(virtualUrl.href);
12234
+ links.push(toFileUrl(fullVirtualPath));
11658
12235
  }
11659
12236
  logger.debug(`Found ${links.length} entries in archive ${filePath}`);
11660
12237
  return {
@@ -11730,9 +12307,138 @@ var LocalFileStrategy = class extends BaseScraperStrategy {
11730
12307
  adapter: null
11731
12308
  };
11732
12309
  }
11733
- isVisibleArchiveEntry(entryPath) {
11734
- if (this.config.scraper.security.fileAccess.includeHidden) return true;
11735
- return !entryPath.split(/[\\/]+/).filter(Boolean).some((segment) => segment.startsWith("."));
12310
+ /**
12311
+ * Judges a folder or archive by the exclude patterns only, since include
12312
+ * patterns name files. Excludes, besides what the patterns exclude, the
12313
+ * files the crawl would not reach: anything inside a folder or archive below the crawl root that an
12314
+ * exclude pattern names, anything below the crawl root with a hidden path
12315
+ * segment unless `includeHidden` is on, and anything reached through a
12316
+ * symlink below the crawl root unless `followSymlinks` is on, and anything
12317
+ * the crawl root's `.gitignore` files name when `respectGitignore` is on.
12318
+ * Archive members count their path inside the archive as segments.
12319
+ *
12320
+ * Segments at or above the crawl root are the user's own choice and are not
12321
+ * judged; the access policy decides whether that root may be read at all.
12322
+ *
12323
+ * @param url The `file://` URL to judge.
12324
+ * @param options Scraper options for this crawl.
12325
+ * @param context Internal allowlist roots the item carries.
12326
+ * @returns Why the crawl must not admit the URL, or null when it may.
12327
+ */
12328
+ async getExclusion(url, options, context) {
12329
+ const root = path.resolve(fileUrlToPathLoose(options.url));
12330
+ let segments;
12331
+ try {
12332
+ segments = relativeSegments(root, path.resolve(fileUrlToPathLoose(url)));
12333
+ } catch {
12334
+ segments = null;
12335
+ }
12336
+ if (segments && await this.isGitignored(root, segments)) return { check: "gitignore" };
12337
+ const patternRejection = await this.isContainer(url) ? evaluateUrlPatterns(url, {
12338
+ excludePatterns: options.excludePatterns,
12339
+ rootDirectory: this.getPatternRootDirectory(url, options, context)
12340
+ }) : await super.getExclusion(url, options, context);
12341
+ if (patternRejection) return patternRejection;
12342
+ if (!segments) return null;
12343
+ let ancestor = root;
12344
+ for (const segment of segments.slice(0, -1)) {
12345
+ ancestor = path.join(ancestor, segment);
12346
+ const ancestorUrl = toFileUrl(ancestor);
12347
+ const rejection = evaluateUrlPatterns(ancestorUrl, {
12348
+ excludePatterns: options.excludePatterns,
12349
+ rootDirectory: this.getPatternRootDirectory(ancestorUrl, options, context)
12350
+ });
12351
+ if (rejection) return rejection;
12352
+ }
12353
+ const { includeHidden, followSymlinks } = this.config.scraper.security.fileAccess;
12354
+ if (!includeHidden && segments.some((segment) => segment.startsWith("."))) return { check: "hidden" };
12355
+ if (!followSymlinks) {
12356
+ let current = root;
12357
+ for (const segment of segments) {
12358
+ current = path.join(current, segment);
12359
+ const entry = await this.lookUpEntry(current);
12360
+ if (typeof entry === "object" && entry.symlink) return { check: "symlink" };
12361
+ }
12362
+ }
12363
+ return null;
12364
+ }
12365
+ /**
12366
+ * Tells whether `url` names a folder or an archive, which the crawl enters
12367
+ * rather than indexes. A path that does not exist is neither.
12368
+ */
12369
+ async isContainer(url) {
12370
+ try {
12371
+ const filePath = fileUrlToPathLoose(url);
12372
+ return (await fs$1.stat(filePath)).isDirectory() || await getArchiveAdapter(filePath) !== null;
12373
+ } catch {
12374
+ return false;
12375
+ }
12376
+ }
12377
+ /**
12378
+ * Whether the active `.gitignore` rules name a path below the crawl root.
12379
+ * Symlinks are tested as plain paths, because Git records them as blobs, so a
12380
+ * directory-only rule (`link/`) never matches one. An archive member has no
12381
+ * entry of its own, so the archive file decides for it, as Git never looks
12382
+ * inside one. An entry that cannot be looked at is tested as a file, so the
12383
+ * rules still apply and anything else reports its own error when fetched.
12384
+ */
12385
+ async isGitignored(root, segments) {
12386
+ if (!this.gitignoreFilter) return false;
12387
+ for (let depth = segments.length; depth > 0; depth--) {
12388
+ const candidate = path.join(root, ...segments.slice(0, depth));
12389
+ const entry = await this.lookUpEntry(candidate);
12390
+ if (entry === "missing") continue;
12391
+ if (depth < segments.length && typeof entry === "object" && entry.directory) break;
12392
+ const isDirectory = typeof entry === "object" && entry.directory;
12393
+ return this.gitignoreFilter.isIgnored(candidate, isDirectory);
12394
+ }
12395
+ return this.gitignoreFilter.isIgnored(path.join(root, ...segments), false);
12396
+ }
12397
+ /** Looks up a path's own entry, once per crawl. */
12398
+ lookUpEntry(filePath) {
12399
+ let lookup = this.entryLookups.get(filePath);
12400
+ if (!lookup) {
12401
+ lookup = fs$1.lstat(filePath).then((stats) => ({
12402
+ symlink: stats.isSymbolicLink(),
12403
+ directory: stats.isDirectory()
12404
+ }), (error) => isMissingPathError(error) ? "missing" : "unreadable");
12405
+ this.entryLookups.set(filePath, lookup);
12406
+ }
12407
+ return lookup;
12408
+ }
12409
+ /**
12410
+ * Runs the crawl with fresh entry lookups, so a link created or removed since
12411
+ * the last run is seen, and with the `.gitignore` rules as they are now.
12412
+ *
12413
+ * @param options Scraper options for this crawl.
12414
+ * @param progressCallback Receives each item's outcome.
12415
+ * @param signal Cancels the crawl.
12416
+ * @returns Why discovered links were rejected.
12417
+ */
12418
+ async scrape(options, progressCallback, signal) {
12419
+ this.entryLookups.clear();
12420
+ this.gitignoreFilter = options.respectGitignore ? await this.createGitignoreFilter(options) : null;
12421
+ try {
12422
+ return await super.scrape(options, progressCallback, signal);
12423
+ } finally {
12424
+ this.entryLookups.clear();
12425
+ this.gitignoreFilter = null;
12426
+ }
12427
+ }
12428
+ /**
12429
+ * Builds the `.gitignore` filter for a crawl rooted at a directory, and warns
12430
+ * when that directory sits below a repository root whose rules it cannot see.
12431
+ */
12432
+ async createGitignoreFilter(options) {
12433
+ const { filePath } = await this.accessPolicy.resolveFileAccess(options.url);
12434
+ const root = path.resolve(filePath);
12435
+ if (!(await fs$1.stat(root).catch((error) => {
12436
+ if (isMissingPathError(error)) return null;
12437
+ throw error;
12438
+ }))?.isDirectory()) return null;
12439
+ const repositoryRoot = await findRepositoryRootAbove(root);
12440
+ if (repositoryRoot) logger.warn(`⚠️ ${root} is inside the Git repository at ${repositoryRoot}. Only .gitignore files at or below the indexed folder are applied, so any rules higher up in that repository are ignored. Index the repository root to apply them.`);
12441
+ return new GitignoreFilter(root);
11736
12442
  }
11737
12443
  async processArchiveEntry(item, archivePath, innerPath, adapter, options) {
11738
12444
  logger.debug(`Reading archive entry: ${innerPath} inside ${archivePath}`);
@@ -11919,9 +12625,15 @@ var WebScraperStrategy = class extends BaseScraperStrategy {
11919
12625
  * of them, while react.dev — the `text/plain` host — returns a real 404.
11920
12626
  * It cost the published Markdown of every such site and bought nothing.
11921
12627
  * Soft-error detection needs to read the body, and belongs elsewhere.
12628
+ *
12629
+ * The llms.txt companions (`llms-full.txt`, `llms-small.txt`, ...) are
12630
+ * Markdown by convention despite their extension, and servers send them as
12631
+ * `text/plain`. They are restated the same way but keep their own identity:
12632
+ * each is a document of its own, not a variant of another page. Other `.txt`
12633
+ * files stay plain text.
11922
12634
  */
11923
12635
  asMarkdownRepresentation(url, rawContent) {
11924
- if (!this.isMarkdownUrl(url) || !this.isAcceptableMarkdownVariant(rawContent)) return rawContent;
12636
+ if (!(this.isMarkdownUrl(url) || isLlmsTxtCompanionUrl(url)) || !this.isAcceptableMarkdownVariant(rawContent)) return rawContent;
11925
12637
  return MimeTypeUtils.isMarkdown(rawContent.mimeType) ? rawContent : {
11926
12638
  ...rawContent,
11927
12639
  mimeType: "text/markdown"
@@ -12057,14 +12769,14 @@ var WebScraperStrategy = class extends BaseScraperStrategy {
12057
12769
  }
12058
12770
  return null;
12059
12771
  }
12060
- createLlmsTxtQueueItems(options, probe) {
12772
+ async createLlmsTxtQueueItems(options, probe) {
12061
12773
  const items = [];
12062
12774
  for (const link of probe.result.links) try {
12063
12775
  const targetUrl = new URL(link.url, probe.url);
12064
12776
  if (targetUrl.protocol !== "http:" && targetUrl.protocol !== "https:") continue;
12065
12777
  if (isArchivePath(targetUrl.pathname)) continue;
12066
12778
  if (!this.canProcessDiscoveredLink(targetUrl)) continue;
12067
- if (!this.shouldProcessUrl(targetUrl.href, options)) continue;
12779
+ if (!await this.admitLink(targetUrl.href, options)) continue;
12068
12780
  if (this.shouldFollowLinkFn) {
12069
12781
  const baseUrl = this.canonicalBaseUrl ?? new URL(options.url);
12070
12782
  if (!this.shouldFollowLinkFn(baseUrl, targetUrl)) continue;
@@ -12077,7 +12789,7 @@ var WebScraperStrategy = class extends BaseScraperStrategy {
12077
12789
  } catch {}
12078
12790
  return items;
12079
12791
  }
12080
- consumePendingLlmsTxtQueueItems(item, options) {
12792
+ async consumePendingLlmsTxtQueueItems(item, options) {
12081
12793
  if (item.depth !== 0) return [];
12082
12794
  const probe = this.pendingLlmsTxtProbe;
12083
12795
  this.pendingLlmsTxtProbe = null;
@@ -12120,8 +12832,13 @@ var WebScraperStrategy = class extends BaseScraperStrategy {
12120
12832
  const fetchedSource = options.preserveHashes ? this.restorePreservedHash(url, fetched.source) : fetched.source;
12121
12833
  const rawContent = this.asMarkdownRepresentation(fetchedSource, fetched);
12122
12834
  const effectiveSource = this.resolvePageIdentity(fetchedSource, rawContent);
12123
- if (this.isRequestedRoot(item, options)) this.updateCanonicalBaseUrl(effectiveSource, options);
12124
- const llmsTxtQueueItems = this.consumePendingLlmsTxtQueueItems(item, options);
12835
+ if (this.isRequestedRoot(item, options)) {
12836
+ this.updateCanonicalBaseUrl(effectiveSource, options);
12837
+ const startUrl = new URL(fetchedSource);
12838
+ if (startUrl.pathname !== new URL(url).pathname && !startUrl.pathname.endsWith("/")) startUrl.pathname = startUrl.pathname.replace(/\/[^/]*$/, "/");
12839
+ this.redirectedStartUrl = startUrl;
12840
+ }
12841
+ const llmsTxtQueueItems = await this.consumePendingLlmsTxtQueueItems(item, options);
12125
12842
  logger.debug(`Fetch result for ${url}: status=${rawContent.status}, etag=${rawContent.etag || "none"}`);
12126
12843
  if (rawContent.status !== FetchStatus.SUCCESS) {
12127
12844
  logger.debug(`Skipping pipeline for ${url} due to status: ${rawContent.status}`);
@@ -12179,7 +12896,6 @@ var WebScraperStrategy = class extends BaseScraperStrategy {
12179
12896
  const targetUrl = new URL(link, effectiveSource);
12180
12897
  if (isArchivePath(targetUrl.pathname)) return [];
12181
12898
  if (!this.canProcessDiscoveredLink(targetUrl)) return [];
12182
- if (!this.shouldProcessUrl(targetUrl.href, options)) return [];
12183
12899
  if (this.shouldFollowLinkFn) {
12184
12900
  const baseUrl = this.canonicalBaseUrl ?? new URL(options.url);
12185
12901
  return this.shouldFollowLinkFn(baseUrl, targetUrl) ? [targetUrl.href] : [];
@@ -12209,7 +12925,7 @@ var WebScraperStrategy = class extends BaseScraperStrategy {
12209
12925
  async scrape(options, progressCallback, signal) {
12210
12926
  this.pendingLlmsTxtProbe = null;
12211
12927
  this.pendingLlmsTxtProbe = await this.probeLlmsTxt(options.url, options.url, options, signal);
12212
- await super.scrape(options, progressCallback, signal);
12928
+ return super.scrape(options, progressCallback, signal);
12213
12929
  }
12214
12930
  async processRootArchive(item, options, signal) {
12215
12931
  logger.info(`📦 Downloading root archive: ${item.url}`);
@@ -12230,18 +12946,13 @@ var WebScraperStrategy = class extends BaseScraperStrategy {
12230
12946
  const localUrl = `file://${tempFile}`;
12231
12947
  const localItem = {
12232
12948
  ...item,
12233
- url: localUrl
12234
- };
12235
- const localOptions = {
12236
- ...options,
12237
- internalAllowedFileRoots: [...options.internalAllowedFileRoots ?? [], tempFile]
12949
+ url: localUrl,
12950
+ internalAllowedFileRoots: [...item.internalAllowedFileRoots ?? [], tempFile]
12238
12951
  };
12239
- const result = await this.localFileStrategy.processItem(localItem, localOptions, signal);
12240
12952
  return {
12241
- ...result,
12953
+ ...await this.localFileStrategy.processItem(localItem, options, signal),
12242
12954
  url: item.url,
12243
- links: result.links,
12244
- internalAllowedFileRoots: [tempFile]
12955
+ links: []
12245
12956
  };
12246
12957
  }
12247
12958
  /**
@@ -12267,7 +12978,7 @@ var NpmScraperStrategy = class {
12267
12978
  } });
12268
12979
  }
12269
12980
  async scrape(options, progressCallback, signal) {
12270
- await this.defaultStrategy.scrape(options, progressCallback, signal);
12981
+ return this.defaultStrategy.scrape(options, progressCallback, signal);
12271
12982
  }
12272
12983
  /**
12273
12984
  * Cleanup resources used by this strategy.
@@ -12287,7 +12998,7 @@ var PyPiScraperStrategy = class {
12287
12998
  } });
12288
12999
  }
12289
13000
  async scrape(options, progressCallback, signal) {
12290
- await this.defaultStrategy.scrape(options, progressCallback, signal);
13001
+ return this.defaultStrategy.scrape(options, progressCallback, signal);
12291
13002
  }
12292
13003
  /**
12293
13004
  * Cleanup resources used by this strategy.
@@ -12395,13 +13106,16 @@ var ScraperService = class {
12395
13106
  * Scrapes content from the provided URL using the appropriate strategy.
12396
13107
  * Reports progress via callback and handles errors.
12397
13108
  * Cleans up strategy resources after scrape completes (success or failure).
13109
+ *
13110
+ * @returns Why discovered links were rejected, for diagnosing an empty result.
12398
13111
  */
12399
13112
  async scrape(options, progressCallback, signal) {
12400
13113
  const strategy = this.registry.getStrategy(options.url);
13114
+ let summary = { rejections: [] };
12401
13115
  let scrapeError = null;
12402
13116
  let cleanupErrorToThrow = null;
12403
13117
  try {
12404
- await strategy.scrape(options, progressCallback, signal);
13118
+ summary = await strategy.scrape(options, progressCallback, signal);
12405
13119
  } catch (error) {
12406
13120
  scrapeError = error instanceof Error ? error : new ScraperError(`Scrape failed for URL: ${options.url}`, false);
12407
13121
  } finally {
@@ -12414,6 +13128,7 @@ var ScraperService = class {
12414
13128
  }
12415
13129
  if (scrapeError) throw scrapeError;
12416
13130
  if (cleanupErrorToThrow) throw cleanupErrorToThrow;
13131
+ return summary;
12417
13132
  }
12418
13133
  };
12419
13134
  // src/pipeline/PipelineWorker.ts
@@ -12432,6 +13147,8 @@ var PipelineWorker = class {
12432
13147
  * Executes the given pipeline job.
12433
13148
  * @param job - The job to execute.
12434
13149
  * @param callbacks - Internal callbacks provided by the manager for reporting.
13150
+ * @returns A warning when the job leaves its version without searchable
13151
+ * content, naming why links were rejected; otherwise null.
12435
13152
  */
12436
13153
  async executeJob(job, callbacks) {
12437
13154
  const { id: jobId, library, version, scraperOptions, abortController } = job;
@@ -12439,24 +13156,28 @@ var PipelineWorker = class {
12439
13156
  logger.debug(`[${jobId}] Worker starting job for ${library}@${version}`);
12440
13157
  try {
12441
13158
  if (!scraperOptions.isRefresh && scraperOptions.clean !== false) {
12442
- await this.store.removeAllDocuments(library, version);
13159
+ await this.store.removeAllDocumentsByVersionId(job.versionId);
12443
13160
  logger.info(`💾 Cleared store for ${library}@${version || "latest"} before scraping.`);
12444
13161
  } else {
12445
13162
  const message = scraperOptions.isRefresh ? `🔄 Refresh operation - preserving existing data for ${library}@${version || "latest"}.` : `💾 Appending to store for ${library}@${version || "latest"} (clean=false).`;
12446
13163
  logger.info(message);
12447
13164
  }
12448
- await this.scraperService.scrape(scraperOptions, async (progress) => {
13165
+ const summary = await this.scraperService.scrape(scraperOptions, async (progress) => {
12449
13166
  if (signal.aborted) throw new CancellationError("Job cancelled during scraping progress");
12450
13167
  await callbacks.onJobProgress?.(job, progress);
12451
13168
  switch (progress.outcome) {
12452
13169
  case PageOutcome.Empty:
12453
- await this.recordEmptyPage(job, callbacks, library, version, progress);
13170
+ await this.recordEmptyPage(job, callbacks, progress);
12454
13171
  break;
12455
13172
  case PageOutcome.Absent:
12456
13173
  await this.removeDeletedPage(job, callbacks, progress);
12457
13174
  break;
13175
+ case PageOutcome.Excluded:
13176
+ await this.removeDeletedPage(job, callbacks, progress);
13177
+ logger.info(`🧹 [${job.id}] Removed page no longer admitted by the scrape options: ${progress.currentUrl}`);
13178
+ break;
12458
13179
  case PageOutcome.Stored:
12459
- await this.storeResult(job, callbacks, library, version, progress);
13180
+ await this.storeResult(job, callbacks, progress);
12460
13181
  break;
12461
13182
  case PageOutcome.Unchanged:
12462
13183
  case PageOutcome.Skipped:
@@ -12469,6 +13190,7 @@ var PipelineWorker = class {
12469
13190
  }, signal);
12470
13191
  if (signal.aborted) throw new CancellationError("Job cancelled");
12471
13192
  logger.debug(`[${jobId}] Worker finished job successfully.`);
13193
+ return await this.store.countChunksByVersionId(job.versionId) === 0 ? emptyVersionWarning(job, summary) : null;
12472
13194
  } catch (error) {
12473
13195
  logger.warn(`⚠️ [${jobId}] Worker encountered error: ${error}`);
12474
13196
  throw error;
@@ -12481,7 +13203,7 @@ var PipelineWorker = class {
12481
13203
  * content is left alone: we learned nothing about the page, and overwriting it
12482
13204
  * would discard good content on a transient fault.
12483
13205
  */
12484
- async recordEmptyPage(job, callbacks, library, version, progress) {
13206
+ async recordEmptyPage(job, callbacks, progress) {
12485
13207
  const { emptyPage } = progress;
12486
13208
  if (!emptyPage) {
12487
13209
  await this.removeDeletedPage(job, callbacks, progress);
@@ -12492,7 +13214,7 @@ var PipelineWorker = class {
12492
13214
  return;
12493
13215
  }
12494
13216
  try {
12495
- await this.store.addEmptyPage(library, version, progress.depth, {
13217
+ await this.store.addEmptyPageByVersionId(job.versionId, progress.depth, {
12496
13218
  url: emptyPage.url,
12497
13219
  contentUrl: emptyPage.contentUrl,
12498
13220
  title: emptyPage.title,
@@ -12529,10 +13251,10 @@ var PipelineWorker = class {
12529
13251
  /**
12530
13252
  * Stores processed content, replacing the page's previous content on refresh.
12531
13253
  */
12532
- async storeResult(job, callbacks, library, version, progress) {
13254
+ async storeResult(job, callbacks, progress) {
12533
13255
  if (!progress.result) return;
12534
13256
  try {
12535
- await this.store.addScrapeResult(library, version, progress.depth, progress.result, progress.pageId);
13257
+ await this.store.addScrapeResultByVersionId(job.versionId, progress.depth, progress.result, progress.pageId);
12536
13258
  logger.debug(`[${job.id}] Stored processed content: ${progress.currentUrl}`);
12537
13259
  } catch (docError) {
12538
13260
  logger.error(`❌ [${job.id}] Failed to process content ${progress.currentUrl}: ${docError}`);
@@ -12541,6 +13263,22 @@ var PipelineWorker = class {
12541
13263
  }
12542
13264
  }
12543
13265
  };
13266
+ /**
13267
+ * Words the warning for a job that left its version without searchable
13268
+ * content, naming the most frequent reason links were rejected.
13269
+ *
13270
+ * @param job The finished job.
13271
+ * @param summary What the scrape reported about rejected links.
13272
+ * @returns The warning text.
13273
+ */
13274
+ function emptyVersionWarning(job, summary) {
13275
+ const name = `${job.library}@${job.version || "latest"}`;
13276
+ const top = summary.rejections[0];
13277
+ if (!top) return `No documents were stored for ${name}: the source yielded no indexable content.`;
13278
+ const links = top.count === 1 ? "1 link was" : `${top.count} links were`;
13279
+ const defaultsNote = top.rejection.check === "exclude" && job.scraperOptions.excludePatterns === void 0 ? "; default exclude patterns apply unless excludePatterns is set" : "";
13280
+ return `No documents were stored for ${name}. ${links} skipped as ${describeLinkRejection(top.rejection)}${defaultsNote}.`;
13281
+ }
12544
13282
  // src/pipeline/PipelineManager.ts
12545
13283
  /**
12546
13284
  * PipelineManager orchestrates a queue of scraping/indexing jobs.
@@ -12606,15 +13344,25 @@ var PipelineManager = class {
12606
13344
  }
12607
13345
  /**
12608
13346
  * Converts internal job representation to public job interface.
13347
+ * The processed page content (`progress.result`) stays on the internal job: it
13348
+ * can weigh hundreds of kilobytes per job and no consumer of the public job reads it.
13349
+ * The custom request headers stay internal too: they often carry credentials,
13350
+ * and the job returned here reaches every caller of `getJob`/`getJobs` and
13351
+ * every job event subscriber.
12609
13352
  */
12610
13353
  toPublicJob(job) {
13354
+ const { headers: _headers, ...reportedScraperOptions } = job.scraperOptions;
12611
13355
  return {
12612
13356
  id: job.id,
12613
13357
  library: job.library,
12614
13358
  version: job.version || null,
12615
13359
  status: job.status,
12616
- progress: job.progress,
13360
+ progress: job.progress ? {
13361
+ ...job.progress,
13362
+ result: null
13363
+ } : null,
12617
13364
  error: job.error ? { message: job.error.message } : null,
13365
+ warning: job.warning ?? null,
12618
13366
  createdAt: job.createdAt,
12619
13367
  startedAt: job.startedAt,
12620
13368
  finishedAt: job.finishedAt,
@@ -12626,7 +13374,7 @@ var PipelineManager = class {
12626
13374
  errorMessage: job.errorMessage,
12627
13375
  updatedAt: job.updatedAt,
12628
13376
  sourceUrl: job.sourceUrl,
12629
- scraperOptions: job.scraperOptions
13377
+ scraperOptions: reportedScraperOptions
12630
13378
  };
12631
13379
  }
12632
13380
  normalizeScraperOptions(options) {
@@ -12828,50 +13576,57 @@ var PipelineManager = class {
12828
13576
  async registerScrapeJob(library, normalizedVersion, options, enqueue) {
12829
13577
  const requested = enqueue.onExisting ?? "reject-version";
12830
13578
  const policy = options.clean === false && requested === "reject-version" ? "replace" : requested;
12831
- const claimed = await this.store.claimVersion(library, normalizedVersion, policy);
12832
- await this.stopJobsFor(library, normalizedVersion);
12833
- const label = formatVersionLabel(claimed.library, normalizedVersion);
12834
- const normalizedOptions = this.normalizeScraperOptions(options);
12835
- const jobId = v4();
12836
- const abortController = new AbortController();
12837
- let resolveCompletion;
12838
- let rejectCompletion;
12839
- const completionPromise = new Promise((resolve, reject) => {
12840
- resolveCompletion = resolve;
12841
- rejectCompletion = reject;
12842
- });
12843
- completionPromise.catch(() => {});
12844
- const job = {
12845
- id: jobId,
12846
- library: claimed.library,
12847
- version: normalizedVersion,
12848
- versionId: claimed.versionId,
12849
- status: PipelineJobStatus.QUEUED,
12850
- progress: null,
12851
- error: null,
12852
- createdAt: /* @__PURE__ */ new Date(),
12853
- startedAt: null,
12854
- finishedAt: null,
12855
- abortController,
12856
- completionPromise,
12857
- resolveCompletion,
12858
- rejectCompletion,
12859
- progressPages: 0,
12860
- progressPagesIndexed: 0,
12861
- progressMaxPages: 0,
12862
- errorMessage: null,
12863
- updatedAt: /* @__PURE__ */ new Date(),
12864
- sourceUrl: normalizedOptions.url,
12865
- scraperOptions: normalizedOptions
12866
- };
12867
- this.jobMap.set(jobId, job);
12868
- this.jobQueue.push(jobId);
12869
- logger.info(`📝 Job enqueued: ${jobId} for ${label}`);
12870
- await this.updateJobStatus(job, PipelineJobStatus.QUEUED);
12871
- if (this.isRunning) this._processQueue().catch((error) => {
12872
- logger.error(`❌ Error in processQueue during enqueue: ${error}`);
12873
- });
12874
- return jobId;
13579
+ const claimed = await this.store.claimVersion(library, normalizedVersion, policy, { markQueued: true });
13580
+ let registered = false;
13581
+ try {
13582
+ await this.stopJobsFor(library, normalizedVersion);
13583
+ const label = formatVersionLabel(claimed.library, normalizedVersion);
13584
+ const normalizedOptions = this.normalizeScraperOptions(options);
13585
+ const jobId = v4();
13586
+ const abortController = new AbortController();
13587
+ let resolveCompletion;
13588
+ let rejectCompletion;
13589
+ const completionPromise = new Promise((resolve, reject) => {
13590
+ resolveCompletion = resolve;
13591
+ rejectCompletion = reject;
13592
+ });
13593
+ completionPromise.catch(() => {});
13594
+ const job = {
13595
+ id: jobId,
13596
+ library: claimed.library,
13597
+ version: normalizedVersion,
13598
+ versionId: claimed.versionId,
13599
+ status: PipelineJobStatus.QUEUED,
13600
+ progress: null,
13601
+ error: null,
13602
+ createdAt: /* @__PURE__ */ new Date(),
13603
+ startedAt: null,
13604
+ finishedAt: null,
13605
+ abortController,
13606
+ completionPromise,
13607
+ resolveCompletion,
13608
+ rejectCompletion,
13609
+ progressPages: 0,
13610
+ progressPagesIndexed: 0,
13611
+ progressMaxPages: 0,
13612
+ errorMessage: null,
13613
+ updatedAt: /* @__PURE__ */ new Date(),
13614
+ sourceUrl: normalizedOptions.url,
13615
+ scraperOptions: normalizedOptions
13616
+ };
13617
+ this.jobMap.set(jobId, job);
13618
+ this.jobQueue.push(jobId);
13619
+ registered = true;
13620
+ logger.info(`📝 Job enqueued: ${jobId} for ${label}`);
13621
+ await this.updateJobStatus(job, PipelineJobStatus.QUEUED);
13622
+ if (this.isRunning) this._processQueue().catch((error) => {
13623
+ logger.error(`❌ Error in processQueue during enqueue: ${error}`);
13624
+ });
13625
+ return jobId;
13626
+ } catch (error) {
13627
+ if (!registered && claimed.previousStatus) await this.store.restoreVersionStatusIfQueued(claimed.versionId, claimed.previousStatus).catch(() => {});
13628
+ throw error;
13629
+ }
12875
13630
  }
12876
13631
  /**
12877
13632
  * Enqueues a refresh job for an existing library version by re-scraping all pages
@@ -13081,7 +13836,7 @@ var PipelineManager = class {
13081
13836
  const signal = abortController.signal;
13082
13837
  const worker = new PipelineWorker(this.store, this.scraperService);
13083
13838
  try {
13084
- await worker.executeJob(job, {
13839
+ const warning = await worker.executeJob(job, {
13085
13840
  onJobProgress: async (internalJob, progress) => {
13086
13841
  await this.updateJobProgress(internalJob, progress);
13087
13842
  },
@@ -13090,10 +13845,12 @@ var PipelineManager = class {
13090
13845
  }
13091
13846
  });
13092
13847
  if (signal.aborted) throw new CancellationError("Job cancelled just before completion");
13848
+ job.warning = warning;
13093
13849
  await this.updateJobStatus(job, PipelineJobStatus.COMPLETED);
13094
13850
  job.finishedAt = /* @__PURE__ */ new Date();
13095
13851
  job.resolveCompletion();
13096
- logger.info(`✅ Job completed: ${jobId}`);
13852
+ if (warning) logger.warn(`⚠️ Job completed with a warning: ${jobId}: ${warning}`);
13853
+ else logger.info(`✅ Job completed: ${jobId}`);
13097
13854
  } catch (error) {
13098
13855
  if (error instanceof CancellationError || signal.aborted) {
13099
13856
  await this.updateJobStatus(job, PipelineJobStatus.CANCELLED);
@@ -13173,7 +13930,10 @@ var PipelineManager = class {
13173
13930
  const publicJob = this.toPublicJob(job);
13174
13931
  this.eventBus.emit(EventType.JOB_PROGRESS, {
13175
13932
  job: publicJob,
13176
- progress
13933
+ progress: {
13934
+ ...progress,
13935
+ result: null
13936
+ }
13177
13937
  });
13178
13938
  logger.debug(`Job ${job.id} progress: ${progress.pagesScraped}/${progress.totalPages} processed, ${progress.pagesIndexed} indexed`);
13179
13939
  }
@@ -13245,6 +14005,12 @@ var DocumentManagementClient = class {
13245
14005
  async compact(options) {
13246
14006
  return this.client.compact.mutate(options ?? {});
13247
14007
  }
14008
+ async renameLibrary(library, newName) {
14009
+ return this.client.renameLibrary.mutate({
14010
+ library,
14011
+ newName
14012
+ });
14013
+ }
13248
14014
  async getVersionsByStatus(statuses) {
13249
14015
  return this.client.getVersionsByStatus.query({ statuses });
13250
14016
  }
@@ -14029,7 +14795,6 @@ async function applyMigrations(db, options) {
14029
14795
  db.pragma("synchronous = NORMAL");
14030
14796
  db.pragma("mmap_size = 268435456");
14031
14797
  db.pragma("cache_size = -64000");
14032
- db.pragma("temp_store = MEMORY");
14033
14798
  logger.debug("Applied safe migration pragmas");
14034
14799
  } catch (_error) {
14035
14800
  logger.warn("⚠️ Could not apply all migration pragmas");
@@ -14094,6 +14859,28 @@ async function applyMigrations(db, options) {
14094
14859
  logger.warn("⚠️ Could not apply all production database settings");
14095
14860
  }
14096
14861
  }
14862
+ /**
14863
+ * Opens a better-sqlite3 database. Open databases only through this function,
14864
+ * so a binary that cannot load ends in one actionable error instead of a raw
14865
+ * module resolution failure or a crash.
14866
+ *
14867
+ * @param dbPath - Path of the database file, or `:memory:`
14868
+ * @param options - better-sqlite3 options, such as `readonly`
14869
+ * @returns The open database
14870
+ * @throws NodeApiUnsupportedError when the runtime provides an older Node-API version than the binary needs
14871
+ * @throws NativeModuleUnavailableError when no better-sqlite3 binary loads on this platform
14872
+ */
14873
+ function openDatabase(dbPath, options = {}) {
14874
+ const nodeApi = process.versions.napi;
14875
+ if (nodeApi !== void 0 && Number(nodeApi) < 10) throw new NodeApiUnsupportedError(nodeApi, 10);
14876
+ try {
14877
+ return new Database(dbPath, options);
14878
+ } catch (error) {
14879
+ if (!isNativeModuleError(error)) throw error;
14880
+ logger.debug(`Failed to load better-sqlite3: ${error}`);
14881
+ throw new NativeModuleUnavailableError();
14882
+ }
14883
+ }
14097
14884
  // src/store/DocumentStore.ts
14098
14885
  /**
14099
14886
  * How many full-text candidates are sorted by score alone before the
@@ -14104,6 +14891,13 @@ async function applyMigrations(db, options) {
14104
14891
  */
14105
14892
  var FTS_TIE_WINDOW_FACTOR = 2;
14106
14893
  /**
14894
+ * The shortest beginning of a text worth halving again when the provider keeps
14895
+ * rejecting it as too large. A provider that still refuses this little has a
14896
+ * limit far below any chunk size, which is a configuration fault to report
14897
+ * rather than retry.
14898
+ */
14899
+ var MIN_TRUNCATED_EMBEDDING_CHARS = 256;
14900
+ /**
14107
14901
  * Orders search results that score the same: by page URL, then by position on
14108
14902
  * the page. Without it, ties fall to storage order, which depends on when and
14109
14903
  * how fast each page was indexed.
@@ -14245,7 +15039,7 @@ var DocumentStore = class {
14245
15039
  this.embeddingBatchSize = this.config.embeddings.batchSize;
14246
15040
  this.embeddingBatchChars = this.config.embeddings.batchChars;
14247
15041
  this.embeddingInitTimeoutMs = this.config.embeddings.initTimeoutMs;
14248
- this.db = new Database(dbPath);
15042
+ this.db = openDatabase(dbPath);
14249
15043
  this.embeddingConfig = this.resolveEmbeddingConfig(appConfig.app.embeddingModel);
14250
15044
  }
14251
15045
  resolveEmbeddingConfig(modelSpec) {
@@ -14277,8 +15071,11 @@ var DocumentStore = class {
14277
15071
  getPageId: this.db.prepare("SELECT id, source_content_type FROM pages WHERE version_id = ? AND url = ?"),
14278
15072
  insertLibrary: this.db.prepare("INSERT INTO libraries (name, display_name) VALUES (?, ?)"),
14279
15073
  getLibraryIdByName: this.db.prepare("SELECT id, display_name FROM libraries WHERE name = ?"),
15074
+ renameLibrary: this.db.prepare("UPDATE libraries SET name = ?, display_name = ? WHERE id = ?"),
15075
+ getActiveVersionStatusesByLibraryId: this.db.prepare("SELECT DISTINCT status FROM versions WHERE library_id = ? AND status IN ('queued', 'running', 'updating')"),
14280
15076
  getLibraryById: this.db.prepare("SELECT * FROM libraries WHERE id = ?"),
14281
15077
  insertVersion: this.db.prepare("INSERT INTO versions (library_id, name, status) VALUES (?, ?, 'not_indexed') ON CONFLICT(library_id, name) DO NOTHING"),
15078
+ markVersionQueued: this.db.prepare("UPDATE versions SET status = 'queued' WHERE id = ?"),
14282
15079
  resolveVersionId: this.db.prepare("SELECT id FROM versions WHERE library_id = ? AND name = ?"),
14283
15080
  getVersionById: this.db.prepare("SELECT * FROM versions WHERE id = ?"),
14284
15081
  queryVersionsByLibraryId: this.db.prepare("SELECT * FROM versions WHERE library_id = ? ORDER BY name"),
@@ -14297,6 +15094,8 @@ var DocumentStore = class {
14297
15094
  JOIN libraries l ON v.library_id = l.id
14298
15095
  WHERE l.name = ? AND COALESCE(v.name, '') = COALESCE(?, '')
14299
15096
  )`),
15097
+ deleteDocumentsByVersionId: this.db.prepare("DELETE FROM documents WHERE page_id IN (SELECT id FROM pages WHERE version_id = ?)"),
15098
+ deletePagesByVersionId: this.db.prepare("DELETE FROM pages WHERE version_id = ?"),
14300
15099
  getDocumentBySort: this.db.prepare(`SELECT d.id
14301
15100
  FROM documents d
14302
15101
  JOIN pages p ON d.page_id = p.id
@@ -14333,12 +15132,14 @@ var DocumentStore = class {
14333
15132
  -- the *first*-index time and never moves on refresh. Fall back to the
14334
15133
  -- oldest page for versions that predate status tracking.
14335
15134
  COALESCE(v.updated_at, MIN(p.created_at)) as indexedAt,
14336
- COUNT(d.id) as documentCount,
14337
- COUNT(DISTINCT p.url) as uniqueUrlCount
15135
+ -- Counts kept per page by migration 020's triggers, so the listing
15136
+ -- never reads the documents table. UNIQUE(version_id, url) makes
15137
+ -- each page of a version a distinct URL.
15138
+ COALESCE(SUM(p.chunk_count), 0) as documentCount,
15139
+ COUNT(p.id) as uniqueUrlCount
14338
15140
  FROM versions v
14339
15141
  JOIN libraries l ON v.library_id = l.id
14340
15142
  LEFT JOIN pages p ON p.version_id = v.id
14341
- LEFT JOIN documents d ON d.page_id = p.id
14342
15143
  GROUP BY v.id
14343
15144
  ORDER BY l.name, version`),
14344
15145
  getChildChunks: this.db.prepare(`
@@ -14923,7 +15724,7 @@ var DocumentStore = class {
14923
15724
  * @throws {VersionAlreadyExistsError} Policy `reject-version` and the version exists.
14924
15725
  * @throws {InvalidLibraryNameError} The library is new and its name fails validation.
14925
15726
  */
14926
- async claimVersion(library, version, policy) {
15727
+ async claimVersion(library, version, policy, options) {
14927
15728
  const label = normalizeVersionLabel(version);
14928
15729
  const storedVersion = denormalizeVersionName(label);
14929
15730
  return this.db.transaction(() => {
@@ -14931,6 +15732,15 @@ var DocumentStore = class {
14931
15732
  if (this.statements.insertVersion.run(libraryRow.id, storedVersion).changes === 0 && policy === "reject-version") throw new VersionAlreadyExistsError(libraryRow.displayName, label);
14932
15733
  const versionIdRow = this.statements.resolveVersionId.get(libraryRow.id, storedVersion);
14933
15734
  if (!versionIdRow) throw new StoreError(`Failed to resolve version_id for library: ${quoteName(library)}, version: ${quoteName(version)}`);
15735
+ if (options?.markQueued) {
15736
+ const current = this.statements.getVersionById.get(versionIdRow.id);
15737
+ this.statements.markVersionQueued.run(versionIdRow.id);
15738
+ return {
15739
+ versionId: versionIdRow.id,
15740
+ library: libraryRow.displayName,
15741
+ previousStatus: current.status
15742
+ };
15743
+ }
14934
15744
  return {
14935
15745
  versionId: versionIdRow.id,
14936
15746
  library: libraryRow.displayName
@@ -15004,6 +15814,18 @@ var DocumentStore = class {
15004
15814
  }
15005
15815
  }
15006
15816
  /**
15817
+ * Puts a version's status back, but only while it is still `queued`.
15818
+ * Used to undo the reservation a claim made when the enqueue fails before a
15819
+ * job is registered, without overwriting a status a job wrote in the meantime.
15820
+ */
15821
+ async restoreVersionStatusIfQueued(versionId, status) {
15822
+ try {
15823
+ this.db.prepare("UPDATE versions SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND status = ?").run(status, versionId, VersionStatus.QUEUED);
15824
+ } catch (error) {
15825
+ throw new StoreError(`Failed to restore version status: ${error}`);
15826
+ }
15827
+ }
15828
+ /**
15007
15829
  * Updates the progress counters for a version being indexed.
15008
15830
  * @param versionId The version ID to update
15009
15831
  * @param pages Current number of pages processed
@@ -15105,6 +15927,43 @@ var DocumentStore = class {
15105
15927
  }
15106
15928
  }
15107
15929
  /**
15930
+ * Renames a library in place: one transaction updates the lookup key and the
15931
+ * display name, leaving versions, pages, chunks and embeddings untouched.
15932
+ *
15933
+ * Runs as one IMMEDIATE transaction with no `await` inside, mirroring
15934
+ * {@link claimVersion}: the database decides a race, and a rename cannot
15935
+ * interleave with a concurrent claim or another rename.
15936
+ *
15937
+ * @param library Current library name, in any casing or padding.
15938
+ * @param newName New name as entered; the trimmed form becomes the display name.
15939
+ * @returns The previous and new display names, or `null` when the library does not exist.
15940
+ * @throws {InvalidLibraryNameError} The new name fails validation.
15941
+ * @throws {LibraryAlreadyExistsError} A different library already uses the new name.
15942
+ * @throws {LibraryBusyError} The library has an indexing job in flight.
15943
+ */
15944
+ async renameLibrary(library, newName) {
15945
+ const displayName = normalizeLibraryDisplayName(newName);
15946
+ const problem = describeLibraryNameProblem(displayName);
15947
+ if (problem) throw new InvalidLibraryNameError(displayName, problem);
15948
+ const oldKey = normalizeLibraryName(library);
15949
+ const newKey = normalizeLibraryName(newName);
15950
+ return this.db.transaction(() => {
15951
+ const row = this.statements.getLibraryIdByName.get(oldKey);
15952
+ if (!row) return null;
15953
+ const active = this.statements.getActiveVersionStatusesByLibraryId.all(row.id);
15954
+ if (active.length > 0) throw new LibraryBusyError(row.display_name, active.map((a) => a.status));
15955
+ if (newKey !== oldKey) {
15956
+ const conflict = this.statements.getLibraryIdByName.get(newKey);
15957
+ if (conflict) throw new LibraryAlreadyExistsError(conflict.display_name);
15958
+ }
15959
+ this.statements.renameLibrary.run(newKey, displayName, row.id);
15960
+ return {
15961
+ oldName: row.display_name,
15962
+ newName: displayName
15963
+ };
15964
+ }).immediate();
15965
+ }
15966
+ /**
15108
15967
  * Deletes a library by its ID.
15109
15968
  * This should only be called when the library has no remaining versions.
15110
15969
  * @param libraryId The library ID to delete
@@ -15236,18 +16095,19 @@ var DocumentStore = class {
15236
16095
  * Creates embeddings for an array of texts with automatic retry logic for size-related errors.
15237
16096
  * If a batch fails due to size limits:
15238
16097
  * - Batches with multiple texts are split in half and retried recursively
15239
- * - Single texts that are too large are truncated and retried once
16098
+ * - A single text that is too large is cut to its first half, again and
16099
+ * again, until the provider accepts it. The stored chunk keeps its full
16100
+ * text; only its vector is computed from the beginning.
15240
16101
  *
15241
16102
  * @param texts Array of texts to embed
15242
16103
  * @param isRetry Internal flag to prevent duplicate warning logs
15243
- * @param hasTruncatedSingleText Whether a single text has already been truncated once
15244
16104
  * @returns Array of embedding vectors
15245
16105
  */
15246
- async embedDocumentsWithRetry(texts, isRetry = false, hasTruncatedSingleText = false) {
16106
+ async embedDocumentsWithRetry(texts, isRetry = false) {
15247
16107
  if (texts.length === 0) return [];
16108
+ const embeddings = this.embeddings;
16109
+ if (embeddings === null) throw new StoreError("Embeddings are not initialized");
15248
16110
  try {
15249
- const embeddings = this.embeddings;
15250
- if (embeddings === null) throw new StoreError("Embeddings are not initialized");
15251
16111
  return await embeddings.embedDocuments(texts);
15252
16112
  } catch (error) {
15253
16113
  if (this.isInputSizeError(error)) {
@@ -15256,26 +16116,44 @@ var DocumentStore = class {
15256
16116
  const firstHalf = texts.slice(0, midpoint);
15257
16117
  const secondHalf = texts.slice(midpoint);
15258
16118
  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)]);
16119
+ const [firstEmbeddings, secondEmbeddings] = await Promise.all([this.embedDocumentsWithRetry(firstHalf, true), this.embedDocumentsWithRetry(secondHalf, true)]);
15260
16120
  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
- }
15273
16121
  }
16122
+ return await this.embedBeginningOf(embeddings, texts[0]);
15274
16123
  }
15275
16124
  throw error;
15276
16125
  }
15277
16126
  }
15278
16127
  /**
16128
+ * Embeds the beginning of a single text the provider rejected as too large.
16129
+ *
16130
+ * The text is halved until the provider accepts it, since one halving is not
16131
+ * enough when a text is several times over the limit. The first halving
16132
+ * always runs; later ones stop below `MIN_TRUNCATED_EMBEDDING_CHARS`. The
16133
+ * beginning holds the title, URL and path header and typically the most
16134
+ * important context.
16135
+ *
16136
+ * @param embeddings The embedding model that rejected the text.
16137
+ * @param text The rejected text.
16138
+ * @returns The embedding of the longest beginning the provider accepted.
16139
+ */
16140
+ async embedBeginningOf(embeddings, text) {
16141
+ logger.warn(`⚠️ Single text exceeded embedding size limit (${text.length} chars), embedding its beginning only.`);
16142
+ let beginning = text.substring(0, Math.floor(text.length / 2));
16143
+ let lastError;
16144
+ do {
16145
+ try {
16146
+ return await embeddings.embedDocuments([beginning]);
16147
+ } catch (error) {
16148
+ lastError = error;
16149
+ if (!this.isInputSizeError(error)) break;
16150
+ }
16151
+ beginning = beginning.substring(0, Math.floor(beginning.length / 2));
16152
+ } while (beginning.length >= MIN_TRUNCATED_EMBEDDING_CHARS);
16153
+ logger.error(`❌ Failed to embed even after truncating. Original length: ${text.length}`);
16154
+ throw lastError;
16155
+ }
16156
+ /**
15279
16157
  * Removes the row a refreshed page was read from, when it is not the row now
15280
16158
  * being written.
15281
16159
  *
@@ -15313,120 +16191,188 @@ var DocumentStore = class {
15313
16191
  async addEmptyPage(library, version, depth, page, previousPageId) {
15314
16192
  try {
15315
16193
  const versionId = await this.resolveVersionId(library, version);
15316
- this.db.transaction(() => {
15317
- const current = this.statements.getPageId.get(versionId, page.url);
15318
- if (losesToStoredRepresentation(current, page.sourceContentType, page.isAdditionalRepresentation)) {
15319
- logger.debug(`Keeping stored ${current?.source_content_type} representation of ${page.url}; ignoring empty ${page.sourceContentType} version`);
15320
- this.retirePreviousPage(previousPageId, current);
15321
- return;
15322
- }
15323
- this.retirePreviousPage(previousPageId, current);
15324
- this.statements.insertPage.run(versionId, page.url, page.title || "", page.etag, page.lastModified, page.sourceContentType, page.contentType, depth, page.contentUrl ?? null);
15325
- const stored = current ?? this.statements.getPageId.get(versionId, page.url);
15326
- if (stored) this.statements.deleteDocumentsByPageId.run(stored.id);
15327
- })();
16194
+ this.addEmptyPageToVersion(versionId, depth, page, previousPageId);
16195
+ } catch (error) {
16196
+ throw new StoreError(`Failed to record empty page: ${error}`);
16197
+ }
16198
+ }
16199
+ /**
16200
+ * Records a page that exists but holds no content under a version the
16201
+ * caller has already resolved.
16202
+ *
16203
+ * Addressing by version id keeps a claimed job's write on the version it
16204
+ * claimed: resolving by name instead would recreate the library under its
16205
+ * old name when a rename landed after the claim.
16206
+ *
16207
+ * @param versionId ID of the version the page belongs to.
16208
+ * @param depth Crawl depth the page was found at.
16209
+ * @param page Page identity and optional validators.
16210
+ * @param previousPageId Page a refresh read this page from, retired when the
16211
+ * write lands under a different row.
16212
+ */
16213
+ async addEmptyPageByVersionId(versionId, depth, page, previousPageId) {
16214
+ try {
16215
+ this.addEmptyPageToVersion(versionId, depth, page, previousPageId);
15328
16216
  } catch (error) {
15329
16217
  throw new StoreError(`Failed to record empty page: ${error}`);
15330
16218
  }
15331
16219
  }
15332
16220
  /**
16221
+ * Writes the empty-page record for a resolved version, in one transaction.
16222
+ *
16223
+ * @param versionId ID of the version the page belongs to.
16224
+ * @param depth Crawl depth the page was found at.
16225
+ * @param page Page identity and optional validators.
16226
+ * @param previousPageId Page a refresh read this page from, if any.
16227
+ */
16228
+ addEmptyPageToVersion(versionId, depth, page, previousPageId) {
16229
+ this.db.transaction(() => {
16230
+ const current = this.statements.getPageId.get(versionId, page.url);
16231
+ if (losesToStoredRepresentation(current, page.sourceContentType, page.isAdditionalRepresentation)) {
16232
+ logger.debug(`Keeping stored ${current?.source_content_type} representation of ${page.url}; ignoring empty ${page.sourceContentType} version`);
16233
+ this.retirePreviousPage(previousPageId, current);
16234
+ return;
16235
+ }
16236
+ this.retirePreviousPage(previousPageId, current);
16237
+ this.statements.insertPage.run(versionId, page.url, page.title || "", page.etag, page.lastModified, page.sourceContentType, page.contentType, depth, page.contentUrl ?? null);
16238
+ const stored = current ?? this.statements.getPageId.get(versionId, page.url);
16239
+ if (stored) this.statements.deleteDocumentsByPageId.run(stored.id);
16240
+ })();
16241
+ }
16242
+ /**
15333
16243
  * Stores documents with library and version metadata, generating embeddings
15334
16244
  * for vector similarity search. Uses the new pages table to normalize page-level
15335
16245
  * metadata and avoid duplication across document chunks.
15336
16246
  */
15337
16247
  async addDocuments(library, version, depth, result, previousPageId) {
15338
16248
  try {
15339
- const { title, url, chunks } = result;
15340
- if (chunks.length === 0) return;
16249
+ if (result.chunks.length === 0) return;
15341
16250
  const versionId = await this.resolveVersionId(library, version);
15342
- const existingPage = this.statements.getPageId.get(versionId, url);
15343
- if (previousPageId === void 0 && losesToStoredRepresentation(existingPage, result.sourceContentType, result.isAdditionalRepresentation)) {
15344
- logger.debug(`Keeping stored ${existingPage?.source_content_type} representation of ${url}; ignoring ${result.sourceContentType} version`);
15345
- return;
15346
- }
15347
- let paddedEmbeddings = [];
15348
- if (this.isVectorSearchEnabled) {
15349
- const texts = chunks.map((chunk) => {
15350
- return `${`<title>${title}</title>\n<url>${url}</url>\n<path>${(chunk.section.path || []).join(" / ")}</path>\n`}${chunk.content}`;
15351
- });
15352
- for (let i = 0; i < chunks.length; i++) {
15353
- const bodySize = chunks[i].content.length;
15354
- if (bodySize > this.splitterMaxChunkSize) logger.warn(`⚠️ Chunk ${i + 1}/${chunks.length} body exceeds max size: ${bodySize} > ${this.splitterMaxChunkSize} chars (URL: ${url})`);
15355
- }
15356
- const maxBatchChars = this.embeddingBatchChars;
15357
- const rawEmbeddings = [];
15358
- let currentBatch = [];
15359
- let currentBatchSize = 0;
15360
- let batchCount = 0;
15361
- const processEmbeddingBatch = async (isFinalBatch = false) => {
15362
- batchCount++;
15363
- const batchTexts = currentBatch;
15364
- const batchChars = currentBatchSize;
15365
- logger.debug(`Processing ${isFinalBatch ? "final " : ""}embedding batch ${batchCount}: ${batchTexts.length} texts, ${batchChars} chars`);
15366
- try {
15367
- const batchEmbeddings = await this.embedDocumentsWithRetry(batchTexts);
15368
- rawEmbeddings.push(...batchEmbeddings);
15369
- } catch (error) {
15370
- throw this.createEmbeddingConnectionError(error, {
15371
- url,
15372
- batchIndex: batchCount,
15373
- batchTextCount: batchTexts.length,
15374
- batchChars,
15375
- totalChunks: chunks.length
15376
- });
15377
- }
15378
- currentBatch = [];
15379
- currentBatchSize = 0;
15380
- };
15381
- for (const text of texts) {
15382
- const textSize = text.length;
15383
- if (currentBatchSize + textSize > maxBatchChars && currentBatch.length > 0) await processEmbeddingBatch();
15384
- currentBatch.push(text);
15385
- currentBatchSize += textSize;
15386
- if (currentBatch.length >= this.embeddingBatchSize) await processEmbeddingBatch();
15387
- }
15388
- if (currentBatch.length > 0) await processEmbeddingBatch(true);
15389
- paddedEmbeddings = rawEmbeddings.map((vector) => this.padVector(vector));
15390
- }
15391
- this.db.transaction(() => {
15392
- const current = this.statements.getPageId.get(versionId, url);
15393
- if (losesToStoredRepresentation(current, result.sourceContentType, result.isAdditionalRepresentation)) {
15394
- logger.debug(`Keeping stored ${current?.source_content_type} representation of ${url}; ignoring ${result.sourceContentType} version`);
15395
- this.retirePreviousPage(previousPageId, current);
15396
- return false;
15397
- }
15398
- this.retirePreviousPage(previousPageId, current);
15399
- if (current) {
15400
- const deleted = this.statements.deleteDocumentsByPageId.run(current.id);
15401
- if (deleted.changes > 0) logger.debug(`Deleted ${deleted.changes} existing documents for URL: ${url}`);
15402
- }
15403
- const sourceContentType = result.sourceContentType || result.contentType || null;
15404
- const contentType = result.contentType || result.sourceContentType || null;
15405
- const etag = result.etag || null;
15406
- const lastModified = result.lastModified || null;
15407
- this.statements.insertPage.run(versionId, url, title || "", etag, lastModified, sourceContentType, contentType, depth, result.contentUrl ?? null);
15408
- const insertedPage = this.statements.getPageId.get(versionId, url);
15409
- if (!insertedPage) throw new StoreError(`Failed to get page ID for URL: ${url}`);
15410
- const pageId = insertedPage.id;
15411
- let docIndex = 0;
15412
- for (let i = 0; i < chunks.length; i++) {
15413
- const chunk = chunks[i];
15414
- const rowId = this.statements.insertDocument.run(pageId, chunk.content, JSON.stringify({
15415
- types: chunk.types,
15416
- level: chunk.section.level,
15417
- path: chunk.section.path
15418
- }), i).lastInsertRowid;
15419
- if (this.isVectorSearchEnabled && paddedEmbeddings.length > 0) this.statements.insertEmbedding.run(Buffer.from(new Float32Array(paddedEmbeddings[docIndex]).buffer), BigInt(rowId));
15420
- docIndex++;
15421
- }
15422
- return true;
15423
- })();
16251
+ await this.addDocumentsToVersion(versionId, depth, result, previousPageId);
16252
+ } catch (error) {
16253
+ if (error instanceof StoreError) throw error;
16254
+ throw new ConnectionError("Failed to add documents to store", error);
16255
+ }
16256
+ }
16257
+ /**
16258
+ * Stores documents under a version the caller has already resolved,
16259
+ * generating embeddings for vector similarity search.
16260
+ *
16261
+ * Addressing by version id keeps a claimed job's write on the version it
16262
+ * claimed: resolving by name instead would recreate the library under its
16263
+ * old name when a rename landed after the claim.
16264
+ *
16265
+ * @param versionId ID of the version the documents belong to.
16266
+ * @param depth Crawl depth the page was found at.
16267
+ * @param result The scrape result to store.
16268
+ * @param previousPageId Page a refresh read this content from, retired when
16269
+ * the write lands under a different row.
16270
+ */
16271
+ async addDocumentsByVersionId(versionId, depth, result, previousPageId) {
16272
+ try {
16273
+ await this.addDocumentsToVersion(versionId, depth, result, previousPageId);
15424
16274
  } catch (error) {
15425
16275
  if (error instanceof StoreError) throw error;
15426
16276
  throw new ConnectionError("Failed to add documents to store", error);
15427
16277
  }
15428
16278
  }
15429
16279
  /**
16280
+ * Writes one page of documents under a resolved version: retires the row a
16281
+ * refresh read the page from, replaces the page's chunks, and stores new
16282
+ * embeddings when vector search is enabled.
16283
+ *
16284
+ * @param versionId ID of the version the documents belong to.
16285
+ * @param depth Crawl depth the page was found at.
16286
+ * @param result The scrape result to store.
16287
+ * @param previousPageId Page a refresh read this content from, if any.
16288
+ */
16289
+ async addDocumentsToVersion(versionId, depth, result, previousPageId) {
16290
+ const { title, url, chunks } = result;
16291
+ if (chunks.length === 0) return;
16292
+ const existingPage = this.statements.getPageId.get(versionId, url);
16293
+ if (previousPageId === void 0 && losesToStoredRepresentation(existingPage, result.sourceContentType, result.isAdditionalRepresentation)) {
16294
+ logger.debug(`Keeping stored ${existingPage?.source_content_type} representation of ${url}; ignoring ${result.sourceContentType} version`);
16295
+ return;
16296
+ }
16297
+ let paddedEmbeddings = [];
16298
+ if (this.isVectorSearchEnabled) {
16299
+ const texts = chunks.map((chunk) => {
16300
+ return `${`<title>${title}</title>\n<url>${url}</url>\n<path>${(chunk.section.path || []).join(" / ")}</path>\n`}${chunk.content}`;
16301
+ });
16302
+ for (let i = 0; i < chunks.length; i++) {
16303
+ const bodySize = chunks[i].content.length;
16304
+ if (bodySize > this.splitterMaxChunkSize) logger.warn(`⚠️ Chunk ${i + 1}/${chunks.length} body exceeds max size: ${bodySize} > ${this.splitterMaxChunkSize} chars (URL: ${url})`);
16305
+ }
16306
+ const maxBatchChars = this.embeddingBatchChars;
16307
+ const rawEmbeddings = [];
16308
+ let currentBatch = [];
16309
+ let currentBatchSize = 0;
16310
+ let batchCount = 0;
16311
+ const processEmbeddingBatch = async (isFinalBatch = false) => {
16312
+ batchCount++;
16313
+ const batchTexts = currentBatch;
16314
+ const batchChars = currentBatchSize;
16315
+ logger.debug(`Processing ${isFinalBatch ? "final " : ""}embedding batch ${batchCount}: ${batchTexts.length} texts, ${batchChars} chars`);
16316
+ try {
16317
+ const batchEmbeddings = await this.embedDocumentsWithRetry(batchTexts);
16318
+ rawEmbeddings.push(...batchEmbeddings);
16319
+ } catch (error) {
16320
+ throw this.createEmbeddingConnectionError(error, {
16321
+ url,
16322
+ batchIndex: batchCount,
16323
+ batchTextCount: batchTexts.length,
16324
+ batchChars,
16325
+ totalChunks: chunks.length
16326
+ });
16327
+ }
16328
+ currentBatch = [];
16329
+ currentBatchSize = 0;
16330
+ };
16331
+ for (const text of texts) {
16332
+ const textSize = text.length;
16333
+ if (currentBatchSize + textSize > maxBatchChars && currentBatch.length > 0) await processEmbeddingBatch();
16334
+ currentBatch.push(text);
16335
+ currentBatchSize += textSize;
16336
+ if (currentBatch.length >= this.embeddingBatchSize) await processEmbeddingBatch();
16337
+ }
16338
+ if (currentBatch.length > 0) await processEmbeddingBatch(true);
16339
+ paddedEmbeddings = rawEmbeddings.map((vector) => this.padVector(vector));
16340
+ }
16341
+ this.db.transaction(() => {
16342
+ const current = this.statements.getPageId.get(versionId, url);
16343
+ if (losesToStoredRepresentation(current, result.sourceContentType, result.isAdditionalRepresentation)) {
16344
+ logger.debug(`Keeping stored ${current?.source_content_type} representation of ${url}; ignoring ${result.sourceContentType} version`);
16345
+ this.retirePreviousPage(previousPageId, current);
16346
+ return false;
16347
+ }
16348
+ this.retirePreviousPage(previousPageId, current);
16349
+ if (current) {
16350
+ const deleted = this.statements.deleteDocumentsByPageId.run(current.id);
16351
+ if (deleted.changes > 0) logger.debug(`Deleted ${deleted.changes} existing documents for URL: ${url}`);
16352
+ }
16353
+ const sourceContentType = result.sourceContentType || result.contentType || null;
16354
+ const contentType = result.contentType || result.sourceContentType || null;
16355
+ const etag = result.etag || null;
16356
+ const lastModified = result.lastModified || null;
16357
+ this.statements.insertPage.run(versionId, url, title || "", etag, lastModified, sourceContentType, contentType, depth, result.contentUrl ?? null);
16358
+ const insertedPage = this.statements.getPageId.get(versionId, url);
16359
+ if (!insertedPage) throw new StoreError(`Failed to get page ID for URL: ${url}`);
16360
+ const pageId = insertedPage.id;
16361
+ let docIndex = 0;
16362
+ for (let i = 0; i < chunks.length; i++) {
16363
+ const chunk = chunks[i];
16364
+ const rowId = this.statements.insertDocument.run(pageId, chunk.content, JSON.stringify({
16365
+ types: chunk.types,
16366
+ level: chunk.section.level,
16367
+ path: chunk.section.path
16368
+ }), i).lastInsertRowid;
16369
+ if (this.isVectorSearchEnabled && paddedEmbeddings.length > 0) this.statements.insertEmbedding.run(Buffer.from(new Float32Array(paddedEmbeddings[docIndex]).buffer), BigInt(rowId));
16370
+ docIndex++;
16371
+ }
16372
+ return true;
16373
+ })();
16374
+ }
16375
+ /**
15430
16376
  * Removes documents and pages matching specified library and version.
15431
16377
  * This consolidated method deletes both documents and their associated pages.
15432
16378
  * @returns Number of documents deleted
@@ -15449,6 +16395,34 @@ var DocumentStore = class {
15449
16395
  return changes;
15450
16396
  }
15451
16397
  /**
16398
+ * Removes documents and pages belonging to a version the caller has
16399
+ * already resolved.
16400
+ *
16401
+ * Addressing by version id keeps a claimed job's clear on the version it
16402
+ * claimed: resolving by name instead would silently delete nothing when a
16403
+ * rename landed after the claim.
16404
+ *
16405
+ * @param versionId ID of the version whose content is removed.
16406
+ * @returns Number of documents deleted.
16407
+ */
16408
+ async deletePagesByVersionId(versionId) {
16409
+ try {
16410
+ return this.deleteVersionContentById(versionId);
16411
+ } catch (error) {
16412
+ throw new ConnectionError("Failed to delete documents", error);
16413
+ }
16414
+ }
16415
+ /**
16416
+ * Deletes a version's documents by ID, then its pages (documents reference
16417
+ * pages). Synchronous so it can run inside a caller's transaction.
16418
+ * @returns The number of documents deleted.
16419
+ */
16420
+ deleteVersionContentById(versionId) {
16421
+ const { changes } = this.statements.deleteDocumentsByVersionId.run(versionId);
16422
+ this.statements.deletePagesByVersionId.run(versionId);
16423
+ return changes;
16424
+ }
16425
+ /**
15452
16426
  * Deletes a page and all its associated document chunks.
15453
16427
  * Performs manual deletion in the correct order to satisfy foreign key constraints:
15454
16428
  * 1. Delete document chunks (page_id references pages.id)
@@ -15478,6 +16452,19 @@ var DocumentStore = class {
15478
16452
  }
15479
16453
  }
15480
16454
  /**
16455
+ * Counts the searchable chunks a version holds, from the per-page counts.
16456
+ *
16457
+ * @param versionId The version's row id.
16458
+ * @returns The number of chunks stored for the version.
16459
+ */
16460
+ async countChunksByVersionId(versionId) {
16461
+ try {
16462
+ return this.db.prepare("SELECT COALESCE(SUM(chunk_count), 0) AS chunks FROM pages WHERE version_id = ?").get(versionId).chunks;
16463
+ } catch (error) {
16464
+ throw new ConnectionError("Failed to count chunks by version ID", error);
16465
+ }
16466
+ }
16467
+ /**
15481
16468
  * Finds pages whose URL or content URL equals one of the candidates.
15482
16469
  *
15483
16470
  * @param library Library name.
@@ -16185,6 +17172,14 @@ var DocumentManagementService = class DocumentManagementService {
16185
17172
  return this.store.claimInterruptedVersion(versionId, updatedAt);
16186
17173
  }
16187
17174
  /**
17175
+ * Puts a version's status back, but only while it is still `queued`, and tells
17176
+ * views the library list changed.
17177
+ */
17178
+ async restoreVersionStatusIfQueued(versionId, status) {
17179
+ await this.store.restoreVersionStatusIfQueued(versionId, status);
17180
+ this.eventBus.emit(EventType.LIBRARY_CHANGE, void 0);
17181
+ }
17182
+ /**
16188
17183
  * Updates the status of a version, and tells views the library list changed.
16189
17184
  */
16190
17185
  async updateVersionStatus(versionId, status, errorMessage) {
@@ -16223,8 +17218,8 @@ var DocumentManagementService = class DocumentManagementService {
16223
17218
  * Creates or verifies the library and version an indexing job writes into, atomically.
16224
17219
  * See {@link DocumentStore.claimVersion} for the policy semantics and errors.
16225
17220
  */
16226
- async claimVersion(library, version, policy) {
16227
- return this.store.claimVersion(library, version, policy);
17221
+ async claimVersion(library, version, policy, options) {
17222
+ return this.store.claimVersion(library, version, policy, options);
16228
17223
  }
16229
17224
  /**
16230
17225
  * Looks up a version that must already exist, without creating anything.
@@ -16324,6 +17319,22 @@ var DocumentManagementService = class DocumentManagementService {
16324
17319
  return new LibraryNotFoundInStoreError(library, suggestions);
16325
17320
  }
16326
17321
  /**
17322
+ * Renames a library in place, keeping its versions and indexed content.
17323
+ *
17324
+ * @param library Current library name.
17325
+ * @param newName New name as entered; its trimmed form becomes the display name.
17326
+ * @returns The previous and new display names.
17327
+ * @throws {LibraryNotFoundInStoreError} If the library does not exist.
17328
+ */
17329
+ async renameLibrary(library, newName) {
17330
+ logger.info(`✏️ Renaming library: ${library} -> ${newName}`);
17331
+ const renamed = await this.store.renameLibrary(library, newName);
17332
+ if (!renamed) throw await this.libraryNotFound(library);
17333
+ this.eventBus.emit(EventType.LIBRARY_CHANGE, void 0);
17334
+ logger.info(`✅ Renamed '${renamed.oldName}' to '${renamed.newName}'.`);
17335
+ return renamed;
17336
+ }
17337
+ /**
16327
17338
  * Returns every label stored for a library — semantic versions and opaque tags
16328
17339
  * alike — in canonical display order.
16329
17340
  *
@@ -16469,6 +17480,24 @@ var DocumentManagementService = class DocumentManagementService {
16469
17480
  this.eventBus.emit(EventType.LIBRARY_CHANGE, void 0);
16470
17481
  }
16471
17482
  /**
17483
+ * Removes all documents for a version the caller has already resolved.
17484
+ * Used by the scraping pipeline, whose jobs clear the version they
17485
+ * claimed before scraping.
17486
+ *
17487
+ * Addressing by version id keeps the clear on the claimed version:
17488
+ * resolving by name instead would silently delete nothing when a rename
17489
+ * landed after the claim.
17490
+ *
17491
+ * @param versionId ID of the version whose documents are removed.
17492
+ */
17493
+ async removeAllDocumentsByVersionId(versionId) {
17494
+ logger.info(`🗑️ Removing all documents from version ${versionId} store`);
17495
+ const count = await this.store.deletePagesByVersionId(versionId);
17496
+ logger.info(`🗑️ Deleted ${count} documents`);
17497
+ await this.compactAfterDelete();
17498
+ this.eventBus.emit(EventType.LIBRARY_CHANGE, void 0);
17499
+ }
17500
+ /**
16472
17501
  * Deletes a page and all its associated document chunks.
16473
17502
  * This is used during refresh operations when a page returns 404 Not Found.
16474
17503
  */
@@ -16485,6 +17514,15 @@ var DocumentManagementService = class DocumentManagementService {
16485
17514
  return this.store.getPagesByVersionId(versionId);
16486
17515
  }
16487
17516
  /**
17517
+ * Counts the searchable chunks a version holds.
17518
+ *
17519
+ * @param versionId The version's row id.
17520
+ * @returns The number of chunks stored for the version.
17521
+ */
17522
+ async countChunksByVersionId(versionId) {
17523
+ return this.store.countChunksByVersionId(versionId);
17524
+ }
17525
+ /**
16488
17526
  * Completely removes a library version and all associated documents.
16489
17527
  * Also removes the library if no other versions remain.
16490
17528
  * If the specified version doesn't exist but the library exists with no versions, removes the library.
@@ -16557,6 +17595,27 @@ var DocumentManagementService = class DocumentManagementService {
16557
17595
  this.eventBus.emit(EventType.LIBRARY_CHANGE, void 0);
16558
17596
  }
16559
17597
  /**
17598
+ * Records a page that exists but holds no content under a version the
17599
+ * caller has already resolved, replacing anything stored for it
17600
+ * previously. Used by the scraping pipeline, whose jobs write to the
17601
+ * version they claimed.
17602
+ *
17603
+ * Addressing by version id keeps the write on the claimed version:
17604
+ * resolving by name instead would recreate the library under its old name
17605
+ * when a rename landed after the claim.
17606
+ *
17607
+ * @param versionId ID of the version the page belongs to.
17608
+ * @param depth Crawl depth the page was found at.
17609
+ * @param page Page identity and optional validators.
17610
+ * @param previousPageId Page a refresh read this page from, retired by the
17611
+ * store when the write lands under a different row.
17612
+ */
17613
+ async addEmptyPageByVersionId(versionId, depth, page, previousPageId) {
17614
+ if (!page.url) throw new StoreError("Empty page metadata must include a valid URL");
17615
+ await this.store.addEmptyPageByVersionId(versionId, depth, page, previousPageId);
17616
+ this.eventBus.emit(EventType.LIBRARY_CHANGE, void 0);
17617
+ }
17618
+ /**
16560
17619
  * Adds pre-processed content directly to the store.
16561
17620
  * This method is used when content has already been processed by a pipeline,
16562
17621
  * avoiding redundant processing. Used primarily by the scraping pipeline.
@@ -16568,8 +17627,47 @@ var DocumentManagementService = class DocumentManagementService {
16568
17627
  * store when the write lands under a different row.
16569
17628
  */
16570
17629
  async addScrapeResult(library, version, depth, result, previousPageId) {
16571
- const processingStart = performance.now();
16572
17630
  const normalizedVersion = normalizeVersionLabel(version);
17631
+ await this.storeScrapeResult(result, () => this.store.addDocuments(library, normalizedVersion, depth, result, previousPageId), {
17632
+ library,
17633
+ libraryVersion: normalizedVersion || null
17634
+ });
17635
+ }
17636
+ /**
17637
+ * Adds pre-processed content directly to a version the caller has already
17638
+ * resolved. Used by the scraping pipeline, whose jobs write to the version
17639
+ * they claimed.
17640
+ *
17641
+ * Addressing by version id keeps the write on the claimed version:
17642
+ * resolving by name instead would recreate the library under its old name
17643
+ * when a rename landed after the claim.
17644
+ *
17645
+ * @param versionId ID of the version the content belongs to.
17646
+ * @param depth Crawl depth the page was found at.
17647
+ * @param result Pre-processed content with chunks already created.
17648
+ * @param previousPageId Page a refresh read this content from, retired by
17649
+ * the store when the write lands under a different row.
17650
+ */
17651
+ async addScrapeResultByVersionId(versionId, depth, result, previousPageId) {
17652
+ const versionRow = await this.store.getVersionById(versionId);
17653
+ if (!versionRow) throw new StoreError(`Cannot add processed content to unknown version ID: ${versionId}`);
17654
+ const libraryRow = await this.store.getLibraryById(versionRow.library_id);
17655
+ await this.storeScrapeResult(result, () => this.store.addDocumentsByVersionId(versionId, depth, result, previousPageId), {
17656
+ library: libraryRow?.name ?? "",
17657
+ libraryVersion: normalizeVersionLabel(versionRow.name) || null
17658
+ });
17659
+ }
17660
+ /**
17661
+ * Stores pre-processed content through the given write, emitting the
17662
+ * library change event on success and tracking failures with native error
17663
+ * tracking.
17664
+ *
17665
+ * @param result Pre-processed content with chunks already created.
17666
+ * @param write The store write to perform.
17667
+ * @param ref Library and version labels for error tracking.
17668
+ */
17669
+ async storeScrapeResult(result, write, ref) {
17670
+ const processingStart = performance.now();
16573
17671
  const { url, title, chunks, contentType } = result;
16574
17672
  if (!url) throw new StoreError("Processed content metadata must include a valid URL");
16575
17673
  logger.info(`📚 Adding processed content: ${title || url}`);
@@ -16579,7 +17677,7 @@ var DocumentManagementService = class DocumentManagementService {
16579
17677
  }
16580
17678
  try {
16581
17679
  logger.info(`✂️ Storing ${chunks.length} pre-split chunks`);
16582
- await this.store.addDocuments(library, normalizedVersion, depth, result, previousPageId);
17680
+ await write();
16583
17681
  this.eventBus.emit(EventType.LIBRARY_CHANGE, void 0);
16584
17682
  } catch (error) {
16585
17683
  const processingTime = performance.now() - processingStart;
@@ -16587,8 +17685,8 @@ var DocumentManagementService = class DocumentManagementService {
16587
17685
  mimeType: contentType,
16588
17686
  contentSizeBytes: chunks.reduce((sum, chunk) => sum + chunk.content.length, 0),
16589
17687
  processingTimeMs: Math.round(processingTime),
16590
- library,
16591
- libraryVersion: normalizedVersion || null,
17688
+ library: ref.library,
17689
+ libraryVersion: ref.libraryVersion,
16592
17690
  context: "processed_content_storage",
16593
17691
  component: DocumentManagementService.constructor.name
16594
17692
  });
@@ -17827,7 +18925,8 @@ function createToolInputSchemas(config) {
17827
18925
  replace: z.boolean().optional().default(false).describe("Rebuild the version from scratch if it already exists. Without it, an existing version is left untouched and the request fails."),
17828
18926
  preserveHashes: z.boolean().optional().describe("Preserve hash fragments for hash-routed SPA documentation sites."),
17829
18927
  includePatterns: patternsSchema.optional().describe("Patterns for including URLs during scraping. Pass one or more patterns as a comma-separated string or as an array. Commas inside { }, [ ] or ( ) are preserved; escape a literal comma with a backslash. Regex patterns must be wrapped in slashes, e.g. /pattern/. If not set, all are included by default."),
17830
- excludePatterns: patternsSchema.optional().describe("Patterns for excluding URLs during scraping. Pass one or more patterns as a comma-separated string or as an array. Commas inside { }, [ ] or ( ) are preserved; escape a literal comma with a backslash. Exclude takes precedence over include. Regex patterns must be wrapped in slashes, e.g. /pattern/.")
18928
+ excludePatterns: patternsSchema.optional().describe("Patterns for excluding URLs during scraping. Pass one or more patterns as a comma-separated string or as an array. Commas inside { }, [ ] or ( ) are preserved; escape a literal comma with a backslash. Exclude takes precedence over include. Regex patterns must be wrapped in slashes, e.g. /pattern/. Globs starting with **/ match only below the scraped URL. If not set, built-in default patterns exclude changelogs, licenses, and test, build, archive and non-English locale folders; any value, even an empty one, replaces the defaults."),
18929
+ respectGitignore: z.boolean().optional().describe("For file:// directories, skip files matched by .gitignore rules in the indexed folder and below. Rules in parent folders, global excludes, and .git/info/exclude are not applied. Defaults to true.")
17831
18930
  }),
17832
18931
  refreshVersion: z.object({
17833
18932
  library: z.string().trim().describe("Library name."),
@@ -17907,7 +19006,7 @@ function createMcpServerInstance(tools, config, instructions, schemas) {
17907
19006
  const server = new McpServer({
17908
19007
  name,
17909
19008
  ...title !== void 0 ? { title } : {},
17910
- version: "3.4.1"
19009
+ version: "3.6.0"
17911
19010
  }, {
17912
19011
  capabilities: {
17913
19012
  tools: {},
@@ -17917,14 +19016,14 @@ function createMcpServerInstance(tools, config, instructions, schemas) {
17917
19016
  });
17918
19017
  if (!readOnly) {
17919
19018
  server.registerTool("scrape_docs", {
17920
- description: "Scrape and index documentation from a URL for a library. Use this tool to index a new library or a new version. Scraping a library version that already exists is rejected unless `replace` is true; use refresh_version to update an existing version in place.",
19019
+ description: "Scrape and index documentation from a URL for a library. Use this tool to index a new library or a new version. Scraping a library version that already exists is rejected unless `replace` is true; use refresh_version to update an existing version in place. Unless `excludePatterns` is set, built-in default exclude patterns skip changelogs, licenses, and test, build, archive and non-English locale folders below the URL; any `excludePatterns` value, even an empty one, replaces them. The job runs in the background: check get_job_info, which warns when the job stored no documents.",
17921
19020
  inputSchema: schemas.scrapeDocs,
17922
19021
  annotations: {
17923
19022
  title: "Scrape New Library Documentation",
17924
19023
  destructiveHint: true,
17925
19024
  openWorldHint: true
17926
19025
  }
17927
- }, async ({ url, library, version, maxPages, maxDepth, scope, followRedirects, replace, preserveHashes, includePatterns, excludePatterns }) => {
19026
+ }, async ({ url, library, version, maxPages, maxDepth, scope, followRedirects, replace, preserveHashes, includePatterns, excludePatterns, respectGitignore }) => {
17928
19027
  telemetry.track(TelemetryEvent.TOOL_USED, {
17929
19028
  tool: "scrape_docs",
17930
19029
  context: "mcp_server",
@@ -17934,7 +19033,8 @@ function createMcpServerInstance(tools, config, instructions, schemas) {
17934
19033
  urlProtocol: extractProtocol(url),
17935
19034
  maxPages,
17936
19035
  maxDepth,
17937
- scope
19036
+ scope,
19037
+ respectGitignore
17938
19038
  });
17939
19039
  try {
17940
19040
  const result = await tools.scrape.execute({
@@ -17950,7 +19050,8 @@ function createMcpServerInstance(tools, config, instructions, schemas) {
17950
19050
  followRedirects,
17951
19051
  preserveHashes,
17952
19052
  includePatterns,
17953
- excludePatterns
19053
+ excludePatterns,
19054
+ respectGitignore
17954
19055
  }
17955
19056
  });
17956
19057
  if ("jobId" in result) return createResponse(`🚀 Scraping job started with ID: ${result.jobId}.`);
@@ -18151,7 +19252,7 @@ ${r.content}\n`);
18151
19252
  });
18152
19253
  try {
18153
19254
  const result = await tools.listJobs.execute({ status });
18154
- const formattedJobs = result.jobs.map((job) => `- ID: ${job.id}\n Status: ${job.status}\n Library: ${job.library}\n Version: ${job.version}\n Created: ${job.createdAt}${job.startedAt ? `\n Started: ${job.startedAt}` : ""}${job.finishedAt ? `\n Finished: ${job.finishedAt}` : ""}${job.error ? `\n Error: ${job.error}` : ""}`).join("\n\n");
19255
+ const formattedJobs = result.jobs.map((job) => `- ID: ${job.id}\n Status: ${job.status}\n Library: ${job.library}\n Version: ${job.version}\n Created: ${job.createdAt}${job.startedAt ? `\n Started: ${job.startedAt}` : ""}${job.finishedAt ? `\n Finished: ${job.finishedAt}` : ""}${job.error ? `\n Error: ${job.error}` : ""}${job.warning ? `\n Warning: ${job.warning}` : ""}`).join("\n\n");
18155
19256
  return createResponse(result.jobs.length > 0 ? `Current Jobs:\n\n${formattedJobs}` : "No jobs found.");
18156
19257
  } catch (error) {
18157
19258
  return createError(error);
@@ -18173,7 +19274,7 @@ ${r.content}\n`);
18173
19274
  });
18174
19275
  try {
18175
19276
  const job = (await tools.getJobInfo.execute({ jobId })).job;
18176
- return createResponse(`Job Info:\n\n${`- ID: ${job.id}\n Status: ${job.status}\n Library: ${job.library}@${job.version}\n Created: ${job.createdAt}${job.startedAt ? `\n Started: ${job.startedAt}` : ""}${job.finishedAt ? `\n Finished: ${job.finishedAt}` : ""}${job.error ? `\n Error: ${job.error}` : ""}`}`);
19277
+ return createResponse(`Job Info:\n\n${`- ID: ${job.id}\n Status: ${job.status}\n Library: ${job.library}@${job.version}\n Created: ${job.createdAt}${job.startedAt ? `\n Started: ${job.startedAt}` : ""}${job.finishedAt ? `\n Finished: ${job.finishedAt}` : ""}${job.error ? `\n Error: ${job.error}` : ""}${job.warning ? `\n Warning: ${job.warning}` : ""}`}`);
18177
19278
  } catch (error) {
18178
19279
  return createError(error);
18179
19280
  }
@@ -18520,6 +19621,7 @@ var GetJobInfoTool = class {
18520
19621
  startedAt: job.startedAt?.toISOString() ?? null,
18521
19622
  finishedAt: job.finishedAt?.toISOString() ?? null,
18522
19623
  error: job.error?.message ?? null,
19624
+ warning: job.warning ?? null,
18523
19625
  progress: job.progressMaxPages && job.progressMaxPages > 0 ? {
18524
19626
  pages: job.progressPages || 0,
18525
19627
  pagesIndexed: job.progress?.pagesIndexed ?? job.progressPagesIndexed ?? null,
@@ -18562,6 +19664,7 @@ var ListJobsTool = class {
18562
19664
  startedAt: job.startedAt?.toISOString() ?? null,
18563
19665
  finishedAt: job.finishedAt?.toISOString() ?? null,
18564
19666
  error: job.error?.message ?? null,
19667
+ warning: job.warning ?? null,
18565
19668
  progress: job.progressMaxPages && job.progressMaxPages > 0 ? {
18566
19669
  pages: job.progressPages || 0,
18567
19670
  pagesIndexed: job.progress?.pagesIndexed ?? job.progressPagesIndexed ?? null,
@@ -18759,6 +19862,7 @@ var ScrapeTool = class {
18759
19862
  scrapeMode: scraperOptions?.scrapeMode ?? ScrapeMode.Auto,
18760
19863
  includePatterns: scraperOptions?.includePatterns,
18761
19864
  excludePatterns: scraperOptions?.excludePatterns,
19865
+ respectGitignore: scraperOptions?.respectGitignore ?? url.startsWith("file://"),
18762
19866
  preserveHashes: scraperOptions?.preserveHashes,
18763
19867
  headers: scraperOptions?.headers,
18764
19868
  clean: scraperOptions?.clean
@@ -18769,7 +19873,10 @@ var ScrapeTool = class {
18769
19873
  const finalJob = await pipeline.getJob(jobId);
18770
19874
  const finalPagesScraped = finalJob?.progress?.pagesScraped ?? 0;
18771
19875
  logger.debug(`Job ${jobId} finished with status ${finalJob?.status}. Pages scraped: ${finalPagesScraped}`);
18772
- return { pagesScraped: finalPagesScraped };
19876
+ return {
19877
+ pagesScraped: finalPagesScraped,
19878
+ warning: finalJob?.warning ?? null
19879
+ };
18773
19880
  } catch (error) {
18774
19881
  logger.error(`❌ Job ${jobId} failed or was cancelled: ${error}`);
18775
19882
  throw error;
@@ -19016,7 +20123,7 @@ function buildSystemInfo(serverConfig, appConfig, mcpEndpointUrl, workerUrl) {
19016
20123
  const mcpEnabled = Boolean(serverConfig.enableMcpServer);
19017
20124
  const authEnabled = Boolean(appConfig.auth.enabled);
19018
20125
  return {
19019
- version: "3.4.1",
20126
+ version: "3.6.0",
19020
20127
  readOnly: Boolean(appConfig.app.readOnly),
19021
20128
  telemetryEnabled: Boolean(appConfig.app.telemetryEnabled),
19022
20129
  services: {
@@ -19180,6 +20287,18 @@ createPipelineRouter(t$3);
19180
20287
  * tRPC router exposing document data store operations via the worker API.
19181
20288
  * Only procedures actually used externally are included to keep surface minimal.
19182
20289
  */
20290
+ /**
20291
+ * Maps a rename failure a caller can act on to its tRPC code, mirroring the
20292
+ * pipeline router's enqueue mapping. Anything else passes through unchanged.
20293
+ */
20294
+ function toRenameError(error) {
20295
+ const code = error instanceof LibraryAlreadyExistsError || error instanceof LibraryBusyError ? "CONFLICT" : error instanceof InvalidLibraryNameError ? "BAD_REQUEST" : error instanceof LibraryNotFoundInStoreError ? "NOT_FOUND" : null;
20296
+ return code && error instanceof Error ? new TRPCError({
20297
+ code,
20298
+ message: error.message,
20299
+ cause: error
20300
+ }) : error;
20301
+ }
19183
20302
  var t$2 = initTRPC.context().create({ transformer: superjson });
19184
20303
  /** A required name, trimmed. */
19185
20304
  var nonEmpty = z.string().trim().min(1);
@@ -19241,6 +20360,16 @@ function createDataRouter(trpc) {
19241
20360
  }).optional()).mutation(async ({ ctx, input }) => {
19242
20361
  return await ctx.docService.compact(input);
19243
20362
  }),
20363
+ renameLibrary: tt.procedure.input(z.object({
20364
+ library: nonEmpty,
20365
+ newName: nonEmpty
20366
+ })).mutation(async ({ ctx, input }) => {
20367
+ try {
20368
+ return await ctx.docService.renameLibrary(input.library, input.newName);
20369
+ } catch (error) {
20370
+ throw toRenameError(error);
20371
+ }
20372
+ }),
19244
20373
  getVersionsByStatus: tt.procedure.input(z.object({ statuses: z.array(z.string()) })).query(async ({ ctx, input }) => {
19245
20374
  const statuses = input.statuses;
19246
20375
  return await ctx.docService.getVersionsByStatus(statuses);
@@ -19688,7 +20817,7 @@ var AppServer = class AppServer {
19688
20817
  if (this.appConfig.app.telemetryEnabled && shouldEnableTelemetry()) try {
19689
20818
  if (telemetry.isEnabled()) {
19690
20819
  telemetry.setGlobalContext({
19691
- appVersion: "3.4.1",
20820
+ appVersion: "3.6.0",
19692
20821
  appPlatform: process.platform,
19693
20822
  appNodeVersion: process.version,
19694
20823
  appServicesEnabled: this.getActiveServicesList(),
@@ -20621,6 +21750,88 @@ function createRemoveCommand(cli) {
20621
21750
  }
20622
21751
  });
20623
21752
  }
21753
+ // src/tools/RenameTool.ts
21754
+ /**
21755
+ * Tool to rename a library in place, keeping its versions and indexed content.
21756
+ * Shared by the CLI; the store refuses the rename while a job writes into the library.
21757
+ */
21758
+ var RenameTool = class {
21759
+ documentManagementService;
21760
+ /**
21761
+ * @param documentManagementService Renames the library, locally or against a worker.
21762
+ */
21763
+ constructor(documentManagementService) {
21764
+ this.documentManagementService = documentManagementService;
21765
+ }
21766
+ /**
21767
+ * Executes the rename of the specified library.
21768
+ * Names are compared case-insensitively, so a case-only change updates the display name.
21769
+ */
21770
+ async execute(args) {
21771
+ const { library, newName } = args;
21772
+ if (!library || typeof library !== "string" || library.trim() === "") throw new ValidationError("Library name is required and must be a non-empty string.", this.constructor.name);
21773
+ if (!newName || typeof newName !== "string" || newName.trim() === "") throw new ValidationError("The new name is required and must be a non-empty string.", this.constructor.name);
21774
+ logger.info(`✏️ Renaming library: ${library} -> ${newName}`);
21775
+ try {
21776
+ await this.documentManagementService.validateLibraryExists(library);
21777
+ const { oldName, newName: renamed } = await this.documentManagementService.renameLibrary(library, newName);
21778
+ const message = `Successfully renamed ${oldName} to ${renamed}.`;
21779
+ logger.info(`✅ ${message}`);
21780
+ return { message };
21781
+ } catch (error) {
21782
+ if (error instanceof ToolError) throw error;
21783
+ const errorMessage = `Failed to rename ${library} to ${newName}: ${error instanceof Error ? error.message : String(error)}`;
21784
+ logger.error(`❌ Error renaming library: ${errorMessage}`);
21785
+ throw new ToolError(errorMessage, this.constructor.name);
21786
+ }
21787
+ }
21788
+ };
21789
+ // src/cli/commands/rename.ts
21790
+ function createRenameCommand(cli) {
21791
+ cli.command("rename <library> <new-name>", "Rename a library in place, keeping its versions and indexed content", (yargs) => {
21792
+ return yargs.version(false).positional("library", {
21793
+ type: "string",
21794
+ description: "Current library name",
21795
+ demandOption: true
21796
+ }).positional("new-name", {
21797
+ type: "string",
21798
+ description: "New library name",
21799
+ demandOption: true
21800
+ }).option("server-url", {
21801
+ type: "string",
21802
+ description: "URL of external pipeline worker RPC (e.g., http://localhost:8080/api)",
21803
+ alias: "serverUrl"
21804
+ });
21805
+ }, async (argv) => {
21806
+ await telemetry.track(TelemetryEvent.CLI_COMMAND, {
21807
+ command: "rename",
21808
+ library: argv.library,
21809
+ newName: argv.newName,
21810
+ useServerUrl: !!argv.serverUrl
21811
+ });
21812
+ const library = argv.library;
21813
+ const newName = argv.newName;
21814
+ const serverUrl = argv.serverUrl;
21815
+ const appConfig = loadConfig(argv, {
21816
+ configPath: argv.config,
21817
+ searchDir: argv.storePath
21818
+ });
21819
+ const backend = await openBackend({
21820
+ serverUrl,
21821
+ eventBus: getEventBus(argv),
21822
+ appConfig
21823
+ });
21824
+ try {
21825
+ const { message } = await new RenameTool(backend.docService).execute({
21826
+ library,
21827
+ newName
21828
+ });
21829
+ renderTextOutput(message);
21830
+ } finally {
21831
+ await backend.close();
21832
+ }
21833
+ });
21834
+ }
20624
21835
  // src/cli/commands/scrape.ts
20625
21836
  function createScrapeCommand(cli) {
20626
21837
  cli.command("scrape <library> <url>", "Download and index documentation from a URL or local directory", (yargs) => {
@@ -20688,9 +21899,14 @@ function createScrapeCommand(cli) {
20688
21899
  }).option("exclude-pattern", {
20689
21900
  type: "string",
20690
21901
  array: true,
20691
- description: "Glob or regex pattern for URLs to exclude (can be specified multiple times, takes precedence over include). Regex patterns must be wrapped in slashes, e.g. /pattern/.",
21902
+ description: "Glob or regex pattern for URLs to exclude (can be specified multiple times, takes precedence over include). Regex patterns must be wrapped in slashes, e.g. /pattern/. Globs starting with **/ match only below the scraped URL. Without this option, default patterns exclude changelogs, licenses, and test, build, archive and locale folders.",
20692
21903
  alias: "excludePattern",
20693
21904
  default: []
21905
+ }).option("respect-gitignore", {
21906
+ type: "boolean",
21907
+ description: "For file:// directories, skip files matched by .gitignore rules in the indexed folder and below (parent-folder and global rules are not applied). On by default; pass --no-respect-gitignore to index ignored files",
21908
+ alias: "respectGitignore",
21909
+ default: true
20694
21910
  }).option("header", {
20695
21911
  type: "string",
20696
21912
  array: true,
@@ -20744,6 +21960,7 @@ function createScrapeCommand(cli) {
20744
21960
  hasHeaders: argv.header.length > 0,
20745
21961
  hasIncludePatterns: argv.includePattern.length > 0,
20746
21962
  hasExcludePatterns: argv.excludePattern.length > 0,
21963
+ respectGitignore: argv.respectGitignore,
20747
21964
  useServerUrl: !!serverUrl
20748
21965
  });
20749
21966
  if (!serverUrl) ensurePlaywrightBrowsersInstalled();
@@ -20776,11 +21993,13 @@ function createScrapeCommand(cli) {
20776
21993
  preserveHashes,
20777
21994
  includePatterns: argv.includePattern?.length > 0 ? argv.includePattern : void 0,
20778
21995
  excludePatterns: argv.excludePattern?.length > 0 ? argv.excludePattern : void 0,
21996
+ respectGitignore: argv.respectGitignore,
20779
21997
  headers: Object.keys(headers).length > 0 ? headers : void 0,
20780
21998
  clean: argv.clean
20781
21999
  }
20782
22000
  });
20783
- if ("pagesScraped" in result) renderTextOutput(`Successfully scraped ${result.pagesScraped} pages`);
22001
+ if ("pagesScraped" in result && result.warning) renderTextOutput(`⚠️ ${result.warning}`);
22002
+ else if ("pagesScraped" in result) renderTextOutput(`Successfully scraped ${result.pagesScraped} pages`);
20784
22003
  else renderTextOutput(`Scraping job started with ID: ${result.jobId}`);
20785
22004
  } catch (error) {
20786
22005
  logger.error(`❌ Scraping failed: ${error instanceof Error ? error.message : String(error)}`);
@@ -21002,6 +22221,7 @@ var COMMAND_FACTORIES = [
21002
22221
  createMcpCommand,
21003
22222
  createRefreshCommand,
21004
22223
  createRemoveCommand,
22224
+ createRenameCommand,
21005
22225
  createScrapeCommand,
21006
22226
  createSearchCommand,
21007
22227
  createWebCommand,
@@ -21046,7 +22266,7 @@ function registerGlobalOptions(cli) {
21046
22266
  function createCli(argv) {
21047
22267
  let globalEventBus = null;
21048
22268
  const commandStartTimes = /* @__PURE__ */ new Map();
21049
- const cli = registerGlobalOptions(yargs(hideBin(argv))).scriptName("docs-mcp-server").strict().usage("Usage: $0 <command> [options]").version("3.4.1").middleware(async (argv) => {
22269
+ const cli = registerGlobalOptions(yargs(hideBin(argv))).scriptName("docs-mcp-server").strict().usage("Usage: $0 <command> [options]").version("3.6.0").middleware(async (argv) => {
21050
22270
  if (argv.verbose && argv.quiet) throw new Error("Arguments verbose and quiet are mutually exclusive");
21051
22271
  applyGlobalCliOutputMode({
21052
22272
  verbose: argv.verbose,
@@ -21068,7 +22288,7 @@ function createCli(argv) {
21068
22288
  if (shouldEnableTelemetry() && telemetry.isEnabled()) {
21069
22289
  const commandName = argv._[0]?.toString() || "default";
21070
22290
  telemetry.setGlobalContext({
21071
- appVersion: "3.4.1",
22291
+ appVersion: "3.6.0",
21072
22292
  appPlatform: process.platform,
21073
22293
  appNodeVersion: process.version,
21074
22294
  appInterface: "cli",
@@ -21128,6 +22348,13 @@ var sigintHandler = async () => {
21128
22348
  }
21129
22349
  };
21130
22350
  /**
22351
+ * Waits until stdout and stderr have written everything queued so far. Writes
22352
+ * to a pipe are asynchronous, so exiting right away can cut off the output.
22353
+ */
22354
+ async function flushOutput() {
22355
+ await Promise.all([process.stdout, process.stderr].map((stream) => new Promise((resolve) => stream.write("", () => resolve()))));
22356
+ }
22357
+ /**
21131
22358
  * Performs cleanup for CLI commands that don't start long-running services.
21132
22359
  * This ensures proper analytics shutdown and process exit to prevent hanging.
21133
22360
  */
@@ -21136,6 +22363,7 @@ async function cleanupCliCommand() {
21136
22363
  logger.debug("CLI command executed. Cleaning up...");
21137
22364
  process.removeListener("SIGINT", sigintHandler);
21138
22365
  await telemetry.shutdown();
22366
+ await flushOutput();
21139
22367
  process.exit();
21140
22368
  }
21141
22369
  }
@@ -21172,6 +22400,7 @@ async function runCli() {
21172
22400
  await Promise.allSettled(shutdownPromises);
21173
22401
  await closeActiveBackend().catch((e) => logger.error(`❌ Error closing backend: ${e}`));
21174
22402
  }
22403
+ await flushOutput();
21175
22404
  process.exit(1);
21176
22405
  }
21177
22406
  const appServer = getActiveAppServer();
@@ -21179,4 +22408,4 @@ async function runCli() {
21179
22408
  }
21180
22409
  export { runCli };
21181
22410
 
21182
- //# sourceMappingURL=main-Cb6JaTXM.js.map
22411
+ //# sourceMappingURL=main-CBgiSgoD.js.map