@arabold/docs-mcp-server 2.3.0 → 2.4.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.
@@ -403,6 +403,7 @@ const DEFAULT_CONFIG = {
403
403
  skipKnownTrackers: true,
404
404
  pageTimeoutMs: 5e3,
405
405
  browserTimeoutMs: 3e4,
406
+ htmlExtractor: "cheerio",
406
407
  fetcher: {
407
408
  maxRetries: 3,
408
409
  baseDelayMs: 1e3,
@@ -499,6 +500,7 @@ const AppConfigSchema = z.object({
499
500
  skipKnownTrackers: envBoolean.default(DEFAULT_CONFIG.scraper.skipKnownTrackers),
500
501
  pageTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.pageTimeoutMs),
501
502
  browserTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.browserTimeoutMs),
503
+ htmlExtractor: z.enum(["cheerio", "defuddle"]).default(DEFAULT_CONFIG.scraper.htmlExtractor),
502
504
  fetcher: z.object({
503
505
  maxRetries: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.maxRetries),
504
506
  baseDelayMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.baseDelayMs),
@@ -3170,6 +3172,22 @@ class FingerprintGenerator {
3170
3172
  return this.headerGenerator.getHeaders();
3171
3173
  }
3172
3174
  }
3175
+ const MARKDOWN_PREFERRED_ACCEPT = "text/markdown, text/html;q=0.9, */*;q=0.8";
3176
+ function withMarkdownPreferredAccept(headers, callerHeaders = {}) {
3177
+ const hasCallerAccept = Object.keys(callerHeaders).some(
3178
+ (header) => header.toLowerCase() === "accept"
3179
+ );
3180
+ if (hasCallerAccept) {
3181
+ return headers;
3182
+ }
3183
+ const withoutGeneratedAccept = Object.fromEntries(
3184
+ Object.entries(headers).filter(([header]) => header.toLowerCase() !== "accept")
3185
+ );
3186
+ return {
3187
+ ...withoutGeneratedAccept,
3188
+ Accept: MARKDOWN_PREFERRED_ACCEPT
3189
+ };
3190
+ }
3173
3191
  var FetchStatus = /* @__PURE__ */ ((FetchStatus2) => {
3174
3192
  FetchStatus2["SUCCESS"] = "success";
3175
3193
  FetchStatus2["NOT_MODIFIED"] = "not_modified";
@@ -3218,10 +3236,15 @@ class BrowserFetcher {
3218
3236
  }
3219
3237
  return await route.continue();
3220
3238
  });
3221
- await page.setExtraHTTPHeaders({
3222
- ...fingerprintHeaders,
3223
- ...options?.headers
3224
- });
3239
+ await page.setExtraHTTPHeaders(
3240
+ withMarkdownPreferredAccept(
3241
+ {
3242
+ ...fingerprintHeaders,
3243
+ ...options?.headers
3244
+ },
3245
+ options?.headers
3246
+ )
3247
+ );
3225
3248
  const timeout = options?.timeout || this.defaultTimeoutMs;
3226
3249
  logger.debug(`Navigating to ${source} with browser...`);
3227
3250
  const response = await page.goto(source, {
@@ -3239,10 +3262,10 @@ class BrowserFetcher {
3239
3262
  }
3240
3263
  const finalUrl = page.url();
3241
3264
  await this.accessPolicy.assertNetworkUrlAllowed(finalUrl);
3242
- const content = await page.content();
3243
- const contentBuffer = Buffer.from(content, "utf-8");
3244
3265
  const contentType = response.headers()["content-type"] || "text/html";
3245
3266
  const { mimeType, charset } = MimeTypeUtils.parseContentType(contentType);
3267
+ const content = MimeTypeUtils.isHtml(mimeType) ? await page.content() : await response.body();
3268
+ const contentBuffer = Buffer.isBuffer(content) ? content : Buffer.from(content, "utf-8");
3246
3269
  const etag = response.headers().etag;
3247
3270
  return {
3248
3271
  content: contentBuffer,
@@ -3465,11 +3488,14 @@ class HttpFetcher {
3465
3488
  let redirectCount = 0;
3466
3489
  while (true) {
3467
3490
  const fingerprint = this.fingerprintGenerator.generateHeaders();
3468
- const headers = {
3469
- ...fingerprint,
3470
- ...options?.headers
3471
- // User-provided headers override generated ones
3472
- };
3491
+ const headers = withMarkdownPreferredAccept(
3492
+ {
3493
+ ...fingerprint,
3494
+ ...options?.headers
3495
+ // User-provided headers override generated ones
3496
+ },
3497
+ options?.headers
3498
+ );
3473
3499
  if (options?.etag) {
3474
3500
  headers["If-None-Match"] = options.etag;
3475
3501
  logger.debug(
@@ -4038,36 +4064,107 @@ class CodeContentSplitter {
4038
4064
  }
4039
4065
  options;
4040
4066
  async split(content) {
4041
- const language = content.match(/^```(\w+)\n/)?.[1];
4042
- const strippedContent = content.replace(/^```(\w*)\n/, "").replace(/```\s*$/, "");
4067
+ const infoMatch = content.match(/^```([^\n]*)\n/);
4068
+ const infoString = (infoMatch?.[1] ?? "").trimEnd();
4069
+ const strippedContent = content.replace(/^```[^\n]*\n/, "").replace(/```\s*$/, "");
4043
4070
  const lines = strippedContent.split("\n");
4044
4071
  const chunks = [];
4045
4072
  let currentChunkLines = [];
4046
4073
  for (const line of lines) {
4047
- const singleLineSize = this.wrap(line, language).length;
4074
+ const singleLineSize = this.wrap(line, infoString).length;
4048
4075
  if (singleLineSize > this.options.chunkSize) {
4049
4076
  throw new MinimumChunkSizeError(singleLineSize, this.options.chunkSize);
4050
4077
  }
4051
4078
  currentChunkLines.push(line);
4052
- const newChunkContent = this.wrap(currentChunkLines.join("\n"), language);
4079
+ const newChunkContent = this.wrap(currentChunkLines.join("\n"), infoString);
4053
4080
  const newChunkSize = newChunkContent.length;
4054
4081
  if (newChunkSize > this.options.chunkSize && currentChunkLines.length > 1) {
4055
4082
  const lastLine = currentChunkLines.pop();
4056
- chunks.push(this.wrap(currentChunkLines.join("\n"), language));
4083
+ chunks.push(this.wrap(currentChunkLines.join("\n"), infoString));
4057
4084
  currentChunkLines = [lastLine];
4058
4085
  }
4059
4086
  }
4060
4087
  if (currentChunkLines.length > 0) {
4061
- chunks.push(this.wrap(currentChunkLines.join("\n"), language));
4088
+ chunks.push(this.wrap(currentChunkLines.join("\n"), infoString));
4062
4089
  }
4063
4090
  return chunks;
4064
4091
  }
4065
- wrap(content, language) {
4066
- return `\`\`\`${language || ""}
4092
+ wrap(content, infoString) {
4093
+ return `\`\`\`${infoString || ""}
4067
4094
  ${content.replace(/\n+$/, "")}
4068
4095
  \`\`\``;
4069
4096
  }
4070
4097
  }
4098
+ const FENCE_PREFIX = "[ \\t]*(?:>[ \\t]*)*";
4099
+ const FENCE_OPENER = new RegExp(`^${FENCE_PREFIX}(\`{3,}|~{3,})`);
4100
+ function splitLinesWithOffsets(text) {
4101
+ const lines = [];
4102
+ let offset = 0;
4103
+ while (offset <= text.length) {
4104
+ const nlIndex = text.indexOf("\n", offset);
4105
+ if (nlIndex === -1) {
4106
+ if (offset < text.length) {
4107
+ lines.push({ content: text.slice(offset), offset, newlineLength: 0 });
4108
+ }
4109
+ return lines;
4110
+ }
4111
+ lines.push({
4112
+ content: text.slice(offset, nlIndex),
4113
+ offset,
4114
+ newlineLength: 1
4115
+ });
4116
+ offset = nlIndex + 1;
4117
+ }
4118
+ return lines;
4119
+ }
4120
+ function isClosingFence(line, delimiter, openerCount) {
4121
+ const closerRegex = new RegExp(
4122
+ `^${FENCE_PREFIX}\\${delimiter}{${openerCount},}[ \\t]*$`
4123
+ );
4124
+ return closerRegex.test(line);
4125
+ }
4126
+ function findFenceRegions(text) {
4127
+ const regions = [];
4128
+ const lines = splitLinesWithOffsets(text);
4129
+ let i = 0;
4130
+ while (i < lines.length) {
4131
+ const opener = FENCE_OPENER.exec(lines[i].content);
4132
+ if (!opener) {
4133
+ i += 1;
4134
+ continue;
4135
+ }
4136
+ const delimiter = opener[1][0];
4137
+ const count = opener[1].length;
4138
+ const startOffset = lines[i].offset;
4139
+ let closerLineIndex = -1;
4140
+ for (let j = i + 1; j < lines.length; j++) {
4141
+ if (isClosingFence(lines[j].content, delimiter, count)) {
4142
+ closerLineIndex = j;
4143
+ break;
4144
+ }
4145
+ }
4146
+ if (closerLineIndex === -1) {
4147
+ regions.push({ startOffset, endOffset: text.length });
4148
+ break;
4149
+ }
4150
+ const closerLine = lines[closerLineIndex];
4151
+ const endOffset = closerLine.offset + closerLine.content.length + closerLine.newlineLength;
4152
+ regions.push({ startOffset, endOffset });
4153
+ i = closerLineIndex + 1;
4154
+ }
4155
+ return regions;
4156
+ }
4157
+ function hasOpenFenceAtEnd(chunk) {
4158
+ const regions = findFenceRegions(chunk);
4159
+ if (regions.length === 0) return false;
4160
+ const last = regions[regions.length - 1];
4161
+ if (last.endOffset !== chunk.length) return false;
4162
+ const lines = splitLinesWithOffsets(chunk.slice(last.startOffset));
4163
+ if (lines.length < 2) return true;
4164
+ const opener = FENCE_OPENER.exec(lines[0].content);
4165
+ if (!opener) return false;
4166
+ return !isClosingFence(lines[lines.length - 1].content, opener[1][0], opener[1].length);
4167
+ }
4071
4168
  class TextContentSplitter {
4072
4169
  constructor(options) {
4073
4170
  this.options = options;
@@ -4089,16 +4186,50 @@ class TextContentSplitter {
4089
4186
  if (longestWord.length > this.options.chunkSize) {
4090
4187
  throw new MinimumChunkSizeError(longestWord.length, this.options.chunkSize);
4091
4188
  }
4092
- const paragraphChunks = this.splitByParagraphs(content);
4189
+ const paragraphChunks = this.mergeForFenceBalance(
4190
+ this.splitByParagraphs(content),
4191
+ ""
4192
+ );
4093
4193
  if (this.areChunksValid(paragraphChunks)) {
4094
4194
  return paragraphChunks;
4095
4195
  }
4096
- const lineChunks = this.splitByLines(content);
4196
+ const lineChunks = this.mergeForFenceBalance(this.splitByLines(content), "");
4097
4197
  if (this.areChunksValid(lineChunks)) {
4098
4198
  return this.mergeChunks(lineChunks, "");
4099
4199
  }
4100
- const wordChunks = await this.splitByWords(content);
4101
- return this.mergeChunks(wordChunks, " ");
4200
+ const wordChunks = this.mergeForFenceBalance(await this.splitByWords(content), " ");
4201
+ const merged = this.mergeChunks(wordChunks, " ");
4202
+ this.warnOversize(merged);
4203
+ return merged;
4204
+ }
4205
+ /**
4206
+ * Walks `chunks` left to right and merges adjacent chunks whenever the running
4207
+ * buffer ends inside an open fenced code block. Guarantees that every emitted
4208
+ * chunk has balanced fences (i.e. `hasOpenFenceAtEnd` returns false).
4209
+ */
4210
+ mergeForFenceBalance(chunks, separator) {
4211
+ const result = [];
4212
+ let buffer = "";
4213
+ for (const chunk of chunks) {
4214
+ buffer = buffer ? `${buffer}${separator}${chunk}` : chunk;
4215
+ if (!hasOpenFenceAtEnd(buffer)) {
4216
+ result.push(buffer);
4217
+ buffer = "";
4218
+ }
4219
+ }
4220
+ if (buffer) {
4221
+ result.push(buffer);
4222
+ }
4223
+ return result;
4224
+ }
4225
+ warnOversize(chunks) {
4226
+ for (const chunk of chunks) {
4227
+ if (chunk.length > this.options.chunkSize) {
4228
+ logger.warn(
4229
+ `⚠ TextContentSplitter emitted oversize chunk to preserve fence balance: ${chunk.length} > ${this.options.chunkSize}`
4230
+ );
4231
+ }
4232
+ }
4102
4233
  }
4103
4234
  /**
4104
4235
  * Checks if all chunks are within the maximum size limit
@@ -5392,7 +5523,7 @@ class HtmlPlaywrightMiddleware {
5392
5523
  * Consider making this more robust (e.g., lazy initialization, singleton).
5393
5524
  */
5394
5525
  async ensureBrowser() {
5395
- if (!this.browser || !this.browser.isConnected()) {
5526
+ if (!this.browser?.isConnected()) {
5396
5527
  logger.debug("Launching new Playwright browser instance (Chromium)");
5397
5528
  this.browser = await BrowserFetcher.launchBrowser();
5398
5529
  this.browser.on("disconnected", () => {
@@ -5770,127 +5901,160 @@ class HtmlPlaywrightMiddleware {
5770
5901
  }
5771
5902
  return false;
5772
5903
  }
5773
- async setupCachingRouteInterception(page, customHeaders = {}, credentials, origin) {
5774
- await page.route("**/*", async (route) => {
5775
- const reqUrl = route.request().url();
5776
- const reqOrigin = (() => {
5777
- try {
5778
- return new URL(reqUrl).origin;
5779
- } catch {
5780
- return null;
5781
- }
5782
- })();
5783
- const resourceType = route.request().resourceType();
5784
- if (!await this.isRequestAllowed(reqUrl)) {
5785
- return await route.abort("blockedbyclient");
5786
- }
5787
- if (await this.tryBlocklistAbort(route, reqUrl)) {
5904
+ isTargetClosedError(error) {
5905
+ if (!(error instanceof Error)) {
5906
+ return false;
5907
+ }
5908
+ return error.message.includes("Target page, context or browser has been closed");
5909
+ }
5910
+ formatRouteError(error) {
5911
+ const message = error instanceof Error ? error.message : String(error);
5912
+ return message.split("\n")[0] || message;
5913
+ }
5914
+ isSpeculativePrefetch(route) {
5915
+ const headers = route.request().headers();
5916
+ return headers["next-router-prefetch"] === "1" || headers.purpose?.toLowerCase() === "prefetch" || headers["sec-purpose"]?.toLowerCase().includes("prefetch") === true;
5917
+ }
5918
+ isCacheableResponseContent(contentType) {
5919
+ const { mimeType } = MimeTypeUtils.parseContentType(contentType);
5920
+ return MimeTypeUtils.isHtml(mimeType) || MimeTypeUtils.isMarkdown(mimeType) || MimeTypeUtils.isSafeForTextProcessing(mimeType);
5921
+ }
5922
+ getRequestOrigin(url) {
5923
+ try {
5924
+ return new URL(url).origin;
5925
+ } catch {
5926
+ return null;
5927
+ }
5928
+ }
5929
+ ignoreRouteLifecycleError(error, action, reqUrl) {
5930
+ if (this.isRouteAlreadyHandledError(error)) {
5931
+ logger.debug(`Route already handled (${action}): ${reqUrl}`);
5932
+ return true;
5933
+ }
5934
+ if (this.isTargetClosedError(error)) {
5935
+ logger.debug(`Route target closed (${action}): ${reqUrl}`);
5936
+ return true;
5937
+ }
5938
+ return false;
5939
+ }
5940
+ async abortRoute(route, reqUrl, action, reason) {
5941
+ try {
5942
+ await route.abort(reason);
5943
+ } catch (error) {
5944
+ if (this.ignoreRouteLifecycleError(error, action, reqUrl)) {
5788
5945
  return;
5789
5946
  }
5790
- if (["image", "font", "media"].includes(resourceType)) {
5791
- try {
5792
- return await route.abort();
5793
- } catch (error) {
5794
- if (this.isRouteAlreadyHandledError(error)) {
5795
- logger.debug(`Route already handled (abort): ${reqUrl}`);
5796
- return;
5797
- }
5798
- throw error;
5799
- }
5947
+ throw error;
5948
+ }
5949
+ }
5950
+ async fulfillRoute(route, reqUrl, options, action) {
5951
+ try {
5952
+ await route.fulfill(options);
5953
+ } catch (error) {
5954
+ if (this.ignoreRouteLifecycleError(error, action, reqUrl)) {
5955
+ return;
5800
5956
  }
5801
- if (route.request().method() === "GET") {
5802
- const cached = HtmlPlaywrightMiddleware.resourceCache.get(reqUrl);
5803
- if (cached !== void 0) {
5804
- logger.debug(`✓ Cache hit for ${resourceType}: ${reqUrl}`);
5805
- try {
5806
- return await route.fulfill({
5807
- status: 200,
5808
- contentType: cached.contentType,
5809
- body: cached.body
5810
- });
5811
- } catch (error) {
5812
- if (this.isRouteAlreadyHandledError(error)) {
5813
- logger.debug(`Route already handled (fulfill cached): ${reqUrl}`);
5814
- return;
5815
- }
5816
- throw error;
5817
- }
5818
- }
5819
- const headers2 = mergePlaywrightHeaders(
5820
- route.request().headers(),
5821
- customHeaders,
5822
- credentials,
5823
- origin,
5824
- reqOrigin ?? void 0
5825
- );
5826
- try {
5827
- const response = await route.fetch({ headers: headers2 });
5828
- const body = await response.text();
5829
- if (response.status() >= 200 && response.status() < 300 && body.length > 0) {
5830
- const contentSizeBytes = Buffer.byteLength(body, "utf8");
5831
- if (contentSizeBytes <= this.config.fetcher.maxCacheItemSizeBytes) {
5832
- const contentType = response.headers()["content-type"] || "application/octet-stream";
5833
- HtmlPlaywrightMiddleware.resourceCache.set(reqUrl, { body, contentType });
5834
- logger.debug(
5835
- `Cached ${resourceType}: ${reqUrl} (${contentSizeBytes} bytes, cache size: ${HtmlPlaywrightMiddleware.resourceCache.size})`
5836
- );
5837
- } else {
5838
- logger.debug(
5839
- `Resource too large to cache: ${reqUrl} (${contentSizeBytes} bytes > ${this.config.fetcher.maxCacheItemSizeBytes} bytes limit)`
5840
- );
5841
- }
5842
- }
5843
- try {
5844
- return await route.fulfill({ response });
5845
- } catch (error) {
5846
- if (this.isRouteAlreadyHandledError(error)) {
5847
- logger.debug(`Route already handled (fulfill): ${reqUrl}`);
5848
- return;
5849
- }
5850
- throw error;
5851
- }
5852
- } catch (error) {
5853
- const errorMessage = error instanceof Error ? error.message : String(error);
5854
- logger.debug(
5855
- `Network error fetching ${resourceType} ${reqUrl}: ${errorMessage}`
5856
- );
5857
- try {
5858
- return await route.abort("failed");
5859
- } catch (abortError) {
5860
- if (this.isRouteAlreadyHandledError(abortError)) {
5861
- logger.debug(`Route already handled (abort after error): ${reqUrl}`);
5862
- return;
5863
- }
5864
- throw abortError;
5865
- }
5866
- }
5957
+ throw error;
5958
+ }
5959
+ }
5960
+ async continueRoute(route, reqUrl, resourceType, options) {
5961
+ try {
5962
+ await route.continue(options);
5963
+ } catch (error) {
5964
+ if (this.ignoreRouteLifecycleError(error, "continue", reqUrl)) {
5965
+ return;
5867
5966
  }
5868
- const headers = mergePlaywrightHeaders(
5869
- route.request().headers(),
5870
- customHeaders,
5871
- credentials,
5872
- origin,
5873
- reqOrigin ?? void 0
5967
+ const errorMessage = this.formatRouteError(error);
5968
+ logger.debug(`Error continuing ${resourceType} ${reqUrl}: ${errorMessage}`);
5969
+ await this.abortRoute(route, reqUrl, "abort after continue error", "failed");
5970
+ }
5971
+ }
5972
+ async cacheResponseIfEligible(reqUrl, resourceType, response) {
5973
+ const contentType = response.headers()["content-type"] || "application/octet-stream";
5974
+ if (response.status() < 200 || response.status() >= 300) {
5975
+ return;
5976
+ }
5977
+ if (!this.isCacheableResponseContent(contentType)) {
5978
+ logger.debug(
5979
+ `Skipping cache for unsupported content type "${contentType}" (${resourceType}): ${reqUrl}`
5874
5980
  );
5875
- try {
5876
- return await route.continue({ headers });
5877
- } catch (error) {
5878
- if (this.isRouteAlreadyHandledError(error)) {
5879
- logger.debug(`Route already handled (continue): ${reqUrl}`);
5880
- return;
5881
- }
5882
- const errorMessage = error instanceof Error ? error.message : String(error);
5883
- logger.debug(`Error continuing ${resourceType} ${reqUrl}: ${errorMessage}`);
5884
- try {
5885
- return await route.abort("failed");
5886
- } catch (abortError) {
5887
- if (this.isRouteAlreadyHandledError(abortError)) {
5888
- logger.debug(`Route already handled (abort after continue error): ${reqUrl}`);
5889
- return;
5890
- }
5891
- throw abortError;
5892
- }
5981
+ return;
5982
+ }
5983
+ const body = await response.text();
5984
+ if (body.length === 0) {
5985
+ return;
5986
+ }
5987
+ const contentSizeBytes = Buffer.byteLength(body, "utf8");
5988
+ const maxCacheItemSizeBytes = this.config?.fetcher?.maxCacheItemSizeBytes ?? defaults.scraper.fetcher.maxCacheItemSizeBytes;
5989
+ if (contentSizeBytes > maxCacheItemSizeBytes) {
5990
+ logger.debug(
5991
+ `Resource too large to cache: ${reqUrl} (${contentSizeBytes} bytes > ${maxCacheItemSizeBytes} bytes limit)`
5992
+ );
5993
+ return;
5994
+ }
5995
+ HtmlPlaywrightMiddleware.resourceCache.set(reqUrl, { body, contentType });
5996
+ logger.debug(
5997
+ `Cached ${resourceType}: ${reqUrl} (${contentSizeBytes} bytes, cache size: ${HtmlPlaywrightMiddleware.resourceCache.size})`
5998
+ );
5999
+ }
6000
+ async handleSubresourceRoute(route, customHeaders, credentials, origin) {
6001
+ const reqUrl = route.request().url();
6002
+ const reqOrigin = this.getRequestOrigin(reqUrl);
6003
+ const resourceType = route.request().resourceType();
6004
+ if (!await this.isRequestAllowed(reqUrl)) {
6005
+ await this.abortRoute(route, reqUrl, "policy abort", "blockedbyclient");
6006
+ return;
6007
+ }
6008
+ if (await this.tryBlocklistAbort(route, reqUrl)) {
6009
+ return;
6010
+ }
6011
+ if (this.isSpeculativePrefetch(route)) {
6012
+ logger.debug(`Aborting speculative prefetch ${resourceType}: ${reqUrl}`);
6013
+ await this.abortRoute(route, reqUrl, "prefetch abort", "aborted");
6014
+ return;
6015
+ }
6016
+ if (["image", "font", "media"].includes(resourceType)) {
6017
+ await this.abortRoute(route, reqUrl, "abort");
6018
+ return;
6019
+ }
6020
+ const headers = mergePlaywrightHeaders(
6021
+ route.request().headers(),
6022
+ customHeaders,
6023
+ credentials,
6024
+ origin,
6025
+ reqOrigin ?? void 0
6026
+ );
6027
+ if (route.request().method() !== "GET") {
6028
+ await this.continueRoute(route, reqUrl, resourceType, { headers });
6029
+ return;
6030
+ }
6031
+ const cached = HtmlPlaywrightMiddleware.resourceCache.get(reqUrl);
6032
+ if (cached !== void 0) {
6033
+ logger.debug(`✓ Cache hit for ${resourceType}: ${reqUrl}`);
6034
+ await this.fulfillRoute(
6035
+ route,
6036
+ reqUrl,
6037
+ { status: 200, contentType: cached.contentType, body: cached.body },
6038
+ "fulfill cached"
6039
+ );
6040
+ return;
6041
+ }
6042
+ try {
6043
+ const response = await route.fetch({ headers });
6044
+ await this.cacheResponseIfEligible(reqUrl, resourceType, response);
6045
+ await this.fulfillRoute(route, reqUrl, { response }, "fulfill");
6046
+ } catch (error) {
6047
+ if (this.ignoreRouteLifecycleError(error, `fetch ${resourceType}`, reqUrl)) {
6048
+ return;
5893
6049
  }
6050
+ const errorMessage = this.formatRouteError(error);
6051
+ logger.debug(`Network error fetching ${resourceType} ${reqUrl}: ${errorMessage}`);
6052
+ await this.abortRoute(route, reqUrl, "abort after error", "failed");
6053
+ }
6054
+ }
6055
+ async setupCachingRouteInterception(page, customHeaders = {}, credentials, origin) {
6056
+ await page.route("**/*", async (route) => {
6057
+ await this.handleSubresourceRoute(route, customHeaders, credentials, origin);
5894
6058
  });
5895
6059
  }
5896
6060
  /**
@@ -6077,127 +6241,12 @@ ${frame.content}
6077
6241
  throw error;
6078
6242
  }
6079
6243
  }
6080
- const reqOrigin = (() => {
6081
- try {
6082
- return new URL(reqUrl).origin;
6083
- } catch {
6084
- return null;
6085
- }
6086
- })();
6087
- const resourceType = route.request().resourceType();
6088
- if (!await this.isRequestAllowed(reqUrl)) {
6089
- return await route.abort("blockedbyclient");
6090
- }
6091
- if (await this.tryBlocklistAbort(route, reqUrl)) {
6092
- return;
6093
- }
6094
- if (["image", "font", "media"].includes(resourceType)) {
6095
- try {
6096
- return await route.abort();
6097
- } catch (error) {
6098
- if (this.isRouteAlreadyHandledError(error)) {
6099
- logger.debug(`Route already handled (abort): ${reqUrl}`);
6100
- return;
6101
- }
6102
- throw error;
6103
- }
6104
- }
6105
- if (route.request().method() === "GET") {
6106
- const cached = HtmlPlaywrightMiddleware.resourceCache.get(reqUrl);
6107
- if (cached !== void 0) {
6108
- logger.debug(`✓ Cache hit for ${resourceType}: ${reqUrl}`);
6109
- try {
6110
- return await route.fulfill({
6111
- status: 200,
6112
- contentType: cached.contentType,
6113
- body: cached.body
6114
- });
6115
- } catch (error) {
6116
- if (this.isRouteAlreadyHandledError(error)) {
6117
- logger.debug(`Route already handled (fulfill cached): ${reqUrl}`);
6118
- return;
6119
- }
6120
- throw error;
6121
- }
6122
- }
6123
- const headers2 = mergePlaywrightHeaders(
6124
- route.request().headers(),
6125
- customHeaders,
6126
- credentials ?? void 0,
6127
- origin ?? void 0,
6128
- reqOrigin ?? void 0
6129
- );
6130
- try {
6131
- const response = await route.fetch({ headers: headers2 });
6132
- const body = await response.text();
6133
- if (response.status() >= 200 && response.status() < 300 && body.length > 0) {
6134
- const contentSizeBytes = Buffer.byteLength(body, "utf8");
6135
- const maxCacheItemSizeBytes = this.config?.fetcher?.maxCacheItemSizeBytes ?? defaults.scraper.fetcher.maxCacheItemSizeBytes;
6136
- if (contentSizeBytes <= maxCacheItemSizeBytes) {
6137
- const contentType2 = response.headers()["content-type"] || "application/octet-stream";
6138
- HtmlPlaywrightMiddleware.resourceCache.set(reqUrl, { body, contentType: contentType2 });
6139
- logger.debug(
6140
- `Cached ${resourceType}: ${reqUrl} (${contentSizeBytes} bytes, cache size: ${HtmlPlaywrightMiddleware.resourceCache.size})`
6141
- );
6142
- } else {
6143
- logger.debug(
6144
- `Resource too large to cache: ${reqUrl} (${contentSizeBytes} bytes > ${maxCacheItemSizeBytes} bytes limit)`
6145
- );
6146
- }
6147
- }
6148
- try {
6149
- return await route.fulfill({ response });
6150
- } catch (error) {
6151
- if (this.isRouteAlreadyHandledError(error)) {
6152
- logger.debug(`Route already handled (fulfill): ${reqUrl}`);
6153
- return;
6154
- }
6155
- throw error;
6156
- }
6157
- } catch (error) {
6158
- const errorMessage = error instanceof Error ? error.message : String(error);
6159
- logger.debug(
6160
- `Network error fetching ${resourceType} ${reqUrl}: ${errorMessage}`
6161
- );
6162
- try {
6163
- return await route.abort("failed");
6164
- } catch (abortError) {
6165
- if (this.isRouteAlreadyHandledError(abortError)) {
6166
- logger.debug(`Route already handled (abort after error): ${reqUrl}`);
6167
- return;
6168
- }
6169
- throw abortError;
6170
- }
6171
- }
6172
- }
6173
- const headers = mergePlaywrightHeaders(
6174
- route.request().headers(),
6244
+ await this.handleSubresourceRoute(
6245
+ route,
6175
6246
  customHeaders,
6176
6247
  credentials ?? void 0,
6177
- origin ?? void 0,
6178
- reqOrigin ?? void 0
6248
+ origin ?? void 0
6179
6249
  );
6180
- try {
6181
- return await route.continue({ headers });
6182
- } catch (error) {
6183
- if (this.isRouteAlreadyHandledError(error)) {
6184
- logger.debug(`Route already handled (continue): ${reqUrl}`);
6185
- return;
6186
- }
6187
- const errorMessage = error instanceof Error ? error.message : String(error);
6188
- logger.debug(`Error continuing ${resourceType} ${reqUrl}: ${errorMessage}`);
6189
- try {
6190
- return await route.abort("failed");
6191
- } catch (abortError) {
6192
- if (this.isRouteAlreadyHandledError(abortError)) {
6193
- logger.debug(
6194
- `Route already handled (abort after continue error): ${reqUrl}`
6195
- );
6196
- return;
6197
- }
6198
- throw abortError;
6199
- }
6200
- }
6201
6250
  });
6202
6251
  await page.goto(context.source, { waitUntil: "load" });
6203
6252
  const pageTimeoutMs = this.config.pageTimeoutMs ?? defaults.scraper.pageTimeoutMs;
@@ -6302,7 +6351,7 @@ function mergePlaywrightHeaders(requestHeaders, customHeaders, credentials, orig
6302
6351
  Authorization: `Basic ${basic}`
6303
6352
  };
6304
6353
  }
6305
- return headers;
6354
+ return withMarkdownPreferredAccept(headers, customHeaders);
6306
6355
  }
6307
6356
  class HtmlSanitizerMiddleware {
6308
6357
  // Default selectors to remove
@@ -6376,7 +6425,84 @@ class HtmlSanitizerMiddleware {
6376
6425
  '[role="search"]',
6377
6426
  '[role="region"][aria-label*="skip" i]',
6378
6427
  '[aria-modal="true"]',
6379
- ".noprint"
6428
+ ".noprint",
6429
+ // Skip-links and screen-reader-only anchors (e.g. "Skip to main content").
6430
+ // Scoped to <a> so icon-button labels (`<span class="sr-only">`) are left alone.
6431
+ "a.sr-only",
6432
+ "a.skip-link",
6433
+ "a.skip-nav",
6434
+ "a.screen-reader-only",
6435
+ "a.visually-hidden",
6436
+ // Breadcrumb variants beyond the .breadcrumb class above (ARIA + schema.org).
6437
+ '[aria-label="Breadcrumb" i]',
6438
+ '[itemtype*="BreadcrumbList"]',
6439
+ // Ad networks — removed at sanitization time (after render) rather than at
6440
+ // network level, to avoid triggering anti-adblock detection on monetized
6441
+ // sites. See subresourceBlocklist.ts for the rationale on why ads are not
6442
+ // network-blocked.
6443
+ // Carbon Ads (Vite, Astro, Tailwind, MDN, …)
6444
+ "#carbonads",
6445
+ ".carbonads",
6446
+ ".carbon-wrap",
6447
+ ".carbon-text",
6448
+ ".carbon-img",
6449
+ ".carbon-poweredby",
6450
+ // Scoped to the click-redirect host (srv.carbonads.net) rather than the
6451
+ // apex domain so that legitimate prose links to carbonads.net survive.
6452
+ 'a[href*="srv.carbonads.net"]',
6453
+ // BuySellAds
6454
+ ".bsa-promotion",
6455
+ ".bsa-cpc",
6456
+ '[id^="bsap_"]',
6457
+ '[id^="bsa-zone_"]',
6458
+ 'img[src*="buysellads.com"]',
6459
+ 'img[src*="buysellads.net"]',
6460
+ // EthicalAds (ReadTheDocs, Python/Django docs)
6461
+ ".ethical-rtd",
6462
+ ".ethical-fixedfooter",
6463
+ ".ethical-bottom-right",
6464
+ "[data-ea-publisher]",
6465
+ ".keep-us-sustainable",
6466
+ 'img[src*="ethicalads.io"]',
6467
+ // Google AdSense
6468
+ ".adsbygoogle",
6469
+ "ins.adsbygoogle",
6470
+ '[id^="google_ads_iframe"]',
6471
+ 'img[src*="googlesyndication.com"]',
6472
+ 'img[src*="doubleclick.net"]',
6473
+ // Outbrain / Taboola — content-recommendation widgets, indistinguishable
6474
+ // from ads on doc pages.
6475
+ ".OUTBRAIN",
6476
+ '[data-widget-id^="OB_"]',
6477
+ ".taboola",
6478
+ '[id^="taboola-"]',
6479
+ // Tracker pixels that escape via async injection
6480
+ 'img[src*="bidr.io"]',
6481
+ 'img[src*="adnxs.com"]',
6482
+ 'img[src*="adsrvr.org"]',
6483
+ 'img[src*="analytics.yahoo.com"]',
6484
+ // Third-party search widgets injected outside of nav/header.
6485
+ // Algolia DocSearch (dominant in technical docs)
6486
+ ".DocSearch",
6487
+ ".DocSearch-Button",
6488
+ ".DocSearch-Container",
6489
+ ".DocSearch-Modal",
6490
+ "#docsearch",
6491
+ '[id^="docsearch-"]',
6492
+ ".algolia-autocomplete",
6493
+ ".algolia-docsearch-suggestion",
6494
+ // MkDocs Material result containers (the search box is in nav; results can
6495
+ // render standalone)
6496
+ ".md-search-result",
6497
+ ".md-search__output",
6498
+ // Sphinx / ReadTheDocs search
6499
+ "#searchbox",
6500
+ "#search-results",
6501
+ ".wy-side-search",
6502
+ // Swiftype / Elastic Site Search
6503
+ "#st-search-input",
6504
+ "#st-results-container",
6505
+ ".st-default-search-input"
6380
6506
  ];
6381
6507
  async process(context, next) {
6382
6508
  const $ = context.dom;
@@ -6474,11 +6600,15 @@ class HtmlToMarkdownMiddleware {
6474
6600
  if (match) language = match[1];
6475
6601
  }
6476
6602
  }
6477
- const brElements = Array.from(element.querySelectorAll("br"));
6478
- for (const br of brElements) {
6603
+ const clone = element.cloneNode(true);
6604
+ for (const br of Array.from(clone.querySelectorAll("br"))) {
6479
6605
  br.replaceWith("\n");
6480
6606
  }
6481
- const text = element.textContent || "";
6607
+ const lineNodes = clone.querySelectorAll("span.line, div.line, [data-line]");
6608
+ for (let i = 0; i < lineNodes.length - 1; i++) {
6609
+ lineNodes[i].appendChild(clone.ownerDocument.createTextNode("\n"));
6610
+ }
6611
+ const text = clone.textContent || "";
6482
6612
  return `
6483
6613
  \`\`\`${language}
6484
6614
  ${text.replace(/^\n+|\n+$/g, "")}
@@ -6622,11 +6752,13 @@ class HtmlPipeline extends BasePipeline {
6622
6752
  const maxChunkSize = config.splitter.maxChunkSize;
6623
6753
  const minChunkSize = config.splitter.minChunkSize;
6624
6754
  this.playwrightMiddleware = new HtmlPlaywrightMiddleware(config.scraper);
6755
+ const extractor = config.scraper.htmlExtractor === "defuddle" ? createLazyDefuddleMiddleware() : new HtmlSanitizerMiddleware();
6756
+ logger.debug(`HtmlPipeline using extractor: ${config.scraper.htmlExtractor}`);
6625
6757
  this.standardMiddleware = [
6626
6758
  new HtmlCheerioParserMiddleware(),
6627
6759
  new HtmlMetadataExtractorMiddleware(),
6628
6760
  new HtmlLinkExtractorMiddleware(),
6629
- new HtmlSanitizerMiddleware(),
6761
+ extractor,
6630
6762
  new HtmlNormalizationMiddleware(),
6631
6763
  new HtmlToMarkdownMiddleware()
6632
6764
  ];
@@ -6691,6 +6823,18 @@ class HtmlPipeline extends BasePipeline {
6691
6823
  }
6692
6824
  }
6693
6825
  }
6826
+ function createLazyDefuddleMiddleware() {
6827
+ let real = null;
6828
+ return {
6829
+ async process(context, next) {
6830
+ if (!real) {
6831
+ const mod = await import("./HtmlDefuddleMiddleware-DjhdN_D2.js");
6832
+ real = new mod.HtmlDefuddleMiddleware();
6833
+ }
6834
+ await real.process(context, next);
6835
+ }
6836
+ };
6837
+ }
6694
6838
  class TextDocumentSplitter {
6695
6839
  config;
6696
6840
  textSplitter;
@@ -7051,9 +7195,12 @@ class JsonPipeline extends BasePipeline {
7051
7195
  return currentDepth;
7052
7196
  }
7053
7197
  }
7198
+ const inlineLinkPattern = /(^|[^!\\])\[[^\]\n]+\]\(([^)\s]+)(?:\s+"[^"]*"|\s+'[^']*'|\s+\([^)]*\))?\)/g;
7199
+ const referenceLinkPattern = /(^|[^!\\])\[[^\]\n]+\]\[([^\]\n]+)\]/g;
7200
+ const referenceDefinitionPattern = /^\s{0,3}\[([^\]\n]+)\]:\s*(\S+)(?:\s+.*)?$/gm;
7054
7201
  class MarkdownLinkExtractorMiddleware {
7055
7202
  /**
7056
- * Processes the context. Currently a no-op regarding link extraction.
7203
+ * Processes the context and appends Markdown link targets to context.links.
7057
7204
  * @param context The current processing context.
7058
7205
  * @param next Function to call the next middleware.
7059
7206
  */
@@ -7061,9 +7208,50 @@ class MarkdownLinkExtractorMiddleware {
7061
7208
  if (!Array.isArray(context.links)) {
7062
7209
  context.links = [];
7063
7210
  }
7211
+ for (const link of extractMarkdownLinks(context.content)) {
7212
+ if (!context.links.includes(link)) {
7213
+ context.links.push(link);
7214
+ }
7215
+ }
7064
7216
  await next();
7065
7217
  }
7066
7218
  }
7219
+ function extractMarkdownLinks(content) {
7220
+ const links = [];
7221
+ const referenceDefinitions = /* @__PURE__ */ new Map();
7222
+ for (const match of content.matchAll(referenceDefinitionPattern)) {
7223
+ const label = normalizeReferenceLabel(match[1]);
7224
+ const target = cleanReferenceTarget(match[2]);
7225
+ if (label && target && !referenceDefinitions.has(label)) {
7226
+ referenceDefinitions.set(label, target);
7227
+ }
7228
+ }
7229
+ for (const match of content.matchAll(inlineLinkPattern)) {
7230
+ addUniqueLink(links, match[2]);
7231
+ }
7232
+ for (const match of content.matchAll(referenceLinkPattern)) {
7233
+ const target = referenceDefinitions.get(normalizeReferenceLabel(match[2]));
7234
+ if (target) {
7235
+ addUniqueLink(links, target);
7236
+ }
7237
+ }
7238
+ return links;
7239
+ }
7240
+ function addUniqueLink(links, target) {
7241
+ if (!target || links.includes(target)) {
7242
+ return;
7243
+ }
7244
+ links.push(target);
7245
+ }
7246
+ function normalizeReferenceLabel(label) {
7247
+ return label?.trim().replace(/\s+/g, " ").toLowerCase() ?? "";
7248
+ }
7249
+ function cleanReferenceTarget(target) {
7250
+ if (!target) {
7251
+ return "";
7252
+ }
7253
+ return target.trim().replace(/^<(.+)>$/, "$1");
7254
+ }
7067
7255
  class MarkdownMetadataExtractorMiddleware {
7068
7256
  /**
7069
7257
  * Processes the context to extract the title from Markdown.
@@ -10774,9 +10962,10 @@ class DocumentStore {
10774
10962
  *
10775
10963
  * @param texts Array of texts to embed
10776
10964
  * @param isRetry Internal flag to prevent duplicate warning logs
10965
+ * @param hasTruncatedSingleText Whether a single text has already been truncated once
10777
10966
  * @returns Array of embedding vectors
10778
10967
  */
10779
- async embedDocumentsWithRetry(texts, isRetry = false) {
10968
+ async embedDocumentsWithRetry(texts, isRetry = false, hasTruncatedSingleText = false) {
10780
10969
  if (texts.length === 0) {
10781
10970
  return [];
10782
10971
  }
@@ -10794,11 +10983,14 @@ class DocumentStore {
10794
10983
  );
10795
10984
  }
10796
10985
  const [firstEmbeddings, secondEmbeddings] = await Promise.all([
10797
- this.embedDocumentsWithRetry(firstHalf, true),
10798
- this.embedDocumentsWithRetry(secondHalf, true)
10986
+ this.embedDocumentsWithRetry(firstHalf, true, false),
10987
+ this.embedDocumentsWithRetry(secondHalf, true, false)
10799
10988
  ]);
10800
10989
  return [...firstEmbeddings, ...secondEmbeddings];
10801
10990
  } else {
10991
+ if (hasTruncatedSingleText) {
10992
+ throw error;
10993
+ }
10802
10994
  const text = texts[0];
10803
10995
  const midpoint = Math.floor(text.length / 2);
10804
10996
  const firstHalf = text.substring(0, midpoint);
@@ -10808,7 +11000,7 @@ class DocumentStore {
10808
11000
  );
10809
11001
  }
10810
11002
  try {
10811
- const embedding = await this.embedDocumentsWithRetry([firstHalf], true);
11003
+ const embedding = await this.embedDocumentsWithRetry([firstHalf], true, true);
10812
11004
  return embedding;
10813
11005
  } catch (retryError) {
10814
11006
  logger.error(
@@ -12620,7 +12812,7 @@ const Layout = ({
12620
12812
  children,
12621
12813
  eventClientConfig
12622
12814
  }) => {
12623
- const versionString = version || "2.3.0";
12815
+ const versionString = version || "2.4.0";
12624
12816
  const versionInitializer = `versionUpdate({ currentVersion: ${`'${versionString}'`} })`;
12625
12817
  return /* @__PURE__ */ jsxs("html", { lang: "en", children: [
12626
12818
  /* @__PURE__ */ jsxs("head", { children: [
@@ -14906,7 +15098,7 @@ class AppServer {
14906
15098
  try {
14907
15099
  if (telemetry.isEnabled()) {
14908
15100
  telemetry.setGlobalContext({
14909
- appVersion: "2.3.0",
15101
+ appVersion: "2.4.0",
14910
15102
  appPlatform: process.platform,
14911
15103
  appNodeVersion: process.version,
14912
15104
  appServicesEnabled: this.getActiveServicesList(),
@@ -15429,6 +15621,94 @@ class PipelineClient {
15429
15621
  logger.debug("PipelineClient.setCallbacks called - no-op for external worker");
15430
15622
  }
15431
15623
  }
15624
+ const emptyLlmsTxtResult = () => ({
15625
+ sections: [],
15626
+ links: []
15627
+ });
15628
+ const markdownLinkPattern = /^\s*[-*+]\s+\[([^\]\n]+)]\(([^)\s]+)\)\s*(?::\s*(.+?)\s*)?$/;
15629
+ function isLlmsTxtUrl(url) {
15630
+ try {
15631
+ const basename = new URL(url).pathname.split("/").filter(Boolean).at(-1);
15632
+ return basename?.toLowerCase() === "llms.txt";
15633
+ } catch {
15634
+ return false;
15635
+ }
15636
+ }
15637
+ function parseLlmsTxt(content) {
15638
+ if (!content.trim() || content.includes("\0")) {
15639
+ return emptyLlmsTxtResult();
15640
+ }
15641
+ if (/^\s*<(?:!doctype\s+html|html|body|head)(?:\s|>)/i.test(content)) {
15642
+ return emptyLlmsTxtResult();
15643
+ }
15644
+ const lines = content.split(/\r?\n/);
15645
+ const firstH1Index = lines.findIndex((line) => /^#\s+\S/.test(line));
15646
+ if (firstH1Index === -1) {
15647
+ return emptyLlmsTxtResult();
15648
+ }
15649
+ const projectName = lines[firstH1Index].replace(/^#\s+/, "").trim();
15650
+ if (!projectName) {
15651
+ return emptyLlmsTxtResult();
15652
+ }
15653
+ const result = {
15654
+ projectName,
15655
+ sections: [],
15656
+ links: []
15657
+ };
15658
+ let currentSection;
15659
+ const summaryLines = [];
15660
+ let collectingSummary = true;
15661
+ for (const line of lines.slice(firstH1Index + 1)) {
15662
+ if (/^#\s+\S/.test(line)) {
15663
+ collectingSummary = false;
15664
+ continue;
15665
+ }
15666
+ const h2Match = /^##\s+(.+?)\s*$/.exec(line);
15667
+ if (h2Match) {
15668
+ collectingSummary = false;
15669
+ const title = h2Match[1].trim();
15670
+ currentSection = {
15671
+ title,
15672
+ optional: title.toLowerCase() === "optional",
15673
+ links: []
15674
+ };
15675
+ result.sections.push(currentSection);
15676
+ continue;
15677
+ }
15678
+ if (collectingSummary) {
15679
+ if (/^>\s?/.test(line)) {
15680
+ summaryLines.push(line.replace(/^>\s?/, "").trim());
15681
+ continue;
15682
+ }
15683
+ if (summaryLines.length > 0 && line.trim() === "") {
15684
+ continue;
15685
+ }
15686
+ if (line.trim() !== "") {
15687
+ collectingSummary = false;
15688
+ }
15689
+ }
15690
+ const linkMatch = markdownLinkPattern.exec(line);
15691
+ if (!linkMatch) {
15692
+ continue;
15693
+ }
15694
+ const link = {
15695
+ title: linkMatch[1].trim(),
15696
+ url: linkMatch[2].trim(),
15697
+ optional: currentSection?.optional ?? false,
15698
+ ...currentSection ? { section: currentSection.title } : {},
15699
+ ...linkMatch[3]?.trim() ? { description: linkMatch[3].trim() } : {}
15700
+ };
15701
+ currentSection?.links.push(link);
15702
+ result.links.push(link);
15703
+ }
15704
+ if (summaryLines.length > 0) {
15705
+ result.summary = summaryLines.join("\n");
15706
+ }
15707
+ if (result.links.length === 0) {
15708
+ return emptyLlmsTxtResult();
15709
+ }
15710
+ return result;
15711
+ }
15432
15712
  const INDEX_FILE_PATTERN = /^index(\.[a-z0-9]+)?$/i;
15433
15713
  function computeBaseDirectory(pathname) {
15434
15714
  if (pathname === "" || pathname === "/") return "/";
@@ -15530,6 +15810,9 @@ class BaseScraperStrategy {
15530
15810
  * crawl queue entirely.
15531
15811
  */
15532
15812
  shouldProcessUrl(url, options, context = {}) {
15813
+ if (isLlmsTxtUrl(url)) {
15814
+ return false;
15815
+ }
15533
15816
  const isInternalArchiveMember = url.startsWith("file://") && isFileUrlInsideRoots(url, context.internalAllowedFileRoots);
15534
15817
  if (!isInternalArchiveMember) {
15535
15818
  const scope = options.scope ?? "subpages";
@@ -15631,11 +15914,17 @@ class BaseScraperStrategy {
15631
15914
  this.recordChildPageCompletion(item, result);
15632
15915
  ensureFailureRateWithinThreshold();
15633
15916
  throwIfBatchAborted();
15634
- return [];
15917
+ return result.queueItems ?? [];
15635
15918
  }
15636
15919
  if (result.status === FetchStatus.NOT_FOUND) {
15637
15920
  const isRefreshDeletion = this.isRefreshDeletion(item, result);
15638
- if (item.depth === 0 && !isRefreshDeletion) {
15921
+ const fallbackQueueItems = result.queueItems ?? [];
15922
+ const hasNewFallbackQueueItem = fallbackQueueItems.some(
15923
+ (queueItem) => !this.visited.has(
15924
+ normalizeUrl(queueItem.url, this.getUrlNormalizerOptions(options))
15925
+ )
15926
+ );
15927
+ if (item.depth === 0 && !isRefreshDeletion && !hasNewFallbackQueueItem) {
15639
15928
  throw new ScraperError(`Root page not found: ${item.url}`, false);
15640
15929
  }
15641
15930
  if (!isRefreshDeletion) {
@@ -15660,7 +15949,7 @@ class BaseScraperStrategy {
15660
15949
  }
15661
15950
  await progressCallback(progress);
15662
15951
  }
15663
- return [];
15952
+ return fallbackQueueItems;
15664
15953
  }
15665
15954
  if (result.status !== FetchStatus.SUCCESS) {
15666
15955
  logger.error(`❌ Unknown fetch status: ${result.status}`);
@@ -15697,7 +15986,7 @@ class BaseScraperStrategy {
15697
15986
  this.recordChildPageCompletion(item, result);
15698
15987
  ensureFailureRateWithinThreshold();
15699
15988
  throwIfBatchAborted();
15700
- return nextItems.map((value) => {
15989
+ const linkQueueItems = nextItems.map((value) => {
15701
15990
  try {
15702
15991
  const targetUrl = new URL$1(value, linkBaseUrl);
15703
15992
  if (!this.shouldProcessUrl(targetUrl.href, options, {
@@ -15715,6 +16004,7 @@ class BaseScraperStrategy {
15715
16004
  }
15716
16005
  return null;
15717
16006
  }).filter((item2) => item2 !== null);
16007
+ return [...result.queueItems ?? [], ...linkQueueItems];
15718
16008
  } catch (error) {
15719
16009
  if (error instanceof FailureThresholdExceededError || error instanceof CancellationError) {
15720
16010
  throw error;
@@ -17053,6 +17343,7 @@ class WebScraperStrategy extends BaseScraperStrategy {
17053
17343
  localFileStrategy;
17054
17344
  tempFiles = [];
17055
17345
  siblingwiseRedirectWarned = false;
17346
+ pendingLlmsTxtProbe = null;
17056
17347
  constructor(config, options = {}) {
17057
17348
  super(config, { urlNormalizerOptions: options.urlNormalizerOptions });
17058
17349
  this.shouldFollowLinkFn = options.shouldFollowLink;
@@ -17086,6 +17377,152 @@ class WebScraperStrategy extends BaseScraperStrategy {
17086
17377
  return actualUrl;
17087
17378
  }
17088
17379
  // Removed custom isInScope logic; using shared scope utility for consistent behavior
17380
+ createFetchOptions(item, options, signal) {
17381
+ return {
17382
+ signal,
17383
+ followRedirects: options.followRedirects,
17384
+ headers: options.headers,
17385
+ etag: item.etag,
17386
+ ...item.internalAllowedFileRoots ? { internalAllowedFileRoots: item.internalAllowedFileRoots } : {}
17387
+ };
17388
+ }
17389
+ buildMarkdownVariantUrl(url) {
17390
+ const variant = new URL(url);
17391
+ if (variant.pathname.endsWith("/")) {
17392
+ variant.pathname = `${variant.pathname}index.html.md`;
17393
+ return variant.toString();
17394
+ }
17395
+ const lastSegment = variant.pathname.split("/").at(-1) ?? "";
17396
+ if (lastSegment.includes(".")) {
17397
+ variant.pathname = `${variant.pathname}.md`;
17398
+ return variant.toString();
17399
+ }
17400
+ variant.pathname = `${variant.pathname}/index.html.md`;
17401
+ return variant.toString();
17402
+ }
17403
+ isAcceptableMarkdownVariant(rawContent) {
17404
+ const mimeType = rawContent.mimeType.toLowerCase();
17405
+ return MimeTypeUtils.isMarkdown(mimeType) || mimeType === "text/plain";
17406
+ }
17407
+ isMarkdownUrl(url) {
17408
+ const mimeType = MimeTypeUtils.detectMimeTypeFromPath(url);
17409
+ return mimeType ? MimeTypeUtils.isMarkdown(mimeType) : false;
17410
+ }
17411
+ async fetchItemContent(item, options, signal) {
17412
+ const fetchOptions = this.createFetchOptions(item, options, signal);
17413
+ if (!item.fromLlmsTxt || this.isMarkdownUrl(item.url)) {
17414
+ return this.fetcher.fetch(item.url, fetchOptions);
17415
+ }
17416
+ const markdownVariantUrl = this.buildMarkdownVariantUrl(item.url);
17417
+ try {
17418
+ const markdownContent = await this.fetcher.fetch(markdownVariantUrl, fetchOptions);
17419
+ if (markdownContent.status === FetchStatus.SUCCESS && this.isAcceptableMarkdownVariant(markdownContent)) {
17420
+ logger.debug(
17421
+ `llms.txt Markdown URL preference succeeded: ${item.url} -> ${markdownVariantUrl}`
17422
+ );
17423
+ return MimeTypeUtils.isMarkdown(markdownContent.mimeType) ? markdownContent : { ...markdownContent, mimeType: "text/markdown" };
17424
+ }
17425
+ logger.debug(
17426
+ `llms.txt Markdown URL preference fell back for ${item.url}: ${markdownVariantUrl} returned status=${markdownContent.status}, contentType=${markdownContent.mimeType}`
17427
+ );
17428
+ } catch (error) {
17429
+ logger.debug(
17430
+ `llms.txt Markdown URL preference fell back for ${item.url}: ${error}`
17431
+ );
17432
+ }
17433
+ return this.fetcher.fetch(item.url, fetchOptions);
17434
+ }
17435
+ getLlmsTxtCandidates(baseUrl, inputUrl) {
17436
+ const input = new URL(inputUrl);
17437
+ const parentPath = input.pathname.endsWith("/") ? input.pathname : input.pathname.slice(0, input.pathname.lastIndexOf("/") + 1);
17438
+ input.pathname = `${parentPath}llms.txt`.replace(/\/+/g, "/");
17439
+ input.search = "";
17440
+ input.hash = "";
17441
+ const root = new URL(baseUrl);
17442
+ root.pathname = "/llms.txt";
17443
+ root.search = "";
17444
+ root.hash = "";
17445
+ return [.../* @__PURE__ */ new Set([input.toString(), root.toString()])];
17446
+ }
17447
+ /**
17448
+ * Probes for an llms.txt file using the existing fetcher and access policy.
17449
+ * @param baseUrl The site base URL used for the root fallback probe.
17450
+ * @param inputUrl The original input URL used for the subpath probe.
17451
+ * @param options Scraper options to apply to probe requests.
17452
+ * @param signal Optional abort signal.
17453
+ * @returns The first valid llms.txt result, or null when none is available.
17454
+ */
17455
+ async probeLlmsTxt(baseUrl, inputUrl, options, signal) {
17456
+ for (const candidate of this.getLlmsTxtCandidates(baseUrl, inputUrl)) {
17457
+ try {
17458
+ const rawContent = await this.fetcher.fetch(
17459
+ candidate,
17460
+ this.createFetchOptions({ url: candidate, depth: 0 }, options, signal)
17461
+ );
17462
+ if (rawContent.status !== FetchStatus.SUCCESS) {
17463
+ logger.debug(`llms.txt probe failed for ${candidate}: ${rawContent.status}`);
17464
+ continue;
17465
+ }
17466
+ const result = parseLlmsTxt(
17467
+ convertToString(rawContent.content, rawContent.charset)
17468
+ );
17469
+ if (result.links.length === 0) {
17470
+ logger.debug(`llms.txt probe failed for ${candidate}: invalid content`);
17471
+ continue;
17472
+ }
17473
+ logger.info(
17474
+ `📄 Detected llms.txt at ${rawContent.source} (${result.links.length} URLs)`
17475
+ );
17476
+ return { url: rawContent.source, result };
17477
+ } catch (error) {
17478
+ logger.debug(`llms.txt probe failed for ${candidate}: ${error}`);
17479
+ }
17480
+ }
17481
+ return null;
17482
+ }
17483
+ createLlmsTxtQueueItems(options, probe) {
17484
+ const items = [];
17485
+ for (const link of probe.result.links) {
17486
+ try {
17487
+ const targetUrl = new URL(link.url, probe.url);
17488
+ if (targetUrl.protocol !== "http:" && targetUrl.protocol !== "https:") {
17489
+ continue;
17490
+ }
17491
+ if (!this.shouldProcessUrl(targetUrl.href, options)) {
17492
+ continue;
17493
+ }
17494
+ if (this.shouldFollowLinkFn) {
17495
+ const baseUrl = this.canonicalBaseUrl ?? new URL(options.url);
17496
+ if (!this.shouldFollowLinkFn(baseUrl, targetUrl)) {
17497
+ continue;
17498
+ }
17499
+ }
17500
+ items.push({ url: targetUrl.href, depth: 0, fromLlmsTxt: true });
17501
+ } catch {
17502
+ }
17503
+ }
17504
+ return items;
17505
+ }
17506
+ consumePendingLlmsTxtQueueItems(item, options) {
17507
+ if (item.depth !== 0) {
17508
+ return [];
17509
+ }
17510
+ const probe = this.pendingLlmsTxtProbe;
17511
+ this.pendingLlmsTxtProbe = null;
17512
+ return probe ? this.createLlmsTxtQueueItems(options, probe) : [];
17513
+ }
17514
+ updateCanonicalBaseUrl(effectiveSource, options) {
17515
+ const final = new URL(effectiveSource);
17516
+ const userPath = new URL(options.url).pathname;
17517
+ if (!isPathDescendant(userPath, final.pathname) && !this.siblingwiseRedirectWarned) {
17518
+ logger.warn(
17519
+ `⚠️ Depth-0 redirect changed path siblingwise. Scope anchor remains the user-provided path; discovered links under the redirected path will not be in scope. Requested: ${options.url} → Final: ${effectiveSource} → Scope anchor: ${userPath}. If the redirected path is intended, resubmit with that URL.`
17520
+ );
17521
+ this.siblingwiseRedirectWarned = true;
17522
+ }
17523
+ final.pathname = userPath;
17524
+ this.canonicalBaseUrl = final;
17525
+ }
17089
17526
  /**
17090
17527
  * Processes a single queue item by fetching its content and processing it through pipelines.
17091
17528
  * @param item - The queue item to process.
@@ -17097,6 +17534,10 @@ class WebScraperStrategy extends BaseScraperStrategy {
17097
17534
  async processItem(item, options, signal) {
17098
17535
  const { url } = item;
17099
17536
  try {
17537
+ if (isLlmsTxtUrl(url)) {
17538
+ logger.debug(`Skipping llms.txt meta-file: ${url}`);
17539
+ return { url, links: [], status: FetchStatus.SUCCESS };
17540
+ }
17100
17541
  if (item.etag) {
17101
17542
  logger.debug(`Processing ${url} with stored ETag: ${item.etag}`);
17102
17543
  }
@@ -17106,23 +17547,28 @@ class WebScraperStrategy extends BaseScraperStrategy {
17106
17547
  return this.processRootArchive(item, options, signal);
17107
17548
  }
17108
17549
  }
17109
- const fetchOptions = {
17110
- signal,
17111
- followRedirects: options.followRedirects,
17112
- headers: options.headers,
17113
- // Forward custom headers
17114
- etag: item.etag,
17115
- // Pass ETag for conditional requests
17116
- ...item.internalAllowedFileRoots ? { internalAllowedFileRoots: item.internalAllowedFileRoots } : {}
17117
- };
17118
- const rawContent = await this.fetcher.fetch(url, fetchOptions);
17550
+ const rawContent = await this.fetchItemContent(item, options, signal);
17119
17551
  const effectiveSource = options.preserveHashes ? this.restorePreservedHash(url, rawContent.source) : rawContent.source;
17552
+ if (item.depth === 0) {
17553
+ this.updateCanonicalBaseUrl(effectiveSource, options);
17554
+ }
17555
+ const llmsTxtQueueItems = this.consumePendingLlmsTxtQueueItems(item, options);
17120
17556
  logger.debug(
17121
17557
  `Fetch result for ${url}: status=${rawContent.status}, etag=${rawContent.etag || "none"}`
17122
17558
  );
17123
17559
  if (rawContent.status !== FetchStatus.SUCCESS) {
17124
17560
  logger.debug(`Skipping pipeline for ${url} due to status: ${rawContent.status}`);
17125
- return { url: effectiveSource, links: [], status: rawContent.status };
17561
+ return {
17562
+ url: effectiveSource,
17563
+ links: [],
17564
+ queueItems: llmsTxtQueueItems,
17565
+ status: rawContent.status
17566
+ };
17567
+ }
17568
+ if (MimeTypeUtils.isMarkdown(rawContent.mimeType)) {
17569
+ logger.debug(
17570
+ `Server provided Markdown content for ${url} via content negotiation or Markdown URL (${rawContent.mimeType})`
17571
+ );
17126
17572
  }
17127
17573
  let processed;
17128
17574
  for (const pipeline of this.pipelines) {
@@ -17143,53 +17589,43 @@ class WebScraperStrategy extends BaseScraperStrategy {
17143
17589
  logger.warn(
17144
17590
  `⚠️ Unsupported content type "${rawContent.mimeType}" for URL ${url}. Skipping processing.`
17145
17591
  );
17146
- return { url: effectiveSource, links: [], status: FetchStatus.SUCCESS };
17592
+ return {
17593
+ url: effectiveSource,
17594
+ links: [],
17595
+ queueItems: llmsTxtQueueItems,
17596
+ status: FetchStatus.SUCCESS
17597
+ };
17147
17598
  }
17148
17599
  for (const err of processed.errors ?? []) {
17149
17600
  logger.warn(`⚠️ Processing error for ${url}: ${err.message}`);
17150
17601
  }
17151
- if (!processed.textContent || !processed.textContent.trim()) {
17602
+ if (!processed.textContent?.trim()) {
17152
17603
  logger.warn(
17153
17604
  `⚠️ No processable content found for ${url} after pipeline execution.`
17154
17605
  );
17155
17606
  return {
17156
17607
  url: effectiveSource,
17157
17608
  links: processed.links,
17609
+ queueItems: llmsTxtQueueItems,
17158
17610
  status: FetchStatus.SUCCESS
17159
17611
  };
17160
17612
  }
17161
- if (item.depth === 0) {
17162
- const final = new URL(effectiveSource);
17163
- const userPath = new URL(options.url).pathname;
17164
- if (isPathDescendant(userPath, final.pathname)) {
17165
- this.canonicalBaseUrl = final;
17166
- } else {
17167
- if (!this.siblingwiseRedirectWarned) {
17168
- logger.warn(
17169
- `⚠️ Depth-0 redirect changed path siblingwise. Scope anchor remains the user-provided path; discovered links under the redirected path will not be in scope. Requested: ${options.url} → Final: ${effectiveSource} → Scope anchor: ${userPath}. If the redirected path is intended, resubmit with that URL.`
17170
- );
17171
- this.siblingwiseRedirectWarned = true;
17172
- }
17173
- final.pathname = userPath;
17174
- this.canonicalBaseUrl = final;
17175
- }
17176
- }
17177
- const filteredLinks = processed.links?.filter((link) => {
17613
+ const filteredLinks = processed.links?.flatMap((link) => {
17178
17614
  try {
17179
- const targetUrl = new URL(link);
17615
+ const targetUrl = new URL(link, effectiveSource);
17180
17616
  if (/\.(zip|tar|gz|tgz)$/i.test(targetUrl.pathname)) {
17181
- return false;
17617
+ return [];
17182
17618
  }
17183
17619
  if (!this.shouldProcessUrl(targetUrl.href, options)) {
17184
- return false;
17620
+ return [];
17185
17621
  }
17186
17622
  if (this.shouldFollowLinkFn) {
17187
17623
  const baseUrl = this.canonicalBaseUrl ?? new URL(options.url);
17188
- return this.shouldFollowLinkFn(baseUrl, targetUrl);
17624
+ return this.shouldFollowLinkFn(baseUrl, targetUrl) ? [targetUrl.href] : [];
17189
17625
  }
17190
- return true;
17626
+ return [targetUrl.href];
17191
17627
  } catch {
17192
- return false;
17628
+ return [];
17193
17629
  }
17194
17630
  }) ?? [];
17195
17631
  return {
@@ -17200,6 +17636,7 @@ class WebScraperStrategy extends BaseScraperStrategy {
17200
17636
  contentType: processed.contentType || rawContent.mimeType,
17201
17637
  content: processed,
17202
17638
  links: filteredLinks,
17639
+ queueItems: llmsTxtQueueItems,
17203
17640
  status: FetchStatus.SUCCESS
17204
17641
  };
17205
17642
  } catch (error) {
@@ -17207,6 +17644,16 @@ class WebScraperStrategy extends BaseScraperStrategy {
17207
17644
  throw error;
17208
17645
  }
17209
17646
  }
17647
+ async scrape(options, progressCallback, signal) {
17648
+ this.pendingLlmsTxtProbe = null;
17649
+ this.pendingLlmsTxtProbe = await this.probeLlmsTxt(
17650
+ options.url,
17651
+ options.url,
17652
+ options,
17653
+ signal
17654
+ );
17655
+ await super.scrape(options, progressCallback, signal);
17656
+ }
17210
17657
  async processRootArchive(item, options, signal) {
17211
17658
  logger.info(`📦 Downloading root archive: ${item.url}`);
17212
17659
  const rawContent = await this.fetcher.fetch(item.url, {
@@ -19276,7 +19723,7 @@ function createCli(argv) {
19276
19723
  let globalEventBus = null;
19277
19724
  let globalTelemetryService = null;
19278
19725
  const commandStartTimes = /* @__PURE__ */ new Map();
19279
- const cli = registerGlobalOutputOptions(yargs(hideBin(argv))).scriptName("docs-mcp-server").strict().usage("Usage: $0 <command> [options]").version("2.3.0").option("verbose", {
19726
+ const cli = registerGlobalOutputOptions(yargs(hideBin(argv))).scriptName("docs-mcp-server").strict().usage("Usage: $0 <command> [options]").version("2.4.0").option("verbose", {
19280
19727
  type: "boolean",
19281
19728
  description: "Enable verbose (debug) logging",
19282
19729
  default: false
@@ -19337,7 +19784,7 @@ function createCli(argv) {
19337
19784
  if (shouldEnableTelemetry() && telemetry.isEnabled()) {
19338
19785
  const commandName = argv2._[0]?.toString() || "default";
19339
19786
  telemetry.setGlobalContext({
19340
- appVersion: "2.3.0",
19787
+ appVersion: "2.4.0",
19341
19788
  appPlatform: process.platform,
19342
19789
  appNodeVersion: process.version,
19343
19790
  appInterface: "cli",
@@ -19483,4 +19930,4 @@ export {
19483
19930
  cleanupCliCommand,
19484
19931
  runCli
19485
19932
  };
19486
- //# sourceMappingURL=main-CCLTqj8g.js.map
19933
+ //# sourceMappingURL=main-BoUugvTO.js.map