@arabold/docs-mcp-server 3.5.0 → 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";
@@ -51,6 +51,7 @@ 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
57
  import * as sqliteVec from "sqlite-vec";
@@ -3644,18 +3645,20 @@ function patternToRegExp(pattern) {
3644
3645
  * Used to avoid prepending a `/` to inputs that are already full URLs.
3645
3646
  */
3646
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
+ }
3647
3655
  /**
3648
- * Checks if a given path matches any pattern in the list.
3649
- * 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.
3650
3658
  */
3651
- function matchesAnyPattern(path, patterns) {
3652
- if (!patterns || patterns.length === 0) return false;
3653
- const normalizedPath = URL_WITH_PROTOCOL_RE.test(path) || path.startsWith("/") ? path : `/${path}`;
3654
- return patterns.some((pattern) => {
3655
- if (isRegexPattern(pattern)) return patternToRegExp(pattern).test(normalizedPath);
3656
- const pathForMatch = normalizedPath.replace(/^\//, "");
3657
- return getGlobMatcher(pattern.startsWith("/") ? pattern.slice(1) : pattern).match(pathForMatch);
3658
- });
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);
3659
3662
  }
3660
3663
  /**
3661
3664
  * Matches a flat string (hostname, label, etc.) against patterns without any
@@ -3671,42 +3674,65 @@ function matchesAnyHostPattern(value, patterns) {
3671
3674
  return getGlobMatcher(pattern.toLowerCase()).match(normalized);
3672
3675
  });
3673
3676
  }
3674
- /**
3675
- * Extracts the path and query from a URL string (no domain).
3676
- */
3677
- function extractPathAndQuery(url) {
3677
+ function getLinkTargets(url, rootDirectory) {
3678
+ let pathname;
3679
+ let search = "";
3680
+ let basename;
3678
3681
  try {
3679
3682
  const u = new URL(url);
3680
- return u.pathname + (u.search || "");
3683
+ pathname = u.pathname;
3684
+ search = u.search;
3685
+ if (u.protocol === "file:") basename = pathname.split("/").pop() || void 0;
3681
3686
  } catch {
3682
- return url;
3687
+ pathname = url.startsWith("/") ? url : `/${url}`;
3683
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
+ };
3684
3696
  }
3685
3697
  /**
3686
- * Determines if a URL should be included based on include/exclude patterns.
3687
- * Exclude patterns take precedence. If no include patterns, all are included by default.
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);
3707
+ }
3708
+ /**
3709
+ * Decides whether a link passes the include and exclude patterns, and why not.
3688
3710
  *
3689
- * If no user exclude patterns are provided, default exclusion patterns are automatically applied.
3690
- * These defaults exclude common documentation files (CHANGELOG.md, LICENSE, etc.) and folders
3691
- * (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.
3692
3714
  *
3693
- * Patterns are matched against both the full URL and the pathname for maximum flexibility:
3694
- * - Full URL: `https://example.com/docs/v3/**` matches `https://example.com/docs/v3/guide`
3695
- * - Pathname: `/docs/v3/**` matches `https://example.com/docs/v3/guide`
3696
- */
3697
- function shouldIncludeUrl(url, includePatterns, excludePatterns) {
3698
- const path = extractPathAndQuery(url);
3699
- const normalizedPath = path.startsWith("/") ? path : `/${path}`;
3700
- let basename;
3701
- if (url.startsWith("file://")) try {
3702
- const u = new URL(url);
3703
- basename = u.pathname ? u.pathname.split("/").pop() : void 0;
3704
- } catch {}
3705
- const stripSlash = (patterns) => patterns?.map((p) => p.startsWith("/") ? p.slice(1) : p);
3706
- const effectiveExcludePatterns = getEffectiveExclusionPatterns(excludePatterns);
3707
- if (matchesAnyPattern(url, effectiveExcludePatterns) || matchesAnyPattern(normalizedPath, effectiveExcludePatterns) || basename && matchesAnyPattern(basename, stripSlash(effectiveExcludePatterns))) return false;
3708
- if (!includePatterns || includePatterns.length === 0) return true;
3709
- 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" };
3710
3736
  }
3711
3737
  // src/utils/accessPolicy.ts
3712
3738
  var SPECIAL_USE_IPV4_CIDRS = [
@@ -5356,18 +5382,42 @@ var PageOutcome = /* @__PURE__ */ function(PageOutcome) {
5356
5382
  PageOutcome["Absent"] = "absent";
5357
5383
  /** Fetched successfully but yielded no content. The page exists and is empty. */
5358
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";
5359
5391
  /** No pipeline can read this content type, so the body was never downloaded. */
5360
5392
  PageOutcome["Skipped"] = "skipped";
5361
5393
  /** Processing failed and the error was ignored under `ignoreErrors`. */
5362
5394
  PageOutcome["Failed"] = "failed";
5363
5395
  return PageOutcome;
5364
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
+ }
5365
5415
  // src/scraper/utils/llmsTxtParser.ts
5366
5416
  var emptyLlmsTxtResult = () => ({
5367
5417
  sections: [],
5368
5418
  links: []
5369
5419
  });
5370
- var markdownLinkPattern = /^\s*[-*+•]\s+\[([^\]\n]+)]\(([^)\s]+)\)\s*(?::\s*(.+?)\s*)?$/;
5420
+ var markdownLinkPattern = /^\s*[-*+•]\s+\[([^\]\n]+)]\(([^)\s]+)\)\s*(?::(.+))?$/;
5371
5421
  var htmlDocumentPattern = /^\s*<(?:!doctype\s+html|html|body|head)(?:\s|>)/i;
5372
5422
  /**
5373
5423
  * Unwraps llms.txt content that a browser rendered as HTML.
@@ -5457,7 +5507,7 @@ function parseLlmsTxt(content) {
5457
5507
  collectingSummary = false;
5458
5508
  continue;
5459
5509
  }
5460
- const h2Match = /^##\s+(.+?)\s*$/.exec(line);
5510
+ const h2Match = /^##\s(.+)$/.exec(line);
5461
5511
  if (h2Match) {
5462
5512
  collectingSummary = false;
5463
5513
  const title = h2Match[1].trim();
@@ -5532,6 +5582,22 @@ function computeBaseDirectory(pathname) {
5532
5582
  return `${pathname}/`;
5533
5583
  }
5534
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
+ /**
5535
5601
  * Returns true when `childPath` is the same as `parentPath` or is a path-descendant of it.
5536
5602
  * `parentPath` is normalized to end with "/" before comparison so directory semantics apply.
5537
5603
  *
@@ -5629,8 +5695,26 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5629
5695
  /** URLs admitted to the queue, clamped at where the crawl will stop. */
5630
5696
  effectiveTotal = 0;
5631
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
+ };
5632
5714
  completedChildPageAttempts = 0;
5633
5715
  failedChildPages = 0;
5716
+ /** Rejected links during the current crawl, keyed by their described reason. */
5717
+ linkRejections = /* @__PURE__ */ new Map();
5634
5718
  /**
5635
5719
  * The point at which the crawl stops, expressed in processed items.
5636
5720
  *
@@ -5697,8 +5781,9 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5697
5781
  return this.canonicalBaseUrl ?? new URL$1(options.url);
5698
5782
  }
5699
5783
  /**
5700
- * Determines if a URL should be processed based on scope and include/exclude patterns in ScraperOptions.
5701
- * 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.
5702
5787
  *
5703
5788
  * `internalAllowedFileRoots` opts a queue item out of the protocol-strict
5704
5789
  * scope check: when a web URL has been accepted as an archive root and the
@@ -5710,18 +5795,147 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5710
5795
  * sandbox via this path. Downstream `resolveFileAccess` enforces the same
5711
5796
  * rule, but rejecting early here keeps unrelated `file://` URLs out of the
5712
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.
5713
5803
  */
5714
- shouldProcessUrl(url, options, context = {}) {
5715
- if (isLlmsTxtUrl(url) || isLlmsTxtCompanionUrl(url)) return false;
5716
- if (!(url.startsWith("file://") && isFileUrlInsideRoots(url, context.internalAllowedFileRoots))) {
5717
- const scope = options.scope ?? "subpages";
5718
- try {
5719
- if (!isInScope(this.getScopeBaseUrl(options), new URL$1(url), scope)) return false;
5720
- } catch {
5721
- return false;
5722
- }
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
+ };
5723
5818
  }
5724
- 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;
5725
5939
  }
5726
5940
  shouldCountTowardFailureThreshold(item, options, result) {
5727
5941
  if (item.fromLlmsTxt) return false;
@@ -5826,6 +6040,12 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5826
6040
  }
5827
6041
  };
5828
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
+ }
5829
6049
  const result = await this.processItem(item, options, signal);
5830
6050
  throwIfCrawlAborted();
5831
6051
  if (result.status === FetchStatus.NOT_MODIFIED) {
@@ -5869,6 +6089,17 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5869
6089
  }
5870
6090
  const finalUrl = this.canonicalizeStoredUrl(result.url || item.url, options);
5871
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
+ }
5872
6103
  const producedContent = !!result.content?.textContent?.trim();
5873
6104
  if (result.content && producedContent) {
5874
6105
  await report(PageOutcome.Stored, {
@@ -5913,20 +6144,23 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5913
6144
  ensureFailureRateWithinThreshold();
5914
6145
  throwIfCrawlAborted();
5915
6146
  const childDepth = item.depth + 1;
5916
- 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;
5917
6150
  try {
5918
- const targetUrl = new URL$1(value, linkBaseUrl);
5919
- if (!this.shouldProcessUrl(targetUrl.href, options, { internalAllowedFileRoots })) return null;
5920
- return {
5921
- url: targetUrl.href,
5922
- depth: childDepth,
5923
- ...internalAllowedFileRoots ? { internalAllowedFileRoots } : {}
5924
- };
6151
+ targetUrl = new URL$1(value, linkBaseUrl);
5925
6152
  } catch (_error) {
5926
6153
  logger.warn(`❌ Invalid URL: ${value}`);
6154
+ return null;
5927
6155
  }
5928
- return null;
5929
- }).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();
5930
6164
  return [...result.queueItems ?? [], ...linkQueueItems];
5931
6165
  } catch (error) {
5932
6166
  if (error instanceof FailureThresholdExceededError || error instanceof CancellationError) throw error;
@@ -5964,6 +6198,7 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5964
6198
  }
5965
6199
  async scrape(options, progressCallback, signal) {
5966
6200
  this.visited.clear();
6201
+ this.linkRejections = /* @__PURE__ */ new Map();
5967
6202
  this.storedIdentities.clear();
5968
6203
  this.pageCount = 0;
5969
6204
  this.pagesIndexed = 0;
@@ -5972,12 +6207,13 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5972
6207
  const initialQueue = options.initialQueue || [];
5973
6208
  const isRefreshMode = initialQueue.length > 0;
5974
6209
  this.canonicalBaseUrl = new URL$1(options.url);
6210
+ this.redirectedStartUrl = void 0;
5975
6211
  let baseUrl = this.canonicalBaseUrl;
5976
6212
  const queue = [];
5977
6213
  const normalizedRootUrl = normalizeUrl(options.url, this.getUrlNormalizerOptions(options));
5978
6214
  if (isRefreshMode) {
5979
6215
  logger.debug(`Starting refresh mode with ${initialQueue.length} pre-populated pages`);
5980
- for (const item of initialQueue) {
6216
+ for (const { internalAllowedFileRoots: _callerRoots, ...item } of initialQueue) {
5981
6217
  const normalizedUrl = normalizeUrl(item.url, this.getUrlNormalizerOptions(options));
5982
6218
  if (!this.visited.has(normalizedUrl)) {
5983
6219
  this.visited.add(normalizedUrl);
@@ -5985,13 +6221,22 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5985
6221
  }
5986
6222
  }
5987
6223
  }
5988
- 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) {
5989
6227
  this.visited.add(normalizedRootUrl);
5990
6228
  queue.unshift({
5991
6229
  url: options.url,
5992
6230
  depth: 0
5993
6231
  });
5994
6232
  }
6233
+ let settleStartPage = () => {};
6234
+ this.startPage = {
6235
+ urls: /* @__PURE__ */ new Set(),
6236
+ settled: new Promise((resolve) => {
6237
+ settleStartPage = resolve;
6238
+ })
6239
+ };
5995
6240
  const maxPages = options.maxPages ?? this.config.scraper.maxPages;
5996
6241
  const maxConcurrency = options.maxConcurrency ?? this.config.scraper.maxConcurrency;
5997
6242
  this.totalDiscovered = queue.length;
@@ -6015,7 +6260,9 @@ var BaseScraperStrategy = class BaseScraperStrategy {
6015
6260
  if (!item) break;
6016
6261
  const seq = nextSeq++;
6017
6262
  baseUrl = this.canonicalBaseUrl ?? baseUrl;
6018
- 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) => {
6019
6266
  finished.set(seq, offered);
6020
6267
  return seq;
6021
6268
  }));
@@ -6035,6 +6282,7 @@ var BaseScraperStrategy = class BaseScraperStrategy {
6035
6282
  } finally {
6036
6283
  signal?.removeEventListener("abort", abortItems);
6037
6284
  }
6285
+ return { rejections: [...this.linkRejections.values()].sort((a, b) => b.count - a.count) };
6038
6286
  }
6039
6287
  /**
6040
6288
  * Cleanup resources used by this strategy.
@@ -6043,24 +6291,24 @@ var BaseScraperStrategy = class BaseScraperStrategy {
6043
6291
  async cleanup() {}
6044
6292
  };
6045
6293
  /**
6046
- * Returns true if `url` is a `file://` URL whose resolved filesystem path lies
6047
- * inside one of the supplied internal roots. Used by the queue-time scope
6048
- * bypass for archive-member URLs so that arbitrary `file://` links injected
6049
- * 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.
6050
6300
  */
6051
- function isFileUrlInsideRoots(url, roots) {
6052
- if (!roots || roots.length === 0) return false;
6301
+ function findContainingFileRoot(url, roots) {
6302
+ if (!roots || roots.length === 0 || !url.startsWith("file://")) return void 0;
6053
6303
  let target;
6054
6304
  try {
6055
6305
  target = path.resolve(fileUrlToPathLoose(url));
6056
6306
  } catch {
6057
- return false;
6307
+ return;
6058
6308
  }
6059
- return roots.some((root) => {
6060
- const resolvedRoot = path.resolve(root);
6061
- if (resolvedRoot === target) return true;
6062
- const relative = path.relative(resolvedRoot, target);
6063
- 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);
6064
6312
  });
6065
6313
  }
6066
6314
  // src/utils/dom.ts
@@ -10892,20 +11140,6 @@ var GitHubWikiProcessor = class {
10892
11140
  };
10893
11141
  }
10894
11142
  /**
10895
- * Determines if a URL should be processed within the wiki scope.
10896
- */
10897
- shouldProcessUrl(url, options) {
10898
- try {
10899
- const parsedUrl = new URL(url);
10900
- const baseWikiInfo = this.parseGitHubWikiUrl(options.url);
10901
- const expectedWikiPath = `/${baseWikiInfo.owner}/${baseWikiInfo.repo}/wiki`;
10902
- if (!parsedUrl.pathname.startsWith(expectedWikiPath)) return false;
10903
- return shouldIncludeUrl(parsedUrl.pathname.replace(expectedWikiPath, "").replace(/^\//, "") || "Home", options.includePatterns, options.excludePatterns);
10904
- } catch {
10905
- return false;
10906
- }
10907
- }
10908
- /**
10909
11143
  * Processes a single GitHub wiki page.
10910
11144
  */
10911
11145
  async process(item, options, headers, signal) {
@@ -11228,6 +11462,21 @@ var COMMON_TEXT_FILES = [
11228
11462
  ".nvmrc",
11229
11463
  ".npmrc"
11230
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
+ }
11231
11480
  /**
11232
11481
  * GitHubScraperStrategy is a discovery strategy that orchestrates the scraping of both
11233
11482
  * GitHub repository code and wiki pages. When given a GitHub repository URL, it will:
@@ -11258,6 +11507,8 @@ var GitHubScraperStrategy = class extends BaseScraperStrategy {
11258
11507
  repoProcessor;
11259
11508
  resolvedAuthHeaders;
11260
11509
  resolvedAuthKey;
11510
+ /** Folder a `/tree/<branch>/<path>` start URL names, measured from the repo root. */
11511
+ treeRootDirectory;
11261
11512
  constructor(config) {
11262
11513
  super(config);
11263
11514
  this.httpFetcher = new HttpFetcher(config.scraper);
@@ -11370,9 +11621,10 @@ var GitHubScraperStrategy = class extends BaseScraperStrategy {
11370
11621
  };
11371
11622
  }
11372
11623
  /**
11373
- * 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.
11374
11626
  */
11375
- shouldProcessFile(item, options) {
11627
+ shouldProcessFile(item) {
11376
11628
  if (item.type !== "blob") return false;
11377
11629
  const filePath = item.path;
11378
11630
  const pathLower = filePath.toLowerCase();
@@ -11383,22 +11635,16 @@ var GitHubScraperStrategy = class extends BaseScraperStrategy {
11383
11635
  const hasCompoundExtension = pathLower.includes(".env.") || pathLower.endsWith(".env") || pathLower.includes(".config.") || pathLower.includes(".lock");
11384
11636
  const fileNameLower = (filePath.split("/").pop() || "").toLowerCase();
11385
11637
  const isCommonTextFile = COMMON_TEXT_FILES.some((name) => fileNameLower === name || fileNameLower.startsWith(`${name}.`));
11386
- if (hasTextExtension || hasDocumentExtension || hasCompoundExtension || isCommonTextFile) return shouldIncludeUrl(filePath, options.includePatterns, options.excludePatterns);
11387
- const mimeType = MimeTypeUtils.detectMimeTypeFromPath(filePath);
11388
- if (mimeType?.startsWith("text/")) {
11389
- logger.debug(`Including file with text MIME type: ${filePath} (${mimeType})`);
11390
- return shouldIncludeUrl(filePath, options.includePatterns, options.excludePatterns);
11391
- }
11392
- return false;
11638
+ return hasTextExtension || hasDocumentExtension || hasCompoundExtension || isCommonTextFile || MimeTypeUtils.detectMimeTypeFromPath(filePath)?.startsWith("text/") === true;
11393
11639
  }
11394
11640
  /**
11395
11641
  * Checks if a path is within the specified subpath.
11396
11642
  */
11397
11643
  isWithinSubPath(path, subPath) {
11398
11644
  if (!subPath) return true;
11399
- const trimmedSubPath = subPath.replace(/^\/+/, "").replace(/\/+$/, "");
11645
+ const trimmedSubPath = trimSlashes(subPath);
11400
11646
  if (trimmedSubPath.length === 0) return true;
11401
- const normalizedPath = path.replace(/^\/+/, "").replace(/\/+$/, "");
11647
+ const normalizedPath = trimSlashes(path);
11402
11648
  if (normalizedPath === trimmedSubPath) return true;
11403
11649
  return normalizedPath.startsWith(`${trimmedSubPath}/`);
11404
11650
  }
@@ -11438,6 +11684,40 @@ var GitHubScraperStrategy = class extends BaseScraperStrategy {
11438
11684
  const { owner, repo } = this.parseGitHubUrl(options.url);
11439
11685
  return new URL(`/${owner}/${repo}`, options.url);
11440
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
+ }
11441
11721
  async processItem(item, options, signal) {
11442
11722
  if (item.url.startsWith("github-file://")) {
11443
11723
  logger.info(`🗑️ Legacy github-file:// URL detected, marking as deleted: ${item.url}`);
@@ -11467,7 +11747,7 @@ var GitHubScraperStrategy = class extends BaseScraperStrategy {
11467
11747
  logger.debug(`Discovered wiki URL: ${wikiUrl}`);
11468
11748
  }
11469
11749
  const { tree, resolvedBranch } = await this.fetchRepositoryTree(repoInfo, headers, signal);
11470
- 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));
11471
11751
  logger.debug(`Discovered ${fileItems.length} processable files in repository (branch: ${resolvedBranch})`);
11472
11752
  const fileUrls = fileItems.map((treeItem) => `https://github.com/${owner}/${repo}/blob/${resolvedBranch}/${treeItem.path}`);
11473
11753
  discoveredLinks.push(...fileUrls);
@@ -11504,7 +11784,13 @@ var GitHubScraperStrategy = class extends BaseScraperStrategy {
11504
11784
  if (!new URL(options.url).hostname.includes("github.com")) throw new Error("URL must be a GitHub URL");
11505
11785
  await this.getResolvedAuthHeaders(options.headers);
11506
11786
  try {
11507
- 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);
11508
11794
  } finally {
11509
11795
  this.resolvedAuthHeaders = void 0;
11510
11796
  this.resolvedAuthKey = void 0;
@@ -11699,6 +11985,143 @@ async function getArchiveAdapter(filePath) {
11699
11985
  if (ext === ".tar" || ext === ".gz" || ext === ".tgz") return new TarAdapter(filePath);
11700
11986
  return null;
11701
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
+ }
11702
12125
  // src/scraper/strategies/LocalFileStrategy.ts
11703
12126
  /**
11704
12127
  * Orders two names by Unicode code point, which is the byte order of their
@@ -11708,6 +12131,26 @@ function compareCodePoints(a, b) {
11708
12131
  return Buffer.compare(Buffer.from(a), Buffer.from(b));
11709
12132
  }
11710
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
+ /**
11711
12154
  * LocalFileStrategy handles crawling and scraping of local files and folders using file:// URLs.
11712
12155
  *
11713
12156
  * Files are routed to the appropriate pipeline based on their detected MIME type:
@@ -11723,6 +12166,13 @@ var LocalFileStrategy = class extends BaseScraperStrategy {
11723
12166
  fileFetcher;
11724
12167
  pipelines;
11725
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;
11726
12176
  constructor(config) {
11727
12177
  super(config);
11728
12178
  this.fileFetcher = new FileFetcher(config.scraper);
@@ -11730,7 +12180,7 @@ var LocalFileStrategy = class extends BaseScraperStrategy {
11730
12180
  this.accessPolicy = new ScraperAccessPolicy(config.scraper.security);
11731
12181
  }
11732
12182
  async processItem(item, options, _signal) {
11733
- const filePath = (await this.accessPolicy.resolveFileAccess(item.url, options.internalAllowedFileRoots)).filePath;
12183
+ const filePath = (await this.accessPolicy.resolveFileAccess(item.url, item.internalAllowedFileRoots)).filePath;
11734
12184
  let stats = null;
11735
12185
  let archivePath = null;
11736
12186
  let innerPath = null;
@@ -11757,25 +12207,10 @@ var LocalFileStrategy = class extends BaseScraperStrategy {
11757
12207
  } else throw error;
11758
12208
  }
11759
12209
  if (stats?.isDirectory()) {
11760
- const contents = (await fs$1.readdir(filePath)).sort(compareCodePoints);
11761
- const visibleContents = this.config.scraper.security.fileAccess.includeHidden ? contents : contents.filter((name) => !name.startsWith("."));
11762
- const links = (await Promise.all(visibleContents.map(async (name) => {
11763
- const entryPath = path.join(filePath, name);
11764
- if (!this.config.scraper.security.fileAccess.followSymlinks) {
11765
- if ((await fs$1.lstat(entryPath).catch(() => null))?.isSymbolicLink()) return null;
11766
- }
11767
- const url = new URL(`file://${entryPath.replace(/\\/g, "/")}`);
11768
- if (url.hostname !== "") {
11769
- url.pathname = `/${url.hostname}${url.pathname}`;
11770
- url.hostname = "";
11771
- }
11772
- return url.href;
11773
- }))).filter((url) => Boolean(url)).filter((url) => {
11774
- const allowed = this.shouldProcessUrl(url, options);
11775
- if (!allowed) logger.debug(`Skipping out-of-scope link: ${url}`);
11776
- return allowed;
12210
+ const links = (await fs$1.readdir(filePath)).sort(compareCodePoints).map((name) => {
12211
+ return toFileUrl(path.join(filePath, name));
11777
12212
  });
11778
- logger.debug(`Found ${links.length} files in ${filePath} (from ${visibleContents.length} entries)`);
12213
+ logger.debug(`Found ${links.length} entries in ${filePath}`);
11779
12214
  return {
11780
12215
  url: item.url,
11781
12216
  links,
@@ -11796,12 +12231,7 @@ var LocalFileStrategy = class extends BaseScraperStrategy {
11796
12231
  }
11797
12232
  const entryPath = entry.path.replace(/^\//, "");
11798
12233
  const fullVirtualPath = path.join(filePath, entryPath).replace(/\\/g, "/");
11799
- const virtualUrl = new URL(`file://${fullVirtualPath}`);
11800
- if (virtualUrl.hostname !== "") {
11801
- virtualUrl.pathname = `/${virtualUrl.hostname}${virtualUrl.pathname}`;
11802
- virtualUrl.hostname = "";
11803
- }
11804
- if (this.shouldProcessUrl(virtualUrl.href, options) && this.isVisibleArchiveEntry(entry.path)) links.push(virtualUrl.href);
12234
+ links.push(toFileUrl(fullVirtualPath));
11805
12235
  }
11806
12236
  logger.debug(`Found ${links.length} entries in archive ${filePath}`);
11807
12237
  return {
@@ -11877,9 +12307,138 @@ var LocalFileStrategy = class extends BaseScraperStrategy {
11877
12307
  adapter: null
11878
12308
  };
11879
12309
  }
11880
- isVisibleArchiveEntry(entryPath) {
11881
- if (this.config.scraper.security.fileAccess.includeHidden) return true;
11882
- 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);
11883
12442
  }
11884
12443
  async processArchiveEntry(item, archivePath, innerPath, adapter, options) {
11885
12444
  logger.debug(`Reading archive entry: ${innerPath} inside ${archivePath}`);
@@ -12210,14 +12769,14 @@ var WebScraperStrategy = class extends BaseScraperStrategy {
12210
12769
  }
12211
12770
  return null;
12212
12771
  }
12213
- createLlmsTxtQueueItems(options, probe) {
12772
+ async createLlmsTxtQueueItems(options, probe) {
12214
12773
  const items = [];
12215
12774
  for (const link of probe.result.links) try {
12216
12775
  const targetUrl = new URL(link.url, probe.url);
12217
12776
  if (targetUrl.protocol !== "http:" && targetUrl.protocol !== "https:") continue;
12218
12777
  if (isArchivePath(targetUrl.pathname)) continue;
12219
12778
  if (!this.canProcessDiscoveredLink(targetUrl)) continue;
12220
- if (!this.shouldProcessUrl(targetUrl.href, options)) continue;
12779
+ if (!await this.admitLink(targetUrl.href, options)) continue;
12221
12780
  if (this.shouldFollowLinkFn) {
12222
12781
  const baseUrl = this.canonicalBaseUrl ?? new URL(options.url);
12223
12782
  if (!this.shouldFollowLinkFn(baseUrl, targetUrl)) continue;
@@ -12230,7 +12789,7 @@ var WebScraperStrategy = class extends BaseScraperStrategy {
12230
12789
  } catch {}
12231
12790
  return items;
12232
12791
  }
12233
- consumePendingLlmsTxtQueueItems(item, options) {
12792
+ async consumePendingLlmsTxtQueueItems(item, options) {
12234
12793
  if (item.depth !== 0) return [];
12235
12794
  const probe = this.pendingLlmsTxtProbe;
12236
12795
  this.pendingLlmsTxtProbe = null;
@@ -12273,8 +12832,13 @@ var WebScraperStrategy = class extends BaseScraperStrategy {
12273
12832
  const fetchedSource = options.preserveHashes ? this.restorePreservedHash(url, fetched.source) : fetched.source;
12274
12833
  const rawContent = this.asMarkdownRepresentation(fetchedSource, fetched);
12275
12834
  const effectiveSource = this.resolvePageIdentity(fetchedSource, rawContent);
12276
- if (this.isRequestedRoot(item, options)) this.updateCanonicalBaseUrl(effectiveSource, options);
12277
- 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);
12278
12842
  logger.debug(`Fetch result for ${url}: status=${rawContent.status}, etag=${rawContent.etag || "none"}`);
12279
12843
  if (rawContent.status !== FetchStatus.SUCCESS) {
12280
12844
  logger.debug(`Skipping pipeline for ${url} due to status: ${rawContent.status}`);
@@ -12332,7 +12896,6 @@ var WebScraperStrategy = class extends BaseScraperStrategy {
12332
12896
  const targetUrl = new URL(link, effectiveSource);
12333
12897
  if (isArchivePath(targetUrl.pathname)) return [];
12334
12898
  if (!this.canProcessDiscoveredLink(targetUrl)) return [];
12335
- if (!this.shouldProcessUrl(targetUrl.href, options)) return [];
12336
12899
  if (this.shouldFollowLinkFn) {
12337
12900
  const baseUrl = this.canonicalBaseUrl ?? new URL(options.url);
12338
12901
  return this.shouldFollowLinkFn(baseUrl, targetUrl) ? [targetUrl.href] : [];
@@ -12362,7 +12925,7 @@ var WebScraperStrategy = class extends BaseScraperStrategy {
12362
12925
  async scrape(options, progressCallback, signal) {
12363
12926
  this.pendingLlmsTxtProbe = null;
12364
12927
  this.pendingLlmsTxtProbe = await this.probeLlmsTxt(options.url, options.url, options, signal);
12365
- await super.scrape(options, progressCallback, signal);
12928
+ return super.scrape(options, progressCallback, signal);
12366
12929
  }
12367
12930
  async processRootArchive(item, options, signal) {
12368
12931
  logger.info(`📦 Downloading root archive: ${item.url}`);
@@ -12383,18 +12946,13 @@ var WebScraperStrategy = class extends BaseScraperStrategy {
12383
12946
  const localUrl = `file://${tempFile}`;
12384
12947
  const localItem = {
12385
12948
  ...item,
12386
- url: localUrl
12949
+ url: localUrl,
12950
+ internalAllowedFileRoots: [...item.internalAllowedFileRoots ?? [], tempFile]
12387
12951
  };
12388
- const localOptions = {
12389
- ...options,
12390
- internalAllowedFileRoots: [...options.internalAllowedFileRoots ?? [], tempFile]
12391
- };
12392
- const result = await this.localFileStrategy.processItem(localItem, localOptions, signal);
12393
12952
  return {
12394
- ...result,
12953
+ ...await this.localFileStrategy.processItem(localItem, options, signal),
12395
12954
  url: item.url,
12396
- links: result.links,
12397
- internalAllowedFileRoots: [tempFile]
12955
+ links: []
12398
12956
  };
12399
12957
  }
12400
12958
  /**
@@ -12420,7 +12978,7 @@ var NpmScraperStrategy = class {
12420
12978
  } });
12421
12979
  }
12422
12980
  async scrape(options, progressCallback, signal) {
12423
- await this.defaultStrategy.scrape(options, progressCallback, signal);
12981
+ return this.defaultStrategy.scrape(options, progressCallback, signal);
12424
12982
  }
12425
12983
  /**
12426
12984
  * Cleanup resources used by this strategy.
@@ -12440,7 +12998,7 @@ var PyPiScraperStrategy = class {
12440
12998
  } });
12441
12999
  }
12442
13000
  async scrape(options, progressCallback, signal) {
12443
- await this.defaultStrategy.scrape(options, progressCallback, signal);
13001
+ return this.defaultStrategy.scrape(options, progressCallback, signal);
12444
13002
  }
12445
13003
  /**
12446
13004
  * Cleanup resources used by this strategy.
@@ -12548,13 +13106,16 @@ var ScraperService = class {
12548
13106
  * Scrapes content from the provided URL using the appropriate strategy.
12549
13107
  * Reports progress via callback and handles errors.
12550
13108
  * Cleans up strategy resources after scrape completes (success or failure).
13109
+ *
13110
+ * @returns Why discovered links were rejected, for diagnosing an empty result.
12551
13111
  */
12552
13112
  async scrape(options, progressCallback, signal) {
12553
13113
  const strategy = this.registry.getStrategy(options.url);
13114
+ let summary = { rejections: [] };
12554
13115
  let scrapeError = null;
12555
13116
  let cleanupErrorToThrow = null;
12556
13117
  try {
12557
- await strategy.scrape(options, progressCallback, signal);
13118
+ summary = await strategy.scrape(options, progressCallback, signal);
12558
13119
  } catch (error) {
12559
13120
  scrapeError = error instanceof Error ? error : new ScraperError(`Scrape failed for URL: ${options.url}`, false);
12560
13121
  } finally {
@@ -12567,6 +13128,7 @@ var ScraperService = class {
12567
13128
  }
12568
13129
  if (scrapeError) throw scrapeError;
12569
13130
  if (cleanupErrorToThrow) throw cleanupErrorToThrow;
13131
+ return summary;
12570
13132
  }
12571
13133
  };
12572
13134
  // src/pipeline/PipelineWorker.ts
@@ -12585,6 +13147,8 @@ var PipelineWorker = class {
12585
13147
  * Executes the given pipeline job.
12586
13148
  * @param job - The job to execute.
12587
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.
12588
13152
  */
12589
13153
  async executeJob(job, callbacks) {
12590
13154
  const { id: jobId, library, version, scraperOptions, abortController } = job;
@@ -12592,24 +13156,28 @@ var PipelineWorker = class {
12592
13156
  logger.debug(`[${jobId}] Worker starting job for ${library}@${version}`);
12593
13157
  try {
12594
13158
  if (!scraperOptions.isRefresh && scraperOptions.clean !== false) {
12595
- await this.store.removeAllDocuments(library, version);
13159
+ await this.store.removeAllDocumentsByVersionId(job.versionId);
12596
13160
  logger.info(`💾 Cleared store for ${library}@${version || "latest"} before scraping.`);
12597
13161
  } else {
12598
13162
  const message = scraperOptions.isRefresh ? `🔄 Refresh operation - preserving existing data for ${library}@${version || "latest"}.` : `💾 Appending to store for ${library}@${version || "latest"} (clean=false).`;
12599
13163
  logger.info(message);
12600
13164
  }
12601
- await this.scraperService.scrape(scraperOptions, async (progress) => {
13165
+ const summary = await this.scraperService.scrape(scraperOptions, async (progress) => {
12602
13166
  if (signal.aborted) throw new CancellationError("Job cancelled during scraping progress");
12603
13167
  await callbacks.onJobProgress?.(job, progress);
12604
13168
  switch (progress.outcome) {
12605
13169
  case PageOutcome.Empty:
12606
- await this.recordEmptyPage(job, callbacks, library, version, progress);
13170
+ await this.recordEmptyPage(job, callbacks, progress);
12607
13171
  break;
12608
13172
  case PageOutcome.Absent:
12609
13173
  await this.removeDeletedPage(job, callbacks, progress);
12610
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;
12611
13179
  case PageOutcome.Stored:
12612
- await this.storeResult(job, callbacks, library, version, progress);
13180
+ await this.storeResult(job, callbacks, progress);
12613
13181
  break;
12614
13182
  case PageOutcome.Unchanged:
12615
13183
  case PageOutcome.Skipped:
@@ -12622,6 +13190,7 @@ var PipelineWorker = class {
12622
13190
  }, signal);
12623
13191
  if (signal.aborted) throw new CancellationError("Job cancelled");
12624
13192
  logger.debug(`[${jobId}] Worker finished job successfully.`);
13193
+ return await this.store.countChunksByVersionId(job.versionId) === 0 ? emptyVersionWarning(job, summary) : null;
12625
13194
  } catch (error) {
12626
13195
  logger.warn(`⚠️ [${jobId}] Worker encountered error: ${error}`);
12627
13196
  throw error;
@@ -12634,7 +13203,7 @@ var PipelineWorker = class {
12634
13203
  * content is left alone: we learned nothing about the page, and overwriting it
12635
13204
  * would discard good content on a transient fault.
12636
13205
  */
12637
- async recordEmptyPage(job, callbacks, library, version, progress) {
13206
+ async recordEmptyPage(job, callbacks, progress) {
12638
13207
  const { emptyPage } = progress;
12639
13208
  if (!emptyPage) {
12640
13209
  await this.removeDeletedPage(job, callbacks, progress);
@@ -12645,7 +13214,7 @@ var PipelineWorker = class {
12645
13214
  return;
12646
13215
  }
12647
13216
  try {
12648
- await this.store.addEmptyPage(library, version, progress.depth, {
13217
+ await this.store.addEmptyPageByVersionId(job.versionId, progress.depth, {
12649
13218
  url: emptyPage.url,
12650
13219
  contentUrl: emptyPage.contentUrl,
12651
13220
  title: emptyPage.title,
@@ -12682,10 +13251,10 @@ var PipelineWorker = class {
12682
13251
  /**
12683
13252
  * Stores processed content, replacing the page's previous content on refresh.
12684
13253
  */
12685
- async storeResult(job, callbacks, library, version, progress) {
13254
+ async storeResult(job, callbacks, progress) {
12686
13255
  if (!progress.result) return;
12687
13256
  try {
12688
- 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);
12689
13258
  logger.debug(`[${job.id}] Stored processed content: ${progress.currentUrl}`);
12690
13259
  } catch (docError) {
12691
13260
  logger.error(`❌ [${job.id}] Failed to process content ${progress.currentUrl}: ${docError}`);
@@ -12694,6 +13263,22 @@ var PipelineWorker = class {
12694
13263
  }
12695
13264
  }
12696
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
+ }
12697
13282
  // src/pipeline/PipelineManager.ts
12698
13283
  /**
12699
13284
  * PipelineManager orchestrates a queue of scraping/indexing jobs.
@@ -12761,8 +13346,12 @@ var PipelineManager = class {
12761
13346
  * Converts internal job representation to public job interface.
12762
13347
  * The processed page content (`progress.result`) stays on the internal job: it
12763
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.
12764
13352
  */
12765
13353
  toPublicJob(job) {
13354
+ const { headers: _headers, ...reportedScraperOptions } = job.scraperOptions;
12766
13355
  return {
12767
13356
  id: job.id,
12768
13357
  library: job.library,
@@ -12773,6 +13362,7 @@ var PipelineManager = class {
12773
13362
  result: null
12774
13363
  } : null,
12775
13364
  error: job.error ? { message: job.error.message } : null,
13365
+ warning: job.warning ?? null,
12776
13366
  createdAt: job.createdAt,
12777
13367
  startedAt: job.startedAt,
12778
13368
  finishedAt: job.finishedAt,
@@ -12784,7 +13374,7 @@ var PipelineManager = class {
12784
13374
  errorMessage: job.errorMessage,
12785
13375
  updatedAt: job.updatedAt,
12786
13376
  sourceUrl: job.sourceUrl,
12787
- scraperOptions: job.scraperOptions
13377
+ scraperOptions: reportedScraperOptions
12788
13378
  };
12789
13379
  }
12790
13380
  normalizeScraperOptions(options) {
@@ -13246,7 +13836,7 @@ var PipelineManager = class {
13246
13836
  const signal = abortController.signal;
13247
13837
  const worker = new PipelineWorker(this.store, this.scraperService);
13248
13838
  try {
13249
- await worker.executeJob(job, {
13839
+ const warning = await worker.executeJob(job, {
13250
13840
  onJobProgress: async (internalJob, progress) => {
13251
13841
  await this.updateJobProgress(internalJob, progress);
13252
13842
  },
@@ -13255,10 +13845,12 @@ var PipelineManager = class {
13255
13845
  }
13256
13846
  });
13257
13847
  if (signal.aborted) throw new CancellationError("Job cancelled just before completion");
13848
+ job.warning = warning;
13258
13849
  await this.updateJobStatus(job, PipelineJobStatus.COMPLETED);
13259
13850
  job.finishedAt = /* @__PURE__ */ new Date();
13260
13851
  job.resolveCompletion();
13261
- logger.info(`✅ Job completed: ${jobId}`);
13852
+ if (warning) logger.warn(`⚠️ Job completed with a warning: ${jobId}: ${warning}`);
13853
+ else logger.info(`✅ Job completed: ${jobId}`);
13262
13854
  } catch (error) {
13263
13855
  if (error instanceof CancellationError || signal.aborted) {
13264
13856
  await this.updateJobStatus(job, PipelineJobStatus.CANCELLED);
@@ -14267,15 +14859,6 @@ async function applyMigrations(db, options) {
14267
14859
  logger.warn("⚠️ Could not apply all production database settings");
14268
14860
  }
14269
14861
  }
14270
- // src/store/openDatabase.ts
14271
- /**
14272
- * Opens the SQLite database with better-sqlite3. The package ships Node-API
14273
- * binaries for Windows, macOS and Linux (glibc and musl) on x64 and arm64, so
14274
- * the binary loads under every Node.js version from 22.14 up and under Bun,
14275
- * without an install script or a download.
14276
- */
14277
- /** The Node-API version better-sqlite3's binaries are built for. */
14278
- var REQUIRED_NODE_API = 10;
14279
14862
  /**
14280
14863
  * Opens a better-sqlite3 database. Open databases only through this function,
14281
14864
  * so a binary that cannot load ends in one actionable error instead of a raw
@@ -14289,7 +14872,7 @@ var REQUIRED_NODE_API = 10;
14289
14872
  */
14290
14873
  function openDatabase(dbPath, options = {}) {
14291
14874
  const nodeApi = process.versions.napi;
14292
- if (nodeApi !== void 0 && Number(nodeApi) < REQUIRED_NODE_API) throw new NodeApiUnsupportedError(nodeApi, REQUIRED_NODE_API);
14875
+ if (nodeApi !== void 0 && Number(nodeApi) < 10) throw new NodeApiUnsupportedError(nodeApi, 10);
14293
14876
  try {
14294
14877
  return new Database(dbPath, options);
14295
14878
  } catch (error) {
@@ -14511,6 +15094,8 @@ var DocumentStore = class {
14511
15094
  JOIN libraries l ON v.library_id = l.id
14512
15095
  WHERE l.name = ? AND COALESCE(v.name, '') = COALESCE(?, '')
14513
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 = ?"),
14514
15099
  getDocumentBySort: this.db.prepare(`SELECT d.id
14515
15100
  FROM documents d
14516
15101
  JOIN pages p ON d.page_id = p.id
@@ -15606,120 +16191,188 @@ var DocumentStore = class {
15606
16191
  async addEmptyPage(library, version, depth, page, previousPageId) {
15607
16192
  try {
15608
16193
  const versionId = await this.resolveVersionId(library, version);
15609
- this.db.transaction(() => {
15610
- const current = this.statements.getPageId.get(versionId, page.url);
15611
- if (losesToStoredRepresentation(current, page.sourceContentType, page.isAdditionalRepresentation)) {
15612
- logger.debug(`Keeping stored ${current?.source_content_type} representation of ${page.url}; ignoring empty ${page.sourceContentType} version`);
15613
- this.retirePreviousPage(previousPageId, current);
15614
- return;
15615
- }
15616
- this.retirePreviousPage(previousPageId, current);
15617
- this.statements.insertPage.run(versionId, page.url, page.title || "", page.etag, page.lastModified, page.sourceContentType, page.contentType, depth, page.contentUrl ?? null);
15618
- const stored = current ?? this.statements.getPageId.get(versionId, page.url);
15619
- if (stored) this.statements.deleteDocumentsByPageId.run(stored.id);
15620
- })();
16194
+ this.addEmptyPageToVersion(versionId, depth, page, previousPageId);
15621
16195
  } catch (error) {
15622
16196
  throw new StoreError(`Failed to record empty page: ${error}`);
15623
16197
  }
15624
16198
  }
15625
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);
16216
+ } catch (error) {
16217
+ throw new StoreError(`Failed to record empty page: ${error}`);
16218
+ }
16219
+ }
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
+ /**
15626
16243
  * Stores documents with library and version metadata, generating embeddings
15627
16244
  * for vector similarity search. Uses the new pages table to normalize page-level
15628
16245
  * metadata and avoid duplication across document chunks.
15629
16246
  */
15630
16247
  async addDocuments(library, version, depth, result, previousPageId) {
15631
16248
  try {
15632
- const { title, url, chunks } = result;
15633
- if (chunks.length === 0) return;
16249
+ if (result.chunks.length === 0) return;
15634
16250
  const versionId = await this.resolveVersionId(library, version);
15635
- const existingPage = this.statements.getPageId.get(versionId, url);
15636
- if (previousPageId === void 0 && losesToStoredRepresentation(existingPage, result.sourceContentType, result.isAdditionalRepresentation)) {
15637
- logger.debug(`Keeping stored ${existingPage?.source_content_type} representation of ${url}; ignoring ${result.sourceContentType} version`);
15638
- return;
15639
- }
15640
- let paddedEmbeddings = [];
15641
- if (this.isVectorSearchEnabled) {
15642
- const texts = chunks.map((chunk) => {
15643
- return `${`<title>${title}</title>\n<url>${url}</url>\n<path>${(chunk.section.path || []).join(" / ")}</path>\n`}${chunk.content}`;
15644
- });
15645
- for (let i = 0; i < chunks.length; i++) {
15646
- const bodySize = chunks[i].content.length;
15647
- if (bodySize > this.splitterMaxChunkSize) logger.warn(`⚠️ Chunk ${i + 1}/${chunks.length} body exceeds max size: ${bodySize} > ${this.splitterMaxChunkSize} chars (URL: ${url})`);
15648
- }
15649
- const maxBatchChars = this.embeddingBatchChars;
15650
- const rawEmbeddings = [];
15651
- let currentBatch = [];
15652
- let currentBatchSize = 0;
15653
- let batchCount = 0;
15654
- const processEmbeddingBatch = async (isFinalBatch = false) => {
15655
- batchCount++;
15656
- const batchTexts = currentBatch;
15657
- const batchChars = currentBatchSize;
15658
- logger.debug(`Processing ${isFinalBatch ? "final " : ""}embedding batch ${batchCount}: ${batchTexts.length} texts, ${batchChars} chars`);
15659
- try {
15660
- const batchEmbeddings = await this.embedDocumentsWithRetry(batchTexts);
15661
- rawEmbeddings.push(...batchEmbeddings);
15662
- } catch (error) {
15663
- throw this.createEmbeddingConnectionError(error, {
15664
- url,
15665
- batchIndex: batchCount,
15666
- batchTextCount: batchTexts.length,
15667
- batchChars,
15668
- totalChunks: chunks.length
15669
- });
15670
- }
15671
- currentBatch = [];
15672
- currentBatchSize = 0;
15673
- };
15674
- for (const text of texts) {
15675
- const textSize = text.length;
15676
- if (currentBatchSize + textSize > maxBatchChars && currentBatch.length > 0) await processEmbeddingBatch();
15677
- currentBatch.push(text);
15678
- currentBatchSize += textSize;
15679
- if (currentBatch.length >= this.embeddingBatchSize) await processEmbeddingBatch();
15680
- }
15681
- if (currentBatch.length > 0) await processEmbeddingBatch(true);
15682
- paddedEmbeddings = rawEmbeddings.map((vector) => this.padVector(vector));
15683
- }
15684
- this.db.transaction(() => {
15685
- const current = this.statements.getPageId.get(versionId, url);
15686
- if (losesToStoredRepresentation(current, result.sourceContentType, result.isAdditionalRepresentation)) {
15687
- logger.debug(`Keeping stored ${current?.source_content_type} representation of ${url}; ignoring ${result.sourceContentType} version`);
15688
- this.retirePreviousPage(previousPageId, current);
15689
- return false;
15690
- }
15691
- this.retirePreviousPage(previousPageId, current);
15692
- if (current) {
15693
- const deleted = this.statements.deleteDocumentsByPageId.run(current.id);
15694
- if (deleted.changes > 0) logger.debug(`Deleted ${deleted.changes} existing documents for URL: ${url}`);
15695
- }
15696
- const sourceContentType = result.sourceContentType || result.contentType || null;
15697
- const contentType = result.contentType || result.sourceContentType || null;
15698
- const etag = result.etag || null;
15699
- const lastModified = result.lastModified || null;
15700
- this.statements.insertPage.run(versionId, url, title || "", etag, lastModified, sourceContentType, contentType, depth, result.contentUrl ?? null);
15701
- const insertedPage = this.statements.getPageId.get(versionId, url);
15702
- if (!insertedPage) throw new StoreError(`Failed to get page ID for URL: ${url}`);
15703
- const pageId = insertedPage.id;
15704
- let docIndex = 0;
15705
- for (let i = 0; i < chunks.length; i++) {
15706
- const chunk = chunks[i];
15707
- const rowId = this.statements.insertDocument.run(pageId, chunk.content, JSON.stringify({
15708
- types: chunk.types,
15709
- level: chunk.section.level,
15710
- path: chunk.section.path
15711
- }), i).lastInsertRowid;
15712
- if (this.isVectorSearchEnabled && paddedEmbeddings.length > 0) this.statements.insertEmbedding.run(Buffer.from(new Float32Array(paddedEmbeddings[docIndex]).buffer), BigInt(rowId));
15713
- docIndex++;
15714
- }
15715
- return true;
15716
- })();
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);
15717
16274
  } catch (error) {
15718
16275
  if (error instanceof StoreError) throw error;
15719
16276
  throw new ConnectionError("Failed to add documents to store", error);
15720
16277
  }
15721
16278
  }
15722
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
+ /**
15723
16376
  * Removes documents and pages matching specified library and version.
15724
16377
  * This consolidated method deletes both documents and their associated pages.
15725
16378
  * @returns Number of documents deleted
@@ -15742,6 +16395,34 @@ var DocumentStore = class {
15742
16395
  return changes;
15743
16396
  }
15744
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
+ /**
15745
16426
  * Deletes a page and all its associated document chunks.
15746
16427
  * Performs manual deletion in the correct order to satisfy foreign key constraints:
15747
16428
  * 1. Delete document chunks (page_id references pages.id)
@@ -15771,6 +16452,19 @@ var DocumentStore = class {
15771
16452
  }
15772
16453
  }
15773
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
+ /**
15774
16468
  * Finds pages whose URL or content URL equals one of the candidates.
15775
16469
  *
15776
16470
  * @param library Library name.
@@ -16786,6 +17480,24 @@ var DocumentManagementService = class DocumentManagementService {
16786
17480
  this.eventBus.emit(EventType.LIBRARY_CHANGE, void 0);
16787
17481
  }
16788
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
+ /**
16789
17501
  * Deletes a page and all its associated document chunks.
16790
17502
  * This is used during refresh operations when a page returns 404 Not Found.
16791
17503
  */
@@ -16802,6 +17514,15 @@ var DocumentManagementService = class DocumentManagementService {
16802
17514
  return this.store.getPagesByVersionId(versionId);
16803
17515
  }
16804
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
+ /**
16805
17526
  * Completely removes a library version and all associated documents.
16806
17527
  * Also removes the library if no other versions remain.
16807
17528
  * If the specified version doesn't exist but the library exists with no versions, removes the library.
@@ -16874,6 +17595,27 @@ var DocumentManagementService = class DocumentManagementService {
16874
17595
  this.eventBus.emit(EventType.LIBRARY_CHANGE, void 0);
16875
17596
  }
16876
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
+ /**
16877
17619
  * Adds pre-processed content directly to the store.
16878
17620
  * This method is used when content has already been processed by a pipeline,
16879
17621
  * avoiding redundant processing. Used primarily by the scraping pipeline.
@@ -16885,8 +17627,47 @@ var DocumentManagementService = class DocumentManagementService {
16885
17627
  * store when the write lands under a different row.
16886
17628
  */
16887
17629
  async addScrapeResult(library, version, depth, result, previousPageId) {
16888
- const processingStart = performance.now();
16889
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();
16890
17671
  const { url, title, chunks, contentType } = result;
16891
17672
  if (!url) throw new StoreError("Processed content metadata must include a valid URL");
16892
17673
  logger.info(`📚 Adding processed content: ${title || url}`);
@@ -16896,7 +17677,7 @@ var DocumentManagementService = class DocumentManagementService {
16896
17677
  }
16897
17678
  try {
16898
17679
  logger.info(`✂️ Storing ${chunks.length} pre-split chunks`);
16899
- await this.store.addDocuments(library, normalizedVersion, depth, result, previousPageId);
17680
+ await write();
16900
17681
  this.eventBus.emit(EventType.LIBRARY_CHANGE, void 0);
16901
17682
  } catch (error) {
16902
17683
  const processingTime = performance.now() - processingStart;
@@ -16904,8 +17685,8 @@ var DocumentManagementService = class DocumentManagementService {
16904
17685
  mimeType: contentType,
16905
17686
  contentSizeBytes: chunks.reduce((sum, chunk) => sum + chunk.content.length, 0),
16906
17687
  processingTimeMs: Math.round(processingTime),
16907
- library,
16908
- libraryVersion: normalizedVersion || null,
17688
+ library: ref.library,
17689
+ libraryVersion: ref.libraryVersion,
16909
17690
  context: "processed_content_storage",
16910
17691
  component: DocumentManagementService.constructor.name
16911
17692
  });
@@ -18144,7 +18925,8 @@ function createToolInputSchemas(config) {
18144
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."),
18145
18926
  preserveHashes: z.boolean().optional().describe("Preserve hash fragments for hash-routed SPA documentation sites."),
18146
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."),
18147
- 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.")
18148
18930
  }),
18149
18931
  refreshVersion: z.object({
18150
18932
  library: z.string().trim().describe("Library name."),
@@ -18224,7 +19006,7 @@ function createMcpServerInstance(tools, config, instructions, schemas) {
18224
19006
  const server = new McpServer({
18225
19007
  name,
18226
19008
  ...title !== void 0 ? { title } : {},
18227
- version: "3.5.0"
19009
+ version: "3.6.0"
18228
19010
  }, {
18229
19011
  capabilities: {
18230
19012
  tools: {},
@@ -18234,14 +19016,14 @@ function createMcpServerInstance(tools, config, instructions, schemas) {
18234
19016
  });
18235
19017
  if (!readOnly) {
18236
19018
  server.registerTool("scrape_docs", {
18237
- 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.",
18238
19020
  inputSchema: schemas.scrapeDocs,
18239
19021
  annotations: {
18240
19022
  title: "Scrape New Library Documentation",
18241
19023
  destructiveHint: true,
18242
19024
  openWorldHint: true
18243
19025
  }
18244
- }, 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 }) => {
18245
19027
  telemetry.track(TelemetryEvent.TOOL_USED, {
18246
19028
  tool: "scrape_docs",
18247
19029
  context: "mcp_server",
@@ -18251,7 +19033,8 @@ function createMcpServerInstance(tools, config, instructions, schemas) {
18251
19033
  urlProtocol: extractProtocol(url),
18252
19034
  maxPages,
18253
19035
  maxDepth,
18254
- scope
19036
+ scope,
19037
+ respectGitignore
18255
19038
  });
18256
19039
  try {
18257
19040
  const result = await tools.scrape.execute({
@@ -18267,7 +19050,8 @@ function createMcpServerInstance(tools, config, instructions, schemas) {
18267
19050
  followRedirects,
18268
19051
  preserveHashes,
18269
19052
  includePatterns,
18270
- excludePatterns
19053
+ excludePatterns,
19054
+ respectGitignore
18271
19055
  }
18272
19056
  });
18273
19057
  if ("jobId" in result) return createResponse(`🚀 Scraping job started with ID: ${result.jobId}.`);
@@ -18468,7 +19252,7 @@ ${r.content}\n`);
18468
19252
  });
18469
19253
  try {
18470
19254
  const result = await tools.listJobs.execute({ status });
18471
- 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");
18472
19256
  return createResponse(result.jobs.length > 0 ? `Current Jobs:\n\n${formattedJobs}` : "No jobs found.");
18473
19257
  } catch (error) {
18474
19258
  return createError(error);
@@ -18490,7 +19274,7 @@ ${r.content}\n`);
18490
19274
  });
18491
19275
  try {
18492
19276
  const job = (await tools.getJobInfo.execute({ jobId })).job;
18493
- 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}` : ""}`}`);
18494
19278
  } catch (error) {
18495
19279
  return createError(error);
18496
19280
  }
@@ -18837,6 +19621,7 @@ var GetJobInfoTool = class {
18837
19621
  startedAt: job.startedAt?.toISOString() ?? null,
18838
19622
  finishedAt: job.finishedAt?.toISOString() ?? null,
18839
19623
  error: job.error?.message ?? null,
19624
+ warning: job.warning ?? null,
18840
19625
  progress: job.progressMaxPages && job.progressMaxPages > 0 ? {
18841
19626
  pages: job.progressPages || 0,
18842
19627
  pagesIndexed: job.progress?.pagesIndexed ?? job.progressPagesIndexed ?? null,
@@ -18879,6 +19664,7 @@ var ListJobsTool = class {
18879
19664
  startedAt: job.startedAt?.toISOString() ?? null,
18880
19665
  finishedAt: job.finishedAt?.toISOString() ?? null,
18881
19666
  error: job.error?.message ?? null,
19667
+ warning: job.warning ?? null,
18882
19668
  progress: job.progressMaxPages && job.progressMaxPages > 0 ? {
18883
19669
  pages: job.progressPages || 0,
18884
19670
  pagesIndexed: job.progress?.pagesIndexed ?? job.progressPagesIndexed ?? null,
@@ -19076,6 +19862,7 @@ var ScrapeTool = class {
19076
19862
  scrapeMode: scraperOptions?.scrapeMode ?? ScrapeMode.Auto,
19077
19863
  includePatterns: scraperOptions?.includePatterns,
19078
19864
  excludePatterns: scraperOptions?.excludePatterns,
19865
+ respectGitignore: scraperOptions?.respectGitignore ?? url.startsWith("file://"),
19079
19866
  preserveHashes: scraperOptions?.preserveHashes,
19080
19867
  headers: scraperOptions?.headers,
19081
19868
  clean: scraperOptions?.clean
@@ -19086,7 +19873,10 @@ var ScrapeTool = class {
19086
19873
  const finalJob = await pipeline.getJob(jobId);
19087
19874
  const finalPagesScraped = finalJob?.progress?.pagesScraped ?? 0;
19088
19875
  logger.debug(`Job ${jobId} finished with status ${finalJob?.status}. Pages scraped: ${finalPagesScraped}`);
19089
- return { pagesScraped: finalPagesScraped };
19876
+ return {
19877
+ pagesScraped: finalPagesScraped,
19878
+ warning: finalJob?.warning ?? null
19879
+ };
19090
19880
  } catch (error) {
19091
19881
  logger.error(`❌ Job ${jobId} failed or was cancelled: ${error}`);
19092
19882
  throw error;
@@ -19333,7 +20123,7 @@ function buildSystemInfo(serverConfig, appConfig, mcpEndpointUrl, workerUrl) {
19333
20123
  const mcpEnabled = Boolean(serverConfig.enableMcpServer);
19334
20124
  const authEnabled = Boolean(appConfig.auth.enabled);
19335
20125
  return {
19336
- version: "3.5.0",
20126
+ version: "3.6.0",
19337
20127
  readOnly: Boolean(appConfig.app.readOnly),
19338
20128
  telemetryEnabled: Boolean(appConfig.app.telemetryEnabled),
19339
20129
  services: {
@@ -20027,7 +20817,7 @@ var AppServer = class AppServer {
20027
20817
  if (this.appConfig.app.telemetryEnabled && shouldEnableTelemetry()) try {
20028
20818
  if (telemetry.isEnabled()) {
20029
20819
  telemetry.setGlobalContext({
20030
- appVersion: "3.5.0",
20820
+ appVersion: "3.6.0",
20031
20821
  appPlatform: process.platform,
20032
20822
  appNodeVersion: process.version,
20033
20823
  appServicesEnabled: this.getActiveServicesList(),
@@ -21109,9 +21899,14 @@ function createScrapeCommand(cli) {
21109
21899
  }).option("exclude-pattern", {
21110
21900
  type: "string",
21111
21901
  array: true,
21112
- 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.",
21113
21903
  alias: "excludePattern",
21114
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
21115
21910
  }).option("header", {
21116
21911
  type: "string",
21117
21912
  array: true,
@@ -21165,6 +21960,7 @@ function createScrapeCommand(cli) {
21165
21960
  hasHeaders: argv.header.length > 0,
21166
21961
  hasIncludePatterns: argv.includePattern.length > 0,
21167
21962
  hasExcludePatterns: argv.excludePattern.length > 0,
21963
+ respectGitignore: argv.respectGitignore,
21168
21964
  useServerUrl: !!serverUrl
21169
21965
  });
21170
21966
  if (!serverUrl) ensurePlaywrightBrowsersInstalled();
@@ -21197,11 +21993,13 @@ function createScrapeCommand(cli) {
21197
21993
  preserveHashes,
21198
21994
  includePatterns: argv.includePattern?.length > 0 ? argv.includePattern : void 0,
21199
21995
  excludePatterns: argv.excludePattern?.length > 0 ? argv.excludePattern : void 0,
21996
+ respectGitignore: argv.respectGitignore,
21200
21997
  headers: Object.keys(headers).length > 0 ? headers : void 0,
21201
21998
  clean: argv.clean
21202
21999
  }
21203
22000
  });
21204
- 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`);
21205
22003
  else renderTextOutput(`Scraping job started with ID: ${result.jobId}`);
21206
22004
  } catch (error) {
21207
22005
  logger.error(`❌ Scraping failed: ${error instanceof Error ? error.message : String(error)}`);
@@ -21468,7 +22266,7 @@ function registerGlobalOptions(cli) {
21468
22266
  function createCli(argv) {
21469
22267
  let globalEventBus = null;
21470
22268
  const commandStartTimes = /* @__PURE__ */ new Map();
21471
- const cli = registerGlobalOptions(yargs(hideBin(argv))).scriptName("docs-mcp-server").strict().usage("Usage: $0 <command> [options]").version("3.5.0").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) => {
21472
22270
  if (argv.verbose && argv.quiet) throw new Error("Arguments verbose and quiet are mutually exclusive");
21473
22271
  applyGlobalCliOutputMode({
21474
22272
  verbose: argv.verbose,
@@ -21490,7 +22288,7 @@ function createCli(argv) {
21490
22288
  if (shouldEnableTelemetry() && telemetry.isEnabled()) {
21491
22289
  const commandName = argv._[0]?.toString() || "default";
21492
22290
  telemetry.setGlobalContext({
21493
- appVersion: "3.5.0",
22291
+ appVersion: "3.6.0",
21494
22292
  appPlatform: process.platform,
21495
22293
  appNodeVersion: process.version,
21496
22294
  appInterface: "cli",
@@ -21610,4 +22408,4 @@ async function runCli() {
21610
22408
  }
21611
22409
  export { runCli };
21612
22410
 
21613
- //# sourceMappingURL=main-D3_JhsO7.js.map
22411
+ //# sourceMappingURL=main-CBgiSgoD.js.map