@arabold/docs-mcp-server 2.3.0 → 2.4.2

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.
@@ -9,7 +9,7 @@ import path from "node:path";
9
9
  import { URL as URL$1 } from "node:url";
10
10
  import envPaths from "env-paths";
11
11
  import { l as logger, n as normalizeEnvValue, g as getLogLevelFromEnv, a as setLogLevel, L as LogLevel } from "./logger-CLtABTNb.js";
12
- import { t as telemetry, T as TelemetryEvent, P as PipelineJobStatus, f as getProjectRoot, E as EmbeddingConfig, b as EventType, S as ServerEventName, s as shouldEnableTelemetry, r as resolveProtocol, p as parseAuthConfig, v as validateAuthConfig, w as warnHttpUsage, e as ensurePlaywrightBrowsersInstalled, g as getEventBus, h as handleEmbeddingModelChange, d as createAppServerConfig, j as parseHeaders, m as validatePort, l as validateHost, k as resolveStorePath, i as initTelemetry, a as EventBusService, c as TelemetryService } from "./utils-CUTutkx-.js";
12
+ import { t as telemetry, T as TelemetryEvent, P as PipelineJobStatus, f as getProjectRoot, E as EmbeddingConfig, b as EventType, S as ServerEventName, s as shouldEnableTelemetry, r as resolveProtocol, p as parseAuthConfig, v as validateAuthConfig, w as warnHttpUsage, e as ensurePlaywrightBrowsersInstalled, g as getEventBus, h as handleEmbeddingModelChange, d as createAppServerConfig, j as parseHeaders, m as validatePort, l as validateHost, k as resolveStorePath, i as initTelemetry, a as EventBusService, c as TelemetryService } from "./utils-CJgh41os.js";
13
13
  import yargs from "yargs";
14
14
  import { hideBin } from "yargs/helpers";
15
15
  import yaml from "yaml";
@@ -356,6 +356,62 @@ function createEmbeddingModel(providerAndModel, runtime) {
356
356
  throw new UnsupportedProviderError(provider);
357
357
  }
358
358
  }
359
+ function normalizePublicOrigin(origin) {
360
+ const trimmed = origin?.trim();
361
+ if (!trimmed) {
362
+ return void 0;
363
+ }
364
+ let parsed;
365
+ try {
366
+ parsed = new URL(trimmed);
367
+ } catch {
368
+ throw new Error(
369
+ "server.publicOrigin must be an absolute HTTP(S) origin without path, query, or fragment."
370
+ );
371
+ }
372
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
373
+ throw new Error("server.publicOrigin must use the http or https protocol.");
374
+ }
375
+ if (parsed.username || parsed.password) {
376
+ throw new Error("server.publicOrigin must not include credentials.");
377
+ }
378
+ if (parsed.pathname !== "/" || parsed.search || parsed.hash) {
379
+ throw new Error(
380
+ "server.publicOrigin must not include a path, query string, or fragment."
381
+ );
382
+ }
383
+ return parsed.origin;
384
+ }
385
+ function buildBindOrigin(host, port) {
386
+ const formattedHost = formatHostForUrl(host);
387
+ return new URL(`http://${formattedHost}:${port}`).origin;
388
+ }
389
+ function getCanonicalServerOrigin(config, port) {
390
+ return normalizePublicOrigin(config.server.publicOrigin) ?? buildBindOrigin(config.server.host, port);
391
+ }
392
+ function isWildcardBindHost(host) {
393
+ const normalized = stripIpv6Brackets(host.trim().toLowerCase());
394
+ return normalized === "0.0.0.0" || normalized === "::" || normalized === "::0" || normalized === "0:0:0:0:0:0:0:0" || normalized === "0000:0000:0000:0000:0000:0000:0000:0000";
395
+ }
396
+ function formatHostForUrl(host) {
397
+ const trimmed = host.trim();
398
+ const unbracketed = stripIpv6Brackets(trimmed);
399
+ if (unbracketed.includes(":")) {
400
+ return `[${unbracketed}]`;
401
+ }
402
+ return trimmed;
403
+ }
404
+ function stripIpv6Brackets(host) {
405
+ return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
406
+ }
407
+ const managedConfigVectorDimensionOmissionMarker = "docs-mcp-server-managed-vector-dimension-omitted";
408
+ const managedConfigHeader = [
409
+ `# ${managedConfigVectorDimensionOmissionMarker}`,
410
+ "# embeddings.vectorDimension is omitted when it comes from generated defaults.",
411
+ "# Add embeddings.vectorDimension explicitly to override native model dimensions.",
412
+ ""
413
+ ].join("\n");
414
+ const vectorDimensionPath = ["embeddings", "vectorDimension"];
359
415
  const envStringArray = z.union([z.array(z.string()), z.string()]).transform((value) => {
360
416
  if (Array.isArray(value)) {
361
417
  return value;
@@ -371,6 +427,23 @@ const envBoolean = z.union([z.boolean(), z.string()]).transform((val) => {
371
427
  const lower = val.toLowerCase().trim();
372
428
  return lower !== "false" && lower !== "0" && lower !== "no" && lower !== "off" && lower !== "";
373
429
  }).pipe(z.boolean());
430
+ const publicOriginSchema = z.preprocess((value) => {
431
+ if (typeof value !== "string") {
432
+ return value;
433
+ }
434
+ const trimmed = value.trim();
435
+ return trimmed.length > 0 ? trimmed : void 0;
436
+ }, z.string().optional()).transform((value, ctx) => {
437
+ try {
438
+ return normalizePublicOrigin(value);
439
+ } catch (error) {
440
+ ctx.addIssue({
441
+ code: z.ZodIssueCode.custom,
442
+ message: error instanceof Error ? error.message : String(error)
443
+ });
444
+ return z.NEVER;
445
+ }
446
+ });
374
447
  const DEFAULT_CONFIG = {
375
448
  app: {
376
449
  storePath: "",
@@ -381,6 +454,7 @@ const DEFAULT_CONFIG = {
381
454
  server: {
382
455
  protocol: "auto",
383
456
  host: "127.0.0.1",
457
+ publicOrigin: void 0,
384
458
  ports: {
385
459
  default: 6280,
386
460
  worker: 8080,
@@ -403,6 +477,7 @@ const DEFAULT_CONFIG = {
403
477
  skipKnownTrackers: true,
404
478
  pageTimeoutMs: 5e3,
405
479
  browserTimeoutMs: 3e4,
480
+ htmlExtractor: "cheerio",
406
481
  fetcher: {
407
482
  maxRetries: 3,
408
483
  baseDelayMs: 1e3,
@@ -477,6 +552,7 @@ const AppConfigSchema = z.object({
477
552
  server: z.object({
478
553
  protocol: z.string().default(DEFAULT_CONFIG.server.protocol),
479
554
  host: z.string().default(DEFAULT_CONFIG.server.host),
555
+ publicOrigin: publicOriginSchema.optional(),
480
556
  ports: z.object({
481
557
  default: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.default),
482
558
  worker: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.worker),
@@ -484,7 +560,12 @@ const AppConfigSchema = z.object({
484
560
  web: z.coerce.number().int().default(DEFAULT_CONFIG.server.ports.web)
485
561
  }).default(DEFAULT_CONFIG.server.ports),
486
562
  heartbeatMs: z.coerce.number().int().default(DEFAULT_CONFIG.server.heartbeatMs)
487
- }).default(DEFAULT_CONFIG.server),
563
+ }).default({
564
+ protocol: DEFAULT_CONFIG.server.protocol,
565
+ host: DEFAULT_CONFIG.server.host,
566
+ ports: DEFAULT_CONFIG.server.ports,
567
+ heartbeatMs: DEFAULT_CONFIG.server.heartbeatMs
568
+ }),
488
569
  auth: z.object({
489
570
  enabled: envBoolean.default(DEFAULT_CONFIG.auth.enabled),
490
571
  issuerUrl: z.string().default(DEFAULT_CONFIG.auth.issuerUrl),
@@ -499,6 +580,7 @@ const AppConfigSchema = z.object({
499
580
  skipKnownTrackers: envBoolean.default(DEFAULT_CONFIG.scraper.skipKnownTrackers),
500
581
  pageTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.pageTimeoutMs),
501
582
  browserTimeoutMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.browserTimeoutMs),
583
+ htmlExtractor: z.enum(["cheerio", "defuddle"]).default(DEFAULT_CONFIG.scraper.htmlExtractor),
502
584
  fetcher: z.object({
503
585
  maxRetries: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.maxRetries),
504
586
  baseDelayMs: z.coerce.number().int().default(DEFAULT_CONFIG.scraper.fetcher.baseDelayMs),
@@ -576,6 +658,7 @@ const AppConfigSchema = z.object({
576
658
  maxChunkDistance: z.coerce.number().int().min(0).default(DEFAULT_CONFIG.assembly.maxChunkDistance)
577
659
  }).default(DEFAULT_CONFIG.assembly)
578
660
  });
661
+ const vectorDimensionExplicit = /* @__PURE__ */ Symbol("vectorDimensionExplicit");
579
662
  const defaults = AppConfigSchema.parse({});
580
663
  const configMappings = [
581
664
  { path: ["server", "protocol"], env: ["DOCS_MCP_PROTOCOL"], cli: "protocol" },
@@ -605,6 +688,11 @@ const configMappings = [
605
688
  cli: "port"
606
689
  },
607
690
  { path: ["server", "host"], env: ["DOCS_MCP_HOST", "HOST"], cli: "host" },
691
+ {
692
+ path: ["server", "publicOrigin"],
693
+ env: ["DOCS_MCP_SERVER_PUBLIC_ORIGIN"],
694
+ cli: "publicOrigin"
695
+ },
608
696
  {
609
697
  path: ["app", "embeddingModel"],
610
698
  env: ["DOCS_MCP_EMBEDDING_MODEL"],
@@ -637,16 +725,34 @@ function loadConfig(cliArgs = {}, options = {}) {
637
725
  }
638
726
  logger.debug(`Using config file: ${configPath}`);
639
727
  const fileConfig = loadConfigFile(configPath) || {};
728
+ const hasManagedVectorDimensionOmissionMarker = hasManagedConfigVectorDimensionOmissionMarker(configPath);
640
729
  const baseConfig = deepMerge(defaults, fileConfig);
730
+ const envConfig = mapEnvToConfig();
731
+ const cliConfig = mapCliToConfig(cliArgs);
732
+ const vectorDimensionWasExplicit = wasVectorDimensionExplicit(
733
+ fileConfig,
734
+ envConfig,
735
+ cliConfig,
736
+ isReadOnlyConfig,
737
+ hasManagedVectorDimensionOmissionMarker
738
+ );
739
+ const fileVectorDimensionWasExplicit = wasVectorDimensionExplicit(
740
+ fileConfig,
741
+ {},
742
+ {},
743
+ isReadOnlyConfig,
744
+ hasManagedVectorDimensionOmissionMarker
745
+ );
641
746
  if (!isReadOnlyConfig) {
642
747
  try {
643
- saveConfigFile(configPath, baseConfig);
748
+ saveConfigFile(configPath, baseConfig, {
749
+ managedDefaultConfig: true,
750
+ omitVectorDimension: !fileVectorDimensionWasExplicit
751
+ });
644
752
  } catch (error) {
645
753
  logger.warn(`Failed to save config file to ${configPath}: ${error}`);
646
754
  }
647
755
  }
648
- const envConfig = mapEnvToConfig();
649
- const cliConfig = mapCliToConfig(cliArgs);
650
756
  const mergedInput = deepMerge(
651
757
  baseConfig,
652
758
  deepMerge(envConfig, cliConfig)
@@ -656,7 +762,15 @@ function loadConfig(cliArgs = {}, options = {}) {
656
762
  }
657
763
  const parseResult = AppConfigSchema.safeParse(mergedInput);
658
764
  if (parseResult.success) {
659
- return parseResult.data;
765
+ return markVectorDimensionSource(
766
+ parseResult.data,
767
+ vectorDimensionWasExplicit
768
+ );
769
+ }
770
+ if (hasParseIssueAtPath(parseResult.error, ["server", "publicOrigin"])) {
771
+ throw new Error(
772
+ `Invalid configuration for server.publicOrigin: ${parseResult.error.message}`
773
+ );
660
774
  }
661
775
  if (!isReadOnlyConfig && fs.existsSync(configPath)) {
662
776
  const quarantinePath = `${configPath}.invalid-${Date.now()}`;
@@ -683,14 +797,40 @@ function loadConfig(cliArgs = {}, options = {}) {
683
797
  setAtPath(fallbackInput, ["app", "embeddingModel"], "text-embedding-3-small");
684
798
  }
685
799
  const fallback = AppConfigSchema.parse(fallbackInput);
800
+ const fallbackConfig = markVectorDimensionSource(
801
+ fallback,
802
+ wasVectorDimensionExplicit({}, envConfig, cliConfig, false, false)
803
+ );
686
804
  if (!isReadOnlyConfig) {
687
805
  try {
688
- saveConfigFile(configPath, fallback);
806
+ saveConfigFile(configPath, fallbackConfig, {
807
+ managedDefaultConfig: true,
808
+ omitVectorDimension: true
809
+ });
689
810
  } catch (error) {
690
811
  logger.warn(`Failed to write fresh config file ${configPath}: ${error}`);
691
812
  }
692
813
  }
693
- return fallback;
814
+ return fallbackConfig;
815
+ }
816
+ function hasManagedConfigVectorDimensionOmissionMarker(filePath) {
817
+ if (!fs.existsSync(filePath)) return false;
818
+ try {
819
+ return fs.readFileSync(filePath, "utf8").includes(managedConfigVectorDimensionOmissionMarker);
820
+ } catch {
821
+ return false;
822
+ }
823
+ }
824
+ function isVectorDimensionExplicit(config) {
825
+ return config.embeddings[vectorDimensionExplicit] === true;
826
+ }
827
+ function markVectorDimensionSource(config, explicit) {
828
+ Object.defineProperty(config.embeddings, vectorDimensionExplicit, {
829
+ value: explicit,
830
+ enumerable: false,
831
+ configurable: true
832
+ });
833
+ return config;
694
834
  }
695
835
  function loadConfigFile(filePath) {
696
836
  if (!fs.existsSync(filePath)) return null;
@@ -705,16 +845,45 @@ function loadConfigFile(filePath) {
705
845
  return null;
706
846
  }
707
847
  }
708
- function saveConfigFile(filePath, config) {
848
+ function wasVectorDimensionExplicit(fileConfig, envConfig, cliConfig, isReadOnlyConfig, hasManagedVectorDimensionOmissionMarker) {
849
+ if (getAtPath(envConfig, vectorDimensionPath) !== void 0 || getAtPath(cliConfig, vectorDimensionPath) !== void 0) {
850
+ return true;
851
+ }
852
+ const fileValue = getAtPath(fileConfig, vectorDimensionPath);
853
+ if (fileValue === void 0) {
854
+ return false;
855
+ }
856
+ if (isReadOnlyConfig || fileValue !== DEFAULT_CONFIG.embeddings.vectorDimension || hasManagedVectorDimensionOmissionMarker) {
857
+ return true;
858
+ }
859
+ return !looksLikeLegacyGeneratedEmbeddingDefaults(fileConfig);
860
+ }
861
+ function looksLikeLegacyGeneratedEmbeddingDefaults(fileConfig) {
862
+ const embeddings = fileConfig.embeddings;
863
+ if (typeof embeddings !== "object" || embeddings === null || Array.isArray(embeddings)) {
864
+ return false;
865
+ }
866
+ return Object.keys(DEFAULT_CONFIG.embeddings).every(
867
+ (key) => Object.hasOwn(embeddings, key)
868
+ );
869
+ }
870
+ function saveConfigFile(filePath, config, options = {}) {
709
871
  const dir = path.dirname(filePath);
710
872
  if (!fs.existsSync(dir)) {
711
873
  fs.mkdirSync(dir, { recursive: true });
712
874
  }
875
+ const configToWrite = cloneConfigValue(config);
876
+ if (options.omitVectorDimension) {
877
+ unsetAtPath(configToWrite, vectorDimensionPath);
878
+ }
713
879
  let content;
714
880
  if (filePath.endsWith(".json")) {
715
- content = JSON.stringify(config, null, 2);
881
+ content = JSON.stringify(configToWrite, null, 2);
716
882
  } else {
717
- content = yaml.stringify(config);
883
+ content = yaml.stringify(configToWrite);
884
+ if (options.managedDefaultConfig) {
885
+ content = `${managedConfigHeader}${content}`;
886
+ }
718
887
  }
719
888
  logger.debug(`Updating config file at ${filePath}`);
720
889
  fs.writeFileSync(filePath, content, "utf8");
@@ -790,6 +959,44 @@ function getAtPath(obj, pathArr) {
790
959
  }
791
960
  return current;
792
961
  }
962
+ function unsetAtPath(obj, pathArr) {
963
+ let current = obj;
964
+ for (const key of pathArr.slice(0, -1)) {
965
+ if (typeof current !== "object" || current === null) {
966
+ return;
967
+ }
968
+ current = current[key];
969
+ }
970
+ if (typeof current === "object" && current !== null) {
971
+ delete current[pathArr[pathArr.length - 1]];
972
+ }
973
+ }
974
+ function cloneConfigValue(value) {
975
+ if (Array.isArray(value)) {
976
+ return value.map((item) => cloneConfigValue(item));
977
+ }
978
+ if (typeof value === "object" && value !== null) {
979
+ const output = {};
980
+ for (const [key, child] of Object.entries(value)) {
981
+ output[key] = cloneConfigValue(child);
982
+ }
983
+ return output;
984
+ }
985
+ return value;
986
+ }
987
+ function hasPath(obj, pathArr) {
988
+ let current = obj;
989
+ for (const key of pathArr) {
990
+ if (typeof current !== "object" || current === null || !Object.hasOwn(current, key)) {
991
+ return false;
992
+ }
993
+ current = current[key];
994
+ }
995
+ return true;
996
+ }
997
+ function hasParseIssueAtPath(error, pathArr) {
998
+ return error.issues.some((issue) => issue.path.join(".") === pathArr.join("."));
999
+ }
793
1000
  function deepMerge(target, source) {
794
1001
  if (typeof target !== "object" || target === null) return source;
795
1002
  if (typeof source !== "object" || source === null) return target;
@@ -810,7 +1017,7 @@ function deepMerge(target, source) {
810
1017
  }
811
1018
  function isValidConfigPath(path2) {
812
1019
  const pathArr = path2.split(".");
813
- return getAtPath(DEFAULT_CONFIG, pathArr) !== void 0;
1020
+ return hasPath(DEFAULT_CONFIG, pathArr);
814
1021
  }
815
1022
  function getConfigValue(config, path2) {
816
1023
  const pathArr = path2.split(".");
@@ -1082,6 +1289,7 @@ class ProxyAuthManager {
1082
1289
  proxyProvider = null;
1083
1290
  discoveredEndpoints = null;
1084
1291
  jwks = null;
1292
+ resourceOrigin = null;
1085
1293
  /**
1086
1294
  * Get the authentication configuration
1087
1295
  */
@@ -1141,6 +1349,7 @@ class ProxyAuthManager {
1141
1349
  if (!this.proxyProvider) {
1142
1350
  throw new Error("Proxy provider not initialized");
1143
1351
  }
1352
+ this.resourceOrigin = baseUrl.origin;
1144
1353
  server.get("/.well-known/oauth-authorization-server", async (_request, reply) => {
1145
1354
  const metadata = {
1146
1355
  issuer: baseUrl.origin,
@@ -1339,14 +1548,16 @@ class ProxyAuthManager {
1339
1548
  * Get supported resource URLs for this MCP server instance.
1340
1549
  * This enables self-discovering resource validation per MCP Authorization spec.
1341
1550
  */
1342
- getSupportedResources(request) {
1343
- const baseUrl = `${request.protocol}://${request.headers.host}`;
1551
+ getSupportedResources() {
1552
+ if (!this.resourceOrigin) {
1553
+ return [];
1554
+ }
1344
1555
  return [
1345
- `${baseUrl}/sse`,
1556
+ `${this.resourceOrigin}/sse`,
1346
1557
  // SSE transport
1347
- `${baseUrl}/mcp`,
1558
+ `${this.resourceOrigin}/mcp`,
1348
1559
  // Streaming HTTP transport
1349
- `${baseUrl}`
1560
+ this.resourceOrigin
1350
1561
  // Server root
1351
1562
  ];
1352
1563
  }
@@ -1406,7 +1617,7 @@ class ProxyAuthManager {
1406
1617
  throw new Error("Userinfo response missing subject");
1407
1618
  }
1408
1619
  if (request) {
1409
- const supportedResources = this.getSupportedResources(request);
1620
+ const supportedResources = this.getSupportedResources();
1410
1621
  logger.debug(`Supported resources: ${JSON.stringify(supportedResources)}`);
1411
1622
  }
1412
1623
  return {
@@ -3170,6 +3381,22 @@ class FingerprintGenerator {
3170
3381
  return this.headerGenerator.getHeaders();
3171
3382
  }
3172
3383
  }
3384
+ const MARKDOWN_PREFERRED_ACCEPT = "text/markdown, text/html;q=0.9, */*;q=0.8";
3385
+ function withMarkdownPreferredAccept(headers, callerHeaders = {}) {
3386
+ const hasCallerAccept = Object.keys(callerHeaders).some(
3387
+ (header) => header.toLowerCase() === "accept"
3388
+ );
3389
+ if (hasCallerAccept) {
3390
+ return headers;
3391
+ }
3392
+ const withoutGeneratedAccept = Object.fromEntries(
3393
+ Object.entries(headers).filter(([header]) => header.toLowerCase() !== "accept")
3394
+ );
3395
+ return {
3396
+ ...withoutGeneratedAccept,
3397
+ Accept: MARKDOWN_PREFERRED_ACCEPT
3398
+ };
3399
+ }
3173
3400
  var FetchStatus = /* @__PURE__ */ ((FetchStatus2) => {
3174
3401
  FetchStatus2["SUCCESS"] = "success";
3175
3402
  FetchStatus2["NOT_MODIFIED"] = "not_modified";
@@ -3218,10 +3445,15 @@ class BrowserFetcher {
3218
3445
  }
3219
3446
  return await route.continue();
3220
3447
  });
3221
- await page.setExtraHTTPHeaders({
3222
- ...fingerprintHeaders,
3223
- ...options?.headers
3224
- });
3448
+ await page.setExtraHTTPHeaders(
3449
+ withMarkdownPreferredAccept(
3450
+ {
3451
+ ...fingerprintHeaders,
3452
+ ...options?.headers
3453
+ },
3454
+ options?.headers
3455
+ )
3456
+ );
3225
3457
  const timeout = options?.timeout || this.defaultTimeoutMs;
3226
3458
  logger.debug(`Navigating to ${source} with browser...`);
3227
3459
  const response = await page.goto(source, {
@@ -3239,10 +3471,10 @@ class BrowserFetcher {
3239
3471
  }
3240
3472
  const finalUrl = page.url();
3241
3473
  await this.accessPolicy.assertNetworkUrlAllowed(finalUrl);
3242
- const content = await page.content();
3243
- const contentBuffer = Buffer.from(content, "utf-8");
3244
3474
  const contentType = response.headers()["content-type"] || "text/html";
3245
3475
  const { mimeType, charset } = MimeTypeUtils.parseContentType(contentType);
3476
+ const content = MimeTypeUtils.isHtml(mimeType) ? await page.content() : await response.body();
3477
+ const contentBuffer = Buffer.isBuffer(content) ? content : Buffer.from(content, "utf-8");
3246
3478
  const etag = response.headers().etag;
3247
3479
  return {
3248
3480
  content: contentBuffer,
@@ -3465,11 +3697,14 @@ class HttpFetcher {
3465
3697
  let redirectCount = 0;
3466
3698
  while (true) {
3467
3699
  const fingerprint = this.fingerprintGenerator.generateHeaders();
3468
- const headers = {
3469
- ...fingerprint,
3470
- ...options?.headers
3471
- // User-provided headers override generated ones
3472
- };
3700
+ const headers = withMarkdownPreferredAccept(
3701
+ {
3702
+ ...fingerprint,
3703
+ ...options?.headers
3704
+ // User-provided headers override generated ones
3705
+ },
3706
+ options?.headers
3707
+ );
3473
3708
  if (options?.etag) {
3474
3709
  headers["If-None-Match"] = options.etag;
3475
3710
  logger.debug(
@@ -4038,36 +4273,107 @@ class CodeContentSplitter {
4038
4273
  }
4039
4274
  options;
4040
4275
  async split(content) {
4041
- const language = content.match(/^```(\w+)\n/)?.[1];
4042
- const strippedContent = content.replace(/^```(\w*)\n/, "").replace(/```\s*$/, "");
4276
+ const infoMatch = content.match(/^```([^\n]*)\n/);
4277
+ const infoString = (infoMatch?.[1] ?? "").trimEnd();
4278
+ const strippedContent = content.replace(/^```[^\n]*\n/, "").replace(/```\s*$/, "");
4043
4279
  const lines = strippedContent.split("\n");
4044
4280
  const chunks = [];
4045
4281
  let currentChunkLines = [];
4046
4282
  for (const line of lines) {
4047
- const singleLineSize = this.wrap(line, language).length;
4283
+ const singleLineSize = this.wrap(line, infoString).length;
4048
4284
  if (singleLineSize > this.options.chunkSize) {
4049
4285
  throw new MinimumChunkSizeError(singleLineSize, this.options.chunkSize);
4050
4286
  }
4051
4287
  currentChunkLines.push(line);
4052
- const newChunkContent = this.wrap(currentChunkLines.join("\n"), language);
4288
+ const newChunkContent = this.wrap(currentChunkLines.join("\n"), infoString);
4053
4289
  const newChunkSize = newChunkContent.length;
4054
4290
  if (newChunkSize > this.options.chunkSize && currentChunkLines.length > 1) {
4055
4291
  const lastLine = currentChunkLines.pop();
4056
- chunks.push(this.wrap(currentChunkLines.join("\n"), language));
4292
+ chunks.push(this.wrap(currentChunkLines.join("\n"), infoString));
4057
4293
  currentChunkLines = [lastLine];
4058
4294
  }
4059
4295
  }
4060
4296
  if (currentChunkLines.length > 0) {
4061
- chunks.push(this.wrap(currentChunkLines.join("\n"), language));
4297
+ chunks.push(this.wrap(currentChunkLines.join("\n"), infoString));
4062
4298
  }
4063
4299
  return chunks;
4064
4300
  }
4065
- wrap(content, language) {
4066
- return `\`\`\`${language || ""}
4301
+ wrap(content, infoString) {
4302
+ return `\`\`\`${infoString || ""}
4067
4303
  ${content.replace(/\n+$/, "")}
4068
4304
  \`\`\``;
4069
4305
  }
4070
4306
  }
4307
+ const FENCE_PREFIX = "[ \\t]*(?:>[ \\t]*)*";
4308
+ const FENCE_OPENER = new RegExp(`^${FENCE_PREFIX}(\`{3,}|~{3,})`);
4309
+ function splitLinesWithOffsets(text) {
4310
+ const lines = [];
4311
+ let offset = 0;
4312
+ while (offset <= text.length) {
4313
+ const nlIndex = text.indexOf("\n", offset);
4314
+ if (nlIndex === -1) {
4315
+ if (offset < text.length) {
4316
+ lines.push({ content: text.slice(offset), offset, newlineLength: 0 });
4317
+ }
4318
+ return lines;
4319
+ }
4320
+ lines.push({
4321
+ content: text.slice(offset, nlIndex),
4322
+ offset,
4323
+ newlineLength: 1
4324
+ });
4325
+ offset = nlIndex + 1;
4326
+ }
4327
+ return lines;
4328
+ }
4329
+ function isClosingFence(line, delimiter, openerCount) {
4330
+ const closerRegex = new RegExp(
4331
+ `^${FENCE_PREFIX}\\${delimiter}{${openerCount},}[ \\t]*$`
4332
+ );
4333
+ return closerRegex.test(line);
4334
+ }
4335
+ function findFenceRegions(text) {
4336
+ const regions = [];
4337
+ const lines = splitLinesWithOffsets(text);
4338
+ let i = 0;
4339
+ while (i < lines.length) {
4340
+ const opener = FENCE_OPENER.exec(lines[i].content);
4341
+ if (!opener) {
4342
+ i += 1;
4343
+ continue;
4344
+ }
4345
+ const delimiter = opener[1][0];
4346
+ const count = opener[1].length;
4347
+ const startOffset = lines[i].offset;
4348
+ let closerLineIndex = -1;
4349
+ for (let j = i + 1; j < lines.length; j++) {
4350
+ if (isClosingFence(lines[j].content, delimiter, count)) {
4351
+ closerLineIndex = j;
4352
+ break;
4353
+ }
4354
+ }
4355
+ if (closerLineIndex === -1) {
4356
+ regions.push({ startOffset, endOffset: text.length });
4357
+ break;
4358
+ }
4359
+ const closerLine = lines[closerLineIndex];
4360
+ const endOffset = closerLine.offset + closerLine.content.length + closerLine.newlineLength;
4361
+ regions.push({ startOffset, endOffset });
4362
+ i = closerLineIndex + 1;
4363
+ }
4364
+ return regions;
4365
+ }
4366
+ function hasOpenFenceAtEnd(chunk) {
4367
+ const regions = findFenceRegions(chunk);
4368
+ if (regions.length === 0) return false;
4369
+ const last = regions[regions.length - 1];
4370
+ if (last.endOffset !== chunk.length) return false;
4371
+ const lines = splitLinesWithOffsets(chunk.slice(last.startOffset));
4372
+ if (lines.length < 2) return true;
4373
+ const opener = FENCE_OPENER.exec(lines[0].content);
4374
+ if (!opener) return false;
4375
+ return !isClosingFence(lines[lines.length - 1].content, opener[1][0], opener[1].length);
4376
+ }
4071
4377
  class TextContentSplitter {
4072
4378
  constructor(options) {
4073
4379
  this.options = options;
@@ -4089,16 +4395,50 @@ class TextContentSplitter {
4089
4395
  if (longestWord.length > this.options.chunkSize) {
4090
4396
  throw new MinimumChunkSizeError(longestWord.length, this.options.chunkSize);
4091
4397
  }
4092
- const paragraphChunks = this.splitByParagraphs(content);
4398
+ const paragraphChunks = this.mergeForFenceBalance(
4399
+ this.splitByParagraphs(content),
4400
+ ""
4401
+ );
4093
4402
  if (this.areChunksValid(paragraphChunks)) {
4094
4403
  return paragraphChunks;
4095
4404
  }
4096
- const lineChunks = this.splitByLines(content);
4405
+ const lineChunks = this.mergeForFenceBalance(this.splitByLines(content), "");
4097
4406
  if (this.areChunksValid(lineChunks)) {
4098
4407
  return this.mergeChunks(lineChunks, "");
4099
4408
  }
4100
- const wordChunks = await this.splitByWords(content);
4101
- return this.mergeChunks(wordChunks, " ");
4409
+ const wordChunks = this.mergeForFenceBalance(await this.splitByWords(content), " ");
4410
+ const merged = this.mergeChunks(wordChunks, " ");
4411
+ this.warnOversize(merged);
4412
+ return merged;
4413
+ }
4414
+ /**
4415
+ * Walks `chunks` left to right and merges adjacent chunks whenever the running
4416
+ * buffer ends inside an open fenced code block. Guarantees that every emitted
4417
+ * chunk has balanced fences (i.e. `hasOpenFenceAtEnd` returns false).
4418
+ */
4419
+ mergeForFenceBalance(chunks, separator) {
4420
+ const result = [];
4421
+ let buffer = "";
4422
+ for (const chunk of chunks) {
4423
+ buffer = buffer ? `${buffer}${separator}${chunk}` : chunk;
4424
+ if (!hasOpenFenceAtEnd(buffer)) {
4425
+ result.push(buffer);
4426
+ buffer = "";
4427
+ }
4428
+ }
4429
+ if (buffer) {
4430
+ result.push(buffer);
4431
+ }
4432
+ return result;
4433
+ }
4434
+ warnOversize(chunks) {
4435
+ for (const chunk of chunks) {
4436
+ if (chunk.length > this.options.chunkSize) {
4437
+ logger.warn(
4438
+ `⚠ TextContentSplitter emitted oversize chunk to preserve fence balance: ${chunk.length} > ${this.options.chunkSize}`
4439
+ );
4440
+ }
4441
+ }
4102
4442
  }
4103
4443
  /**
4104
4444
  * Checks if all chunks are within the maximum size limit
@@ -5392,7 +5732,7 @@ class HtmlPlaywrightMiddleware {
5392
5732
  * Consider making this more robust (e.g., lazy initialization, singleton).
5393
5733
  */
5394
5734
  async ensureBrowser() {
5395
- if (!this.browser || !this.browser.isConnected()) {
5735
+ if (!this.browser?.isConnected()) {
5396
5736
  logger.debug("Launching new Playwright browser instance (Chromium)");
5397
5737
  this.browser = await BrowserFetcher.launchBrowser();
5398
5738
  this.browser.on("disconnected", () => {
@@ -5402,23 +5742,112 @@ class HtmlPlaywrightMiddleware {
5402
5742
  }
5403
5743
  return this.browser;
5404
5744
  }
5745
+ getPageTimeoutMs() {
5746
+ return this.config.pageTimeoutMs ?? defaults.scraper.pageTimeoutMs;
5747
+ }
5748
+ getBrowserTimeoutMs() {
5749
+ return this.config.browserTimeoutMs ?? defaults.scraper.browserTimeoutMs;
5750
+ }
5751
+ async withTimeout(operation, timeoutMs, description) {
5752
+ let timeout;
5753
+ try {
5754
+ return await Promise.race([
5755
+ operation,
5756
+ new Promise((_resolve, reject) => {
5757
+ timeout = setTimeout(() => {
5758
+ reject(new Error(`${description} timed out after ${timeoutMs}ms`));
5759
+ }, timeoutMs);
5760
+ })
5761
+ ]);
5762
+ } finally {
5763
+ if (timeout) {
5764
+ clearTimeout(timeout);
5765
+ }
5766
+ }
5767
+ }
5768
+ getBrowserProcess(browser) {
5769
+ if (!("process" in browser) || typeof browser.process !== "function") {
5770
+ return null;
5771
+ }
5772
+ return browser.process();
5773
+ }
5774
+ killBrowserProcess(browser, reason) {
5775
+ const browserProcess = this.getBrowserProcess(browser);
5776
+ if (!browserProcess || browserProcess.killed) {
5777
+ return;
5778
+ }
5779
+ const pid = browserProcess.pid ? ` pid=${browserProcess.pid}` : "";
5780
+ logger.warn(`⚠️ Force killing Playwright browser process${pid}: ${reason}`);
5781
+ try {
5782
+ if (!browserProcess.kill("SIGKILL")) {
5783
+ logger.warn(`⚠️ Failed to force kill Playwright browser process${pid}`);
5784
+ }
5785
+ } catch (error) {
5786
+ logger.warn(`⚠️ Failed to force kill Playwright browser process${pid}: ${error}`);
5787
+ }
5788
+ }
5405
5789
  /**
5406
5790
  * Closes the Playwright browser instance if it exists.
5407
5791
  * Should be called during application shutdown.
5408
5792
  * Attempts to close even if the browser is disconnected to ensure proper cleanup of zombie processes.
5409
5793
  */
5410
- async closeBrowser() {
5794
+ async closeBrowser(reason = "shutdown") {
5411
5795
  if (this.browser) {
5796
+ const browser = this.browser;
5412
5797
  try {
5413
- logger.debug("Closing Playwright browser instance...");
5414
- await this.browser.close();
5798
+ logger.debug(`Closing Playwright browser instance (${reason})...`);
5799
+ await this.withTimeout(
5800
+ browser.close(),
5801
+ this.getPageTimeoutMs(),
5802
+ "Playwright browser close"
5803
+ );
5415
5804
  } catch (error) {
5416
- logger.warn(`⚠️ Error closing Playwright browser: ${error}`);
5805
+ logger.warn(`⚠️ Error closing Playwright browser (${reason}): ${error}`);
5806
+ this.killBrowserProcess(browser, reason);
5417
5807
  } finally {
5418
5808
  this.browser = null;
5419
5809
  }
5420
5810
  }
5421
5811
  }
5812
+ async cleanupPageAndContext(page, browserContext, source) {
5813
+ let cleanupSucceeded = true;
5814
+ const timeoutMs = this.getPageTimeoutMs();
5815
+ if (page) {
5816
+ try {
5817
+ await this.withTimeout(
5818
+ page.unroute("**/*"),
5819
+ timeoutMs,
5820
+ `Playwright route cleanup for ${source}`
5821
+ );
5822
+ } catch (error) {
5823
+ cleanupSucceeded = false;
5824
+ logger.warn(`⚠️ Playwright route cleanup failed for ${source}: ${error}`);
5825
+ }
5826
+ try {
5827
+ await this.withTimeout(
5828
+ page.close(),
5829
+ timeoutMs,
5830
+ `Playwright page close for ${source}`
5831
+ );
5832
+ } catch (error) {
5833
+ cleanupSucceeded = false;
5834
+ logger.warn(`⚠️ Playwright page cleanup failed for ${source}: ${error}`);
5835
+ }
5836
+ }
5837
+ if (browserContext) {
5838
+ try {
5839
+ await this.withTimeout(
5840
+ browserContext.close(),
5841
+ timeoutMs,
5842
+ `Playwright browser context close for ${source}`
5843
+ );
5844
+ } catch (error) {
5845
+ cleanupSucceeded = false;
5846
+ logger.warn(`⚠️ Playwright context cleanup failed for ${source}: ${error}`);
5847
+ }
5848
+ }
5849
+ return cleanupSucceeded;
5850
+ }
5422
5851
  /**
5423
5852
  * Injects the shadow DOM extractor script into the page.
5424
5853
  * This script performs non-invasive extraction that preserves document structure.
@@ -5770,127 +6199,160 @@ class HtmlPlaywrightMiddleware {
5770
6199
  }
5771
6200
  return false;
5772
6201
  }
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)) {
6202
+ isTargetClosedError(error) {
6203
+ if (!(error instanceof Error)) {
6204
+ return false;
6205
+ }
6206
+ return error.message.includes("Target page, context or browser has been closed");
6207
+ }
6208
+ formatRouteError(error) {
6209
+ const message = error instanceof Error ? error.message : String(error);
6210
+ return message.split("\n")[0] || message;
6211
+ }
6212
+ isSpeculativePrefetch(route) {
6213
+ const headers = route.request().headers();
6214
+ return headers["next-router-prefetch"] === "1" || headers.purpose?.toLowerCase() === "prefetch" || headers["sec-purpose"]?.toLowerCase().includes("prefetch") === true;
6215
+ }
6216
+ isCacheableResponseContent(contentType) {
6217
+ const { mimeType } = MimeTypeUtils.parseContentType(contentType);
6218
+ return MimeTypeUtils.isHtml(mimeType) || MimeTypeUtils.isMarkdown(mimeType) || MimeTypeUtils.isSafeForTextProcessing(mimeType);
6219
+ }
6220
+ getRequestOrigin(url) {
6221
+ try {
6222
+ return new URL(url).origin;
6223
+ } catch {
6224
+ return null;
6225
+ }
6226
+ }
6227
+ ignoreRouteLifecycleError(error, action, reqUrl) {
6228
+ if (this.isRouteAlreadyHandledError(error)) {
6229
+ logger.debug(`Route already handled (${action}): ${reqUrl}`);
6230
+ return true;
6231
+ }
6232
+ if (this.isTargetClosedError(error)) {
6233
+ logger.debug(`Route target closed (${action}): ${reqUrl}`);
6234
+ return true;
6235
+ }
6236
+ return false;
6237
+ }
6238
+ async abortRoute(route, reqUrl, action, reason) {
6239
+ try {
6240
+ await route.abort(reason);
6241
+ } catch (error) {
6242
+ if (this.ignoreRouteLifecycleError(error, action, reqUrl)) {
5788
6243
  return;
5789
6244
  }
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
- }
6245
+ throw error;
6246
+ }
6247
+ }
6248
+ async fulfillRoute(route, reqUrl, options, action) {
6249
+ try {
6250
+ await route.fulfill(options);
6251
+ } catch (error) {
6252
+ if (this.ignoreRouteLifecycleError(error, action, reqUrl)) {
6253
+ return;
5800
6254
  }
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
- }
6255
+ throw error;
6256
+ }
6257
+ }
6258
+ async continueRoute(route, reqUrl, resourceType, options) {
6259
+ try {
6260
+ await route.continue(options);
6261
+ } catch (error) {
6262
+ if (this.ignoreRouteLifecycleError(error, "continue", reqUrl)) {
6263
+ return;
5867
6264
  }
5868
- const headers = mergePlaywrightHeaders(
5869
- route.request().headers(),
5870
- customHeaders,
5871
- credentials,
5872
- origin,
5873
- reqOrigin ?? void 0
6265
+ const errorMessage = this.formatRouteError(error);
6266
+ logger.debug(`Error continuing ${resourceType} ${reqUrl}: ${errorMessage}`);
6267
+ await this.abortRoute(route, reqUrl, "abort after continue error", "failed");
6268
+ }
6269
+ }
6270
+ async cacheResponseIfEligible(reqUrl, resourceType, response) {
6271
+ const contentType = response.headers()["content-type"] || "application/octet-stream";
6272
+ if (response.status() < 200 || response.status() >= 300) {
6273
+ return;
6274
+ }
6275
+ if (!this.isCacheableResponseContent(contentType)) {
6276
+ logger.debug(
6277
+ `Skipping cache for unsupported content type "${contentType}" (${resourceType}): ${reqUrl}`
5874
6278
  );
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
- }
6279
+ return;
6280
+ }
6281
+ const body = await response.text();
6282
+ if (body.length === 0) {
6283
+ return;
6284
+ }
6285
+ const contentSizeBytes = Buffer.byteLength(body, "utf8");
6286
+ const maxCacheItemSizeBytes = this.config?.fetcher?.maxCacheItemSizeBytes ?? defaults.scraper.fetcher.maxCacheItemSizeBytes;
6287
+ if (contentSizeBytes > maxCacheItemSizeBytes) {
6288
+ logger.debug(
6289
+ `Resource too large to cache: ${reqUrl} (${contentSizeBytes} bytes > ${maxCacheItemSizeBytes} bytes limit)`
6290
+ );
6291
+ return;
6292
+ }
6293
+ HtmlPlaywrightMiddleware.resourceCache.set(reqUrl, { body, contentType });
6294
+ logger.debug(
6295
+ `Cached ${resourceType}: ${reqUrl} (${contentSizeBytes} bytes, cache size: ${HtmlPlaywrightMiddleware.resourceCache.size})`
6296
+ );
6297
+ }
6298
+ async handleSubresourceRoute(route, customHeaders, credentials, origin) {
6299
+ const reqUrl = route.request().url();
6300
+ const reqOrigin = this.getRequestOrigin(reqUrl);
6301
+ const resourceType = route.request().resourceType();
6302
+ if (!await this.isRequestAllowed(reqUrl)) {
6303
+ await this.abortRoute(route, reqUrl, "policy abort", "blockedbyclient");
6304
+ return;
6305
+ }
6306
+ if (await this.tryBlocklistAbort(route, reqUrl)) {
6307
+ return;
6308
+ }
6309
+ if (this.isSpeculativePrefetch(route)) {
6310
+ logger.debug(`Aborting speculative prefetch ${resourceType}: ${reqUrl}`);
6311
+ await this.abortRoute(route, reqUrl, "prefetch abort", "aborted");
6312
+ return;
6313
+ }
6314
+ if (["image", "font", "media"].includes(resourceType)) {
6315
+ await this.abortRoute(route, reqUrl, "abort");
6316
+ return;
6317
+ }
6318
+ const headers = mergePlaywrightHeaders(
6319
+ route.request().headers(),
6320
+ customHeaders,
6321
+ credentials,
6322
+ origin,
6323
+ reqOrigin ?? void 0
6324
+ );
6325
+ if (route.request().method() !== "GET") {
6326
+ await this.continueRoute(route, reqUrl, resourceType, { headers });
6327
+ return;
6328
+ }
6329
+ const cached = HtmlPlaywrightMiddleware.resourceCache.get(reqUrl);
6330
+ if (cached !== void 0) {
6331
+ logger.debug(`✓ Cache hit for ${resourceType}: ${reqUrl}`);
6332
+ await this.fulfillRoute(
6333
+ route,
6334
+ reqUrl,
6335
+ { status: 200, contentType: cached.contentType, body: cached.body },
6336
+ "fulfill cached"
6337
+ );
6338
+ return;
6339
+ }
6340
+ try {
6341
+ const response = await route.fetch({ headers });
6342
+ await this.cacheResponseIfEligible(reqUrl, resourceType, response);
6343
+ await this.fulfillRoute(route, reqUrl, { response }, "fulfill");
6344
+ } catch (error) {
6345
+ if (this.ignoreRouteLifecycleError(error, `fetch ${resourceType}`, reqUrl)) {
6346
+ return;
5893
6347
  }
6348
+ const errorMessage = this.formatRouteError(error);
6349
+ logger.debug(`Network error fetching ${resourceType} ${reqUrl}: ${errorMessage}`);
6350
+ await this.abortRoute(route, reqUrl, "abort after error", "failed");
6351
+ }
6352
+ }
6353
+ async setupCachingRouteInterception(page, customHeaders = {}, credentials, origin) {
6354
+ await page.route("**/*", async (route) => {
6355
+ await this.handleSubresourceRoute(route, customHeaders, credentials, origin);
5894
6356
  });
5895
6357
  }
5896
6358
  /**
@@ -6030,6 +6492,8 @@ ${frame.content}
6030
6492
  let page = null;
6031
6493
  let browserContext = null;
6032
6494
  let renderedHtml = null;
6495
+ let shouldResetBrowser = false;
6496
+ let renderFailed = false;
6033
6497
  const { credentials, origin } = extractCredentialsAndOrigin(context.source);
6034
6498
  const customHeaders = context.options?.headers ?? {};
6035
6499
  try {
@@ -6077,130 +6541,18 @@ ${frame.content}
6077
6541
  throw error;
6078
6542
  }
6079
6543
  }
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(),
6544
+ await this.handleSubresourceRoute(
6545
+ route,
6175
6546
  customHeaders,
6176
6547
  credentials ?? void 0,
6177
- origin ?? void 0,
6178
- reqOrigin ?? void 0
6548
+ origin ?? void 0
6179
6549
  );
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
6550
  });
6202
- await page.goto(context.source, { waitUntil: "load" });
6203
- const pageTimeoutMs = this.config.pageTimeoutMs ?? defaults.scraper.pageTimeoutMs;
6551
+ const pageTimeoutMs = this.getPageTimeoutMs();
6552
+ await page.goto(context.source, {
6553
+ waitUntil: "load",
6554
+ timeout: this.getBrowserTimeoutMs()
6555
+ });
6204
6556
  await page.waitForSelector("body, frameset", {
6205
6557
  timeout: pageTimeoutMs
6206
6558
  });
@@ -6220,17 +6572,25 @@ ${frame.content}
6220
6572
  `Playwright: Successfully rendered content for ${context.source} using ${method}`
6221
6573
  );
6222
6574
  } catch (error) {
6575
+ renderFailed = true;
6576
+ shouldResetBrowser = true;
6223
6577
  logger.error(`❌ Playwright failed to render ${context.source}: ${error}`);
6224
6578
  context.errors.push(
6225
6579
  error instanceof Error ? error : new Error(`Playwright rendering failed: ${String(error)}`)
6226
6580
  );
6227
6581
  } finally {
6228
- if (page) {
6229
- await page.unroute("**/*");
6230
- await page.close();
6582
+ const cleanupSucceeded = await this.cleanupPageAndContext(
6583
+ page,
6584
+ browserContext,
6585
+ context.source
6586
+ );
6587
+ const cleanupFailed = !cleanupSucceeded;
6588
+ if (cleanupFailed) {
6589
+ shouldResetBrowser = true;
6231
6590
  }
6232
- if (browserContext) {
6233
- await browserContext.close();
6591
+ if (shouldResetBrowser) {
6592
+ const resetReason = renderFailed ? cleanupFailed ? `reset after Playwright render and cleanup failure for ${context.source}` : `reset after Playwright render failure for ${context.source}` : `reset after Playwright cleanup failure for ${context.source}`;
6593
+ await this.closeBrowser(resetReason);
6234
6594
  }
6235
6595
  }
6236
6596
  if (renderedHtml !== null) {
@@ -6302,7 +6662,7 @@ function mergePlaywrightHeaders(requestHeaders, customHeaders, credentials, orig
6302
6662
  Authorization: `Basic ${basic}`
6303
6663
  };
6304
6664
  }
6305
- return headers;
6665
+ return withMarkdownPreferredAccept(headers, customHeaders);
6306
6666
  }
6307
6667
  class HtmlSanitizerMiddleware {
6308
6668
  // Default selectors to remove
@@ -6376,7 +6736,84 @@ class HtmlSanitizerMiddleware {
6376
6736
  '[role="search"]',
6377
6737
  '[role="region"][aria-label*="skip" i]',
6378
6738
  '[aria-modal="true"]',
6379
- ".noprint"
6739
+ ".noprint",
6740
+ // Skip-links and screen-reader-only anchors (e.g. "Skip to main content").
6741
+ // Scoped to <a> so icon-button labels (`<span class="sr-only">`) are left alone.
6742
+ "a.sr-only",
6743
+ "a.skip-link",
6744
+ "a.skip-nav",
6745
+ "a.screen-reader-only",
6746
+ "a.visually-hidden",
6747
+ // Breadcrumb variants beyond the .breadcrumb class above (ARIA + schema.org).
6748
+ '[aria-label="Breadcrumb" i]',
6749
+ '[itemtype*="BreadcrumbList"]',
6750
+ // Ad networks — removed at sanitization time (after render) rather than at
6751
+ // network level, to avoid triggering anti-adblock detection on monetized
6752
+ // sites. See subresourceBlocklist.ts for the rationale on why ads are not
6753
+ // network-blocked.
6754
+ // Carbon Ads (Vite, Astro, Tailwind, MDN, …)
6755
+ "#carbonads",
6756
+ ".carbonads",
6757
+ ".carbon-wrap",
6758
+ ".carbon-text",
6759
+ ".carbon-img",
6760
+ ".carbon-poweredby",
6761
+ // Scoped to the click-redirect host (srv.carbonads.net) rather than the
6762
+ // apex domain so that legitimate prose links to carbonads.net survive.
6763
+ 'a[href*="srv.carbonads.net"]',
6764
+ // BuySellAds
6765
+ ".bsa-promotion",
6766
+ ".bsa-cpc",
6767
+ '[id^="bsap_"]',
6768
+ '[id^="bsa-zone_"]',
6769
+ 'img[src*="buysellads.com"]',
6770
+ 'img[src*="buysellads.net"]',
6771
+ // EthicalAds (ReadTheDocs, Python/Django docs)
6772
+ ".ethical-rtd",
6773
+ ".ethical-fixedfooter",
6774
+ ".ethical-bottom-right",
6775
+ "[data-ea-publisher]",
6776
+ ".keep-us-sustainable",
6777
+ 'img[src*="ethicalads.io"]',
6778
+ // Google AdSense
6779
+ ".adsbygoogle",
6780
+ "ins.adsbygoogle",
6781
+ '[id^="google_ads_iframe"]',
6782
+ 'img[src*="googlesyndication.com"]',
6783
+ 'img[src*="doubleclick.net"]',
6784
+ // Outbrain / Taboola — content-recommendation widgets, indistinguishable
6785
+ // from ads on doc pages.
6786
+ ".OUTBRAIN",
6787
+ '[data-widget-id^="OB_"]',
6788
+ ".taboola",
6789
+ '[id^="taboola-"]',
6790
+ // Tracker pixels that escape via async injection
6791
+ 'img[src*="bidr.io"]',
6792
+ 'img[src*="adnxs.com"]',
6793
+ 'img[src*="adsrvr.org"]',
6794
+ 'img[src*="analytics.yahoo.com"]',
6795
+ // Third-party search widgets injected outside of nav/header.
6796
+ // Algolia DocSearch (dominant in technical docs)
6797
+ ".DocSearch",
6798
+ ".DocSearch-Button",
6799
+ ".DocSearch-Container",
6800
+ ".DocSearch-Modal",
6801
+ "#docsearch",
6802
+ '[id^="docsearch-"]',
6803
+ ".algolia-autocomplete",
6804
+ ".algolia-docsearch-suggestion",
6805
+ // MkDocs Material result containers (the search box is in nav; results can
6806
+ // render standalone)
6807
+ ".md-search-result",
6808
+ ".md-search__output",
6809
+ // Sphinx / ReadTheDocs search
6810
+ "#searchbox",
6811
+ "#search-results",
6812
+ ".wy-side-search",
6813
+ // Swiftype / Elastic Site Search
6814
+ "#st-search-input",
6815
+ "#st-results-container",
6816
+ ".st-default-search-input"
6380
6817
  ];
6381
6818
  async process(context, next) {
6382
6819
  const $ = context.dom;
@@ -6439,8 +6876,15 @@ class HtmlSanitizerMiddleware {
6439
6876
  await next();
6440
6877
  }
6441
6878
  }
6879
+ const maxGfmTableRows = 500;
6880
+ const maxGfmTableCells = 1e3;
6881
+ const maxGfmTableHtmlLength = 1e5;
6882
+ const gfmTableChunkRows = 100;
6883
+ const preservedTablePlaceholderAttribute = "data-docs-mcp-preserved-table-id";
6442
6884
  class HtmlToMarkdownMiddleware {
6443
6885
  turndownService;
6886
+ preservedTableHtml = /* @__PURE__ */ new Map();
6887
+ preservedTableSequence = 0;
6444
6888
  constructor() {
6445
6889
  this.turndownService = new TurndownService({
6446
6890
  headingStyle: "atx",
@@ -6474,11 +6918,15 @@ class HtmlToMarkdownMiddleware {
6474
6918
  if (match) language = match[1];
6475
6919
  }
6476
6920
  }
6477
- const brElements = Array.from(element.querySelectorAll("br"));
6478
- for (const br of brElements) {
6921
+ const clone = element.cloneNode(true);
6922
+ for (const br of Array.from(clone.querySelectorAll("br"))) {
6479
6923
  br.replaceWith("\n");
6480
6924
  }
6481
- const text = element.textContent || "";
6925
+ const lineNodes = clone.querySelectorAll("span.line, div.line, [data-line]");
6926
+ for (let i = 0; i < lineNodes.length - 1; i++) {
6927
+ lineNodes[i].appendChild(clone.ownerDocument.createTextNode("\n"));
6928
+ }
6929
+ const text = clone.textContent || "";
6482
6930
  return `
6483
6931
  \`\`\`${language}
6484
6932
  ${text.replace(/^\n+|\n+$/g, "")}
@@ -6500,10 +6948,90 @@ ${text.replace(/^\n+|\n+$/g, "")}
6500
6948
  }
6501
6949
  return `[${normalizedContent}](${href})`;
6502
6950
  }
6503
- });
6951
+ });
6952
+ this.turndownService.addRule("preservedOversizedTable", {
6953
+ filter: (node) => {
6954
+ const element = node;
6955
+ return element.nodeName === "DIV" && element.hasAttribute(preservedTablePlaceholderAttribute);
6956
+ },
6957
+ replacement: (_content, node) => {
6958
+ const element = node;
6959
+ const tableId = element.getAttribute(preservedTablePlaceholderAttribute);
6960
+ const tableHtml = tableId ? this.preservedTableHtml.get(tableId) : void 0;
6961
+ return tableHtml ? `
6962
+
6963
+ ${tableHtml}
6964
+
6965
+ ` : "";
6966
+ }
6967
+ });
6968
+ }
6969
+ normalizeLinkContent(content) {
6970
+ return fullTrim(content).replace(/[ \t]*[\r\n]+[ \t]*/g, " ");
6971
+ }
6972
+ splitOversizedTables($, source) {
6973
+ $("table").each((_index, element) => {
6974
+ const $table = $(element);
6975
+ const rowCount = $table.find("tr").length;
6976
+ const cellCount = $table.find("td, th").length;
6977
+ const htmlLength = $.html(element).length;
6978
+ if (rowCount <= maxGfmTableRows && cellCount <= maxGfmTableCells && htmlLength <= maxGfmTableHtmlLength) {
6979
+ return;
6980
+ }
6981
+ const replacement = this.buildSplitTableHtml($, $table);
6982
+ if (!replacement) {
6983
+ const tableId = `table-${++this.preservedTableSequence}`;
6984
+ this.preservedTableHtml.set(tableId, $.html(element));
6985
+ logger.warn(
6986
+ `⚠️ Preserving oversized HTML table for ${source} as HTML before GFM conversion: ${rowCount} rows, ${cellCount} cells, ${htmlLength} chars`
6987
+ );
6988
+ $table.replaceWith(
6989
+ `<div ${preservedTablePlaceholderAttribute}="${tableId}">preserved table</div>`
6990
+ );
6991
+ return;
6992
+ }
6993
+ logger.warn(
6994
+ `⚠️ Splitting oversized HTML table for ${source} before GFM conversion: ${rowCount} rows, ${cellCount} cells, ${htmlLength} chars`
6995
+ );
6996
+ $table.replaceWith(replacement);
6997
+ });
6998
+ }
6999
+ buildSplitTableHtml($, $table) {
7000
+ const headerRows = this.getHeaderRows($table);
7001
+ const headerRowSet = new Set(headerRows);
7002
+ const dataRows = $table.find("tr").toArray().filter((row) => row.type === "tag" && !headerRowSet.has(row));
7003
+ if (dataRows.length <= gfmTableChunkRows) {
7004
+ return null;
7005
+ }
7006
+ const chunks = [];
7007
+ const headerHtml = headerRows.map((row) => $.html(row)).join("");
7008
+ const preservedChildHtml = this.getPreservedTableChildHtml($, $table);
7009
+ for (let index = 0; index < dataRows.length; index += gfmTableChunkRows) {
7010
+ const rowsHtml = dataRows.slice(index, index + gfmTableChunkRows).map((row) => $.html(row)).join("");
7011
+ const tableParts = ["<table>", preservedChildHtml];
7012
+ if (headerHtml) {
7013
+ tableParts.push("<thead>", headerHtml, "</thead>");
7014
+ }
7015
+ tableParts.push("<tbody>", rowsHtml, "</tbody></table>");
7016
+ chunks.push(tableParts.join(""));
7017
+ }
7018
+ return chunks.join("\n");
6504
7019
  }
6505
- normalizeLinkContent(content) {
6506
- return fullTrim(content).replace(/[ \t]*[\r\n]+[ \t]*/g, " ");
7020
+ getPreservedTableChildHtml($, $table) {
7021
+ return $table.children("caption, colgroup").toArray().filter((child) => child.type === "tag").map((child) => $.html(child)).join("");
7022
+ }
7023
+ getHeaderRows($table) {
7024
+ const theadRows = $table.children("thead").find("tr").toArray().filter((row) => row.type === "tag");
7025
+ if (theadRows.length > 0) {
7026
+ return theadRows;
7027
+ }
7028
+ const firstRow = $table.find("tr").first();
7029
+ if (firstRow.length === 0) {
7030
+ return [];
7031
+ }
7032
+ const cells = firstRow.children("th, td").toArray();
7033
+ const isHeaderRow = cells.length > 0 && cells.every((cell) => cell.type === "tag" && cell.tagName === "th");
7034
+ return isHeaderRow ? firstRow.toArray() : [];
6507
7035
  }
6508
7036
  /**
6509
7037
  * Processes the context to convert the sanitized HTML body node to Markdown.
@@ -6521,6 +7049,8 @@ ${text.replace(/^\n+|\n+$/g, "")}
6521
7049
  }
6522
7050
  try {
6523
7051
  logger.debug(`Converting HTML content to Markdown for ${context.source}`);
7052
+ this.preservedTableHtml.clear();
7053
+ this.splitOversizedTables($, context.source);
6524
7054
  const htmlToConvert = $("body").html() || $.html();
6525
7055
  const markdown = this.turndownService.turndown(htmlToConvert).trim();
6526
7056
  if (!markdown) {
@@ -6541,6 +7071,8 @@ ${text.replace(/^\n+|\n+$/g, "")}
6541
7071
  `Failed to convert HTML to Markdown: ${error instanceof Error ? error.message : String(error)}`
6542
7072
  )
6543
7073
  );
7074
+ } finally {
7075
+ this.preservedTableHtml.clear();
6544
7076
  }
6545
7077
  await next();
6546
7078
  }
@@ -6622,11 +7154,13 @@ class HtmlPipeline extends BasePipeline {
6622
7154
  const maxChunkSize = config.splitter.maxChunkSize;
6623
7155
  const minChunkSize = config.splitter.minChunkSize;
6624
7156
  this.playwrightMiddleware = new HtmlPlaywrightMiddleware(config.scraper);
7157
+ const extractor = config.scraper.htmlExtractor === "defuddle" ? createLazyDefuddleMiddleware() : new HtmlSanitizerMiddleware();
7158
+ logger.debug(`HtmlPipeline using extractor: ${config.scraper.htmlExtractor}`);
6625
7159
  this.standardMiddleware = [
6626
7160
  new HtmlCheerioParserMiddleware(),
6627
7161
  new HtmlMetadataExtractorMiddleware(),
6628
7162
  new HtmlLinkExtractorMiddleware(),
6629
- new HtmlSanitizerMiddleware(),
7163
+ extractor,
6630
7164
  new HtmlNormalizationMiddleware(),
6631
7165
  new HtmlToMarkdownMiddleware()
6632
7166
  ];
@@ -6691,6 +7225,18 @@ class HtmlPipeline extends BasePipeline {
6691
7225
  }
6692
7226
  }
6693
7227
  }
7228
+ function createLazyDefuddleMiddleware() {
7229
+ let real = null;
7230
+ return {
7231
+ async process(context, next) {
7232
+ if (!real) {
7233
+ const mod = await import("./HtmlDefuddleMiddleware-DjhdN_D2.js");
7234
+ real = new mod.HtmlDefuddleMiddleware();
7235
+ }
7236
+ await real.process(context, next);
7237
+ }
7238
+ };
7239
+ }
6694
7240
  class TextDocumentSplitter {
6695
7241
  config;
6696
7242
  textSplitter;
@@ -7051,9 +7597,12 @@ class JsonPipeline extends BasePipeline {
7051
7597
  return currentDepth;
7052
7598
  }
7053
7599
  }
7600
+ const inlineLinkPattern = /(^|[^!\\])\[[^\]\n]+\]\(([^)\s]+)(?:\s+"[^"]*"|\s+'[^']*'|\s+\([^)]*\))?\)/g;
7601
+ const referenceLinkPattern = /(^|[^!\\])\[[^\]\n]+\]\[([^\]\n]+)\]/g;
7602
+ const referenceDefinitionPattern = /^\s{0,3}\[([^\]\n]+)\]:\s*(\S+)(?:\s+.*)?$/gm;
7054
7603
  class MarkdownLinkExtractorMiddleware {
7055
7604
  /**
7056
- * Processes the context. Currently a no-op regarding link extraction.
7605
+ * Processes the context and appends Markdown link targets to context.links.
7057
7606
  * @param context The current processing context.
7058
7607
  * @param next Function to call the next middleware.
7059
7608
  */
@@ -7061,9 +7610,50 @@ class MarkdownLinkExtractorMiddleware {
7061
7610
  if (!Array.isArray(context.links)) {
7062
7611
  context.links = [];
7063
7612
  }
7613
+ for (const link of extractMarkdownLinks(context.content)) {
7614
+ if (!context.links.includes(link)) {
7615
+ context.links.push(link);
7616
+ }
7617
+ }
7064
7618
  await next();
7065
7619
  }
7066
7620
  }
7621
+ function extractMarkdownLinks(content) {
7622
+ const links = [];
7623
+ const referenceDefinitions = /* @__PURE__ */ new Map();
7624
+ for (const match of content.matchAll(referenceDefinitionPattern)) {
7625
+ const label = normalizeReferenceLabel(match[1]);
7626
+ const target = cleanReferenceTarget(match[2]);
7627
+ if (label && target && !referenceDefinitions.has(label)) {
7628
+ referenceDefinitions.set(label, target);
7629
+ }
7630
+ }
7631
+ for (const match of content.matchAll(inlineLinkPattern)) {
7632
+ addUniqueLink(links, match[2]);
7633
+ }
7634
+ for (const match of content.matchAll(referenceLinkPattern)) {
7635
+ const target = referenceDefinitions.get(normalizeReferenceLabel(match[2]));
7636
+ if (target) {
7637
+ addUniqueLink(links, target);
7638
+ }
7639
+ }
7640
+ return links;
7641
+ }
7642
+ function addUniqueLink(links, target) {
7643
+ if (!target || links.includes(target)) {
7644
+ return;
7645
+ }
7646
+ links.push(target);
7647
+ }
7648
+ function normalizeReferenceLabel(label) {
7649
+ return label?.trim().replace(/\s+/g, " ").toLowerCase() ?? "";
7650
+ }
7651
+ function cleanReferenceTarget(target) {
7652
+ if (!target) {
7653
+ return "";
7654
+ }
7655
+ return target.trim().replace(/^<(.+)>$/, "$1");
7656
+ }
7067
7657
  class MarkdownMetadataExtractorMiddleware {
7068
7658
  /**
7069
7659
  * Processes the context to extract the title from Markdown.
@@ -9850,7 +10440,7 @@ function isActiveStatus(status) {
9850
10440
  class DocumentStore {
9851
10441
  config;
9852
10442
  db;
9853
- embeddings;
10443
+ embeddings = null;
9854
10444
  dbDimension;
9855
10445
  searchWeightVec;
9856
10446
  searchWeightFts;
@@ -9860,7 +10450,7 @@ class DocumentStore {
9860
10450
  embeddingBatchSize;
9861
10451
  embeddingBatchChars;
9862
10452
  embeddingInitTimeoutMs;
9863
- modelDimension;
10453
+ modelDimension = null;
9864
10454
  embeddingConfig;
9865
10455
  isVectorSearchEnabled = false;
9866
10456
  /**
@@ -10178,6 +10768,18 @@ class DocumentStore {
10178
10768
  stmt.run("embedding_model", model);
10179
10769
  stmt.run("embedding_dimension", String(dimension));
10180
10770
  }
10771
+ getStoredDimensionForCurrentModel() {
10772
+ const config = this.embeddingConfig;
10773
+ if (!config) {
10774
+ return null;
10775
+ }
10776
+ const stored = this.getEmbeddingMetadata();
10777
+ if (stored.model !== config.modelSpec || stored.dimension === null) {
10778
+ return null;
10779
+ }
10780
+ const dimension = Number(stored.dimension);
10781
+ return Number.isInteger(dimension) && dimension >= 1 ? dimension : null;
10782
+ }
10181
10783
  /**
10182
10784
  * Compares the configured embedding model and dimension against stored metadata.
10183
10785
  * Throws EmbeddingModelChangedError if either has changed since the last run.
@@ -10198,8 +10800,8 @@ class DocumentStore {
10198
10800
  if (stored.model === null) {
10199
10801
  return;
10200
10802
  }
10201
- const currentModel = this.config.app.embeddingModel;
10202
- const currentDimension = String(this.config.embeddings.vectorDimension);
10803
+ const currentModel = this.embeddingConfig.modelSpec;
10804
+ const currentDimension = String(this.dbDimension);
10203
10805
  const modelChanged = stored.model !== currentModel;
10204
10806
  const dimensionChanged = stored.dimension !== null && stored.dimension !== currentDimension;
10205
10807
  if (modelChanged || dimensionChanged) {
@@ -10269,72 +10871,153 @@ class DocumentStore {
10269
10871
  return;
10270
10872
  }
10271
10873
  try {
10272
- this.embeddings = createEmbeddingModel(config.modelSpec, {
10273
- requestTimeoutMs: this.config.embeddings.requestTimeoutMs,
10274
- vectorDimension: this.dbDimension
10275
- });
10276
- if (config.dimensions !== null) {
10277
- this.modelDimension = config.dimensions;
10278
- } else {
10279
- const testPromise = this.embeddings.embedQuery("test");
10280
- let timeoutId;
10281
- const timeoutPromise = new Promise((_, reject) => {
10282
- timeoutId = setTimeout(() => {
10283
- reject(
10284
- new Error(
10285
- `Embedding service connection timed out after ${this.embeddingInitTimeoutMs / 1e3} seconds`
10286
- )
10287
- );
10288
- }, this.embeddingInitTimeoutMs);
10289
- });
10290
- try {
10291
- const testVector = await Promise.race([testPromise, timeoutPromise]);
10292
- this.modelDimension = testVector.length;
10293
- } finally {
10294
- if (timeoutId !== void 0) {
10295
- clearTimeout(timeoutId);
10296
- }
10297
- }
10298
- EmbeddingConfig.setKnownModelDimensions(config.model, this.modelDimension);
10874
+ if (this.embeddings === null) {
10875
+ this.embeddings = this.createEmbeddingClient(this.dbDimension);
10299
10876
  }
10877
+ const modelDimension = this.modelDimension ?? this.dbDimension;
10300
10878
  if (this.embeddings instanceof FixedDimensionEmbeddings && this.embeddings.allowTruncate) {
10301
- this.modelDimension = Math.min(this.modelDimension, this.dbDimension);
10879
+ this.modelDimension = Math.min(modelDimension, this.dbDimension);
10880
+ } else {
10881
+ this.modelDimension = modelDimension;
10302
10882
  }
10303
10883
  if (this.modelDimension > this.dbDimension) {
10304
10884
  throw new DimensionError(config.modelSpec, this.modelDimension, this.dbDimension);
10305
10885
  }
10306
10886
  this.isVectorSearchEnabled = true;
10307
10887
  logger.debug(
10308
- `Embeddings initialized: ${config.provider}:${config.model} (${this.modelDimension}d)`
10888
+ `Embeddings initialized: ${config.provider}:${config.model} (${this.dbDimension}d)`
10309
10889
  );
10310
10890
  this.setEmbeddingMetadata(config.modelSpec, this.dbDimension);
10311
10891
  } catch (error) {
10312
- if (error instanceof Error) {
10313
- if (error.message.includes("does not exist") || error.message.includes("MODEL_NOT_FOUND")) {
10314
- throw new ModelConfigurationError(
10315
- `Invalid embedding model: ${config.model}
10316
- The model "${config.model}" is not available or you don't have access to it.
10317
- See README.md for supported models or run with --help for more details.`
10892
+ this.throwEmbeddingInitializationError(error, config);
10893
+ }
10894
+ }
10895
+ createEmbeddingClient(vectorDimension) {
10896
+ const config = this.embeddingConfig;
10897
+ if (!config) {
10898
+ throw new StoreError("Cannot create embedding client without configuration");
10899
+ }
10900
+ return createEmbeddingModel(config.modelSpec, {
10901
+ requestTimeoutMs: this.config.embeddings.requestTimeoutMs,
10902
+ vectorDimension
10903
+ });
10904
+ }
10905
+ async detectEmbeddingDimension(embeddings) {
10906
+ const testPromise = embeddings.embedQuery("test");
10907
+ let timeoutId;
10908
+ const timeoutPromise = new Promise((_, reject) => {
10909
+ timeoutId = setTimeout(() => {
10910
+ reject(
10911
+ new Error(
10912
+ `Embedding service connection timed out after ${this.embeddingInitTimeoutMs / 1e3} seconds`
10913
+ )
10914
+ );
10915
+ }, this.embeddingInitTimeoutMs);
10916
+ });
10917
+ try {
10918
+ const testVector = await Promise.race([testPromise, timeoutPromise]);
10919
+ return testVector.length;
10920
+ } finally {
10921
+ if (timeoutId !== void 0) {
10922
+ clearTimeout(timeoutId);
10923
+ }
10924
+ }
10925
+ }
10926
+ async resolveEffectiveEmbeddingDimension(options = {}) {
10927
+ this.validateVectorDimension(this.dbDimension);
10928
+ if (this.embeddingConfig === null || this.embeddingConfig === void 0) {
10929
+ return;
10930
+ }
10931
+ const config = this.embeddingConfig;
10932
+ if (!areCredentialsAvailable(config.provider)) {
10933
+ return;
10934
+ }
10935
+ try {
10936
+ const storedDimension = options.ignoreStoredMetadata ? null : this.getStoredDimensionForCurrentModel();
10937
+ if (storedDimension !== null) {
10938
+ if (!isVectorDimensionExplicit(this.config)) {
10939
+ this.dbDimension = storedDimension;
10940
+ }
10941
+ this.modelDimension = this.dbDimension;
10942
+ logger.debug(
10943
+ `Vector dimension loaded from metadata: ${this.dbDimension} for ${config.provider}:${config.model}`
10944
+ );
10945
+ return;
10946
+ }
10947
+ const stored = this.getEmbeddingMetadata();
10948
+ if (!options.ignoreStoredMetadata && stored.model !== null && stored.model !== config.modelSpec) {
10949
+ if (!isVectorDimensionExplicit(this.config) && config.dimensions !== null) {
10950
+ this.validateDetectedVectorDimension(
10951
+ config.dimensions,
10952
+ "known model dimension lookup"
10318
10953
  );
10954
+ this.dbDimension = config.dimensions;
10955
+ this.modelDimension = config.dimensions;
10319
10956
  }
10320
- if (error.message.includes("API key") || error.message.includes("401") || error.message.includes("authentication")) {
10321
- throw new ModelConfigurationError(
10322
- `Authentication failed for ${config.provider} embedding provider
10957
+ return;
10958
+ }
10959
+ let nativeDimension = config.dimensions;
10960
+ let nativeDimensionSource = "known model dimension lookup";
10961
+ if (nativeDimension === null) {
10962
+ this.embeddings = this.createEmbeddingClient(this.dbDimension);
10963
+ nativeDimension = await this.detectEmbeddingDimension(this.embeddings);
10964
+ nativeDimensionSource = "embedding provider probe";
10965
+ }
10966
+ this.validateDetectedVectorDimension(nativeDimension, nativeDimensionSource);
10967
+ if (config.dimensions === null) {
10968
+ EmbeddingConfig.setKnownModelDimensions(config.model, nativeDimension);
10969
+ }
10970
+ this.modelDimension = nativeDimension;
10971
+ if (!isVectorDimensionExplicit(this.config)) {
10972
+ this.dbDimension = nativeDimension;
10973
+ logger.info(
10974
+ `📐 Vector dimension auto-resolved to ${this.dbDimension} for ${config.provider}:${config.model}`
10975
+ );
10976
+ }
10977
+ } catch (error) {
10978
+ this.throwEmbeddingInitializationError(error, config);
10979
+ }
10980
+ }
10981
+ validateVectorDimension(dim) {
10982
+ if (typeof dim !== "number" || !Number.isInteger(dim) || dim < 1) {
10983
+ throw new StoreError(
10984
+ `Invalid embeddings.vectorDimension: ${dim}. Must be a positive integer.`
10985
+ );
10986
+ }
10987
+ }
10988
+ validateDetectedVectorDimension(dim, source) {
10989
+ if (typeof dim !== "number" || !Number.isInteger(dim) || dim < 1) {
10990
+ throw new StoreError(
10991
+ `Invalid detected embedding dimension from ${source}: ${dim}. Must be a positive integer.`
10992
+ );
10993
+ }
10994
+ }
10995
+ throwEmbeddingInitializationError(error, config) {
10996
+ if (error instanceof Error) {
10997
+ if (error.message.includes("does not exist") || error.message.includes("MODEL_NOT_FOUND")) {
10998
+ throw new ModelConfigurationError(
10999
+ `Invalid embedding model: ${config.model}
11000
+ The model "${config.model}" is not available or you don't have access to it.
11001
+ See README.md for supported models or run with --help for more details.`
11002
+ );
11003
+ }
11004
+ if (error.message.includes("API key") || error.message.includes("401") || error.message.includes("authentication")) {
11005
+ throw new ModelConfigurationError(
11006
+ `Authentication failed for ${config.provider} embedding provider
10323
11007
  Please check your API key configuration.
10324
11008
  See README.md for configuration options or run with --help for more details.`
10325
- );
10326
- }
10327
- if (error.message.includes("timed out") || error.message.includes("ECONNREFUSED") || error.message.includes("ENOTFOUND") || error.message.includes("ETIMEDOUT") || error.message.includes("ECONNRESET") || error.message.includes("network") || error.message.includes("fetch failed")) {
10328
- throw new ModelConfigurationError(
10329
- `Failed to connect to ${config.provider} embedding service
11009
+ );
11010
+ }
11011
+ if (error.message.includes("timed out") || error.message.includes("ECONNREFUSED") || error.message.includes("ENOTFOUND") || error.message.includes("ETIMEDOUT") || error.message.includes("ECONNRESET") || error.message.includes("network") || error.message.includes("fetch failed")) {
11012
+ throw new ModelConfigurationError(
11013
+ `Failed to connect to ${config.provider} embedding service
10330
11014
  ${error.message}
10331
11015
  Please check that the embedding service is running and accessible.
10332
11016
  If using a local model (e.g., Ollama), ensure the service is started.`
10333
- );
10334
- }
11017
+ );
10335
11018
  }
10336
- throw error;
10337
11019
  }
11020
+ throw error;
10338
11021
  }
10339
11022
  /**
10340
11023
  * Generates a safe FTS query by tokenizing the input and escaping for FTS5.
@@ -10413,6 +11096,7 @@ class DocumentStore {
10413
11096
  maxRetries: this.config.db.migrationMaxRetries,
10414
11097
  retryDelayMs: this.config.db.migrationRetryDelayMs
10415
11098
  });
11099
+ await this.resolveEffectiveEmbeddingDimension();
10416
11100
  this.checkEmbeddingModelChange();
10417
11101
  this.ensureVectorTable();
10418
11102
  this.prepareStatements();
@@ -10433,8 +11117,9 @@ class DocumentStore {
10433
11117
  * completed here after invalidation.
10434
11118
  */
10435
11119
  async resolveModelChange() {
11120
+ await this.resolveEffectiveEmbeddingDimension({ ignoreStoredMetadata: true });
10436
11121
  const currentModel = this.config.app.embeddingModel;
10437
- const currentDimension = this.config.embeddings.vectorDimension;
11122
+ const currentDimension = this.dbDimension;
10438
11123
  this.invalidateAllVectors(currentModel, currentDimension);
10439
11124
  this.ensureVectorTable();
10440
11125
  this.prepareStatements();
@@ -10459,12 +11144,8 @@ class DocumentStore {
10459
11144
  * and are handled by the model change detection system (checkEmbeddingModelChange).
10460
11145
  */
10461
11146
  ensureVectorTable() {
10462
- const dim = this.config.embeddings.vectorDimension;
10463
- if (typeof dim !== "number" || !Number.isInteger(dim) || dim < 1) {
10464
- throw new StoreError(
10465
- `Invalid embeddings.vectorDimension: ${dim}. Must be a positive integer.`
10466
- );
10467
- }
11147
+ const dim = this.dbDimension;
11148
+ this.validateVectorDimension(dim);
10468
11149
  const existingSql = this.db.prepare(
10469
11150
  "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'documents_vec';"
10470
11151
  ).get();
@@ -10774,14 +11455,19 @@ class DocumentStore {
10774
11455
  *
10775
11456
  * @param texts Array of texts to embed
10776
11457
  * @param isRetry Internal flag to prevent duplicate warning logs
11458
+ * @param hasTruncatedSingleText Whether a single text has already been truncated once
10777
11459
  * @returns Array of embedding vectors
10778
11460
  */
10779
- async embedDocumentsWithRetry(texts, isRetry = false) {
11461
+ async embedDocumentsWithRetry(texts, isRetry = false, hasTruncatedSingleText = false) {
10780
11462
  if (texts.length === 0) {
10781
11463
  return [];
10782
11464
  }
10783
11465
  try {
10784
- return await this.embeddings.embedDocuments(texts);
11466
+ const embeddings = this.embeddings;
11467
+ if (embeddings === null) {
11468
+ throw new StoreError("Embeddings are not initialized");
11469
+ }
11470
+ return await embeddings.embedDocuments(texts);
10785
11471
  } catch (error) {
10786
11472
  if (this.isInputSizeError(error)) {
10787
11473
  if (texts.length > 1) {
@@ -10794,11 +11480,14 @@ class DocumentStore {
10794
11480
  );
10795
11481
  }
10796
11482
  const [firstEmbeddings, secondEmbeddings] = await Promise.all([
10797
- this.embedDocumentsWithRetry(firstHalf, true),
10798
- this.embedDocumentsWithRetry(secondHalf, true)
11483
+ this.embedDocumentsWithRetry(firstHalf, true, false),
11484
+ this.embedDocumentsWithRetry(secondHalf, true, false)
10799
11485
  ]);
10800
11486
  return [...firstEmbeddings, ...secondEmbeddings];
10801
11487
  } else {
11488
+ if (hasTruncatedSingleText) {
11489
+ throw error;
11490
+ }
10802
11491
  const text = texts[0];
10803
11492
  const midpoint = Math.floor(text.length / 2);
10804
11493
  const firstHalf = text.substring(0, midpoint);
@@ -10808,7 +11497,7 @@ class DocumentStore {
10808
11497
  );
10809
11498
  }
10810
11499
  try {
10811
- const embedding = await this.embedDocumentsWithRetry([firstHalf], true);
11500
+ const embedding = await this.embedDocumentsWithRetry([firstHalf], true, true);
10812
11501
  return embedding;
10813
11502
  } catch (retryError) {
10814
11503
  logger.error(
@@ -11098,7 +11787,7 @@ class DocumentStore {
11098
11787
  return [];
11099
11788
  }
11100
11789
  const { id: versionId } = versionRow;
11101
- if (this.isVectorSearchEnabled) {
11790
+ if (this.isVectorSearchEnabled && this.embeddings !== null) {
11102
11791
  const rawEmbedding = await this.embeddings.embedQuery(query);
11103
11792
  const embedding = this.padVector(rawEmbedding);
11104
11793
  const overfetchLimit = Math.max(1, limit * this.searchOverfetchFactor);
@@ -12620,7 +13309,7 @@ const Layout = ({
12620
13309
  children,
12621
13310
  eventClientConfig
12622
13311
  }) => {
12623
- const versionString = version || "2.3.0";
13312
+ const versionString = version || "2.4.2";
12624
13313
  const versionInitializer = `versionUpdate({ currentVersion: ${`'${versionString}'`} })`;
12625
13314
  return /* @__PURE__ */ jsxs("html", { lang: "en", children: [
12626
13315
  /* @__PURE__ */ jsxs("head", { children: [
@@ -14906,7 +15595,7 @@ class AppServer {
14906
15595
  try {
14907
15596
  if (telemetry.isEnabled()) {
14908
15597
  telemetry.setGlobalContext({
14909
- appVersion: "2.3.0",
15598
+ appVersion: "2.4.2",
14910
15599
  appPlatform: process.platform,
14911
15600
  appNodeVersion: process.version,
14912
15601
  appServicesEnabled: this.getActiveServicesList(),
@@ -14941,7 +15630,7 @@ class AppServer {
14941
15630
  }
14942
15631
  await this.setupServer();
14943
15632
  try {
14944
- const address = await this.server.listen({
15633
+ await this.server.listen({
14945
15634
  port: this.serverConfig.port,
14946
15635
  host: this.appConfig.server.host
14947
15636
  });
@@ -14951,7 +15640,7 @@ class AppServer {
14951
15640
  if (this.remoteEventProxy) {
14952
15641
  this.remoteEventProxy.connect();
14953
15642
  }
14954
- this.logStartupInfo(address);
15643
+ this.logStartupInfo(this.getCanonicalOrigin());
14955
15644
  return this.server;
14956
15645
  } catch (error) {
14957
15646
  logger.error(`❌ Failed to start AppServer: ${error}`);
@@ -15227,10 +15916,18 @@ class AppServer {
15227
15916
  if (!this.authManager) {
15228
15917
  return;
15229
15918
  }
15230
- const baseUrl = new URL(`http://localhost:${this.serverConfig.port}`);
15919
+ const baseUrl = new URL(this.getCanonicalOrigin());
15231
15920
  this.authManager.registerRoutes(this.server, baseUrl);
15921
+ if (!this.appConfig.server.publicOrigin && isWildcardBindHost(this.appConfig.server.host)) {
15922
+ logger.warn(
15923
+ "⚠️ Authentication is enabled with a wildcard bind host and no public origin. Configure server.publicOrigin or --public-origin for remote OAuth clients."
15924
+ );
15925
+ }
15232
15926
  logger.debug("OAuth2 proxy endpoints registered");
15233
15927
  }
15928
+ getCanonicalOrigin() {
15929
+ return getCanonicalServerOrigin(this.appConfig, this.serverConfig.port);
15930
+ }
15234
15931
  /**
15235
15932
  * Log startup information showing which services are enabled.
15236
15933
  */
@@ -15429,6 +16126,94 @@ class PipelineClient {
15429
16126
  logger.debug("PipelineClient.setCallbacks called - no-op for external worker");
15430
16127
  }
15431
16128
  }
16129
+ const emptyLlmsTxtResult = () => ({
16130
+ sections: [],
16131
+ links: []
16132
+ });
16133
+ const markdownLinkPattern = /^\s*[-*+]\s+\[([^\]\n]+)]\(([^)\s]+)\)\s*(?::\s*(.+?)\s*)?$/;
16134
+ function isLlmsTxtUrl(url) {
16135
+ try {
16136
+ const basename = new URL(url).pathname.split("/").filter(Boolean).at(-1);
16137
+ return basename?.toLowerCase() === "llms.txt";
16138
+ } catch {
16139
+ return false;
16140
+ }
16141
+ }
16142
+ function parseLlmsTxt(content) {
16143
+ if (!content.trim() || content.includes("\0")) {
16144
+ return emptyLlmsTxtResult();
16145
+ }
16146
+ if (/^\s*<(?:!doctype\s+html|html|body|head)(?:\s|>)/i.test(content)) {
16147
+ return emptyLlmsTxtResult();
16148
+ }
16149
+ const lines = content.split(/\r?\n/);
16150
+ const firstH1Index = lines.findIndex((line) => /^#\s+\S/.test(line));
16151
+ if (firstH1Index === -1) {
16152
+ return emptyLlmsTxtResult();
16153
+ }
16154
+ const projectName = lines[firstH1Index].replace(/^#\s+/, "").trim();
16155
+ if (!projectName) {
16156
+ return emptyLlmsTxtResult();
16157
+ }
16158
+ const result = {
16159
+ projectName,
16160
+ sections: [],
16161
+ links: []
16162
+ };
16163
+ let currentSection;
16164
+ const summaryLines = [];
16165
+ let collectingSummary = true;
16166
+ for (const line of lines.slice(firstH1Index + 1)) {
16167
+ if (/^#\s+\S/.test(line)) {
16168
+ collectingSummary = false;
16169
+ continue;
16170
+ }
16171
+ const h2Match = /^##\s+(.+?)\s*$/.exec(line);
16172
+ if (h2Match) {
16173
+ collectingSummary = false;
16174
+ const title = h2Match[1].trim();
16175
+ currentSection = {
16176
+ title,
16177
+ optional: title.toLowerCase() === "optional",
16178
+ links: []
16179
+ };
16180
+ result.sections.push(currentSection);
16181
+ continue;
16182
+ }
16183
+ if (collectingSummary) {
16184
+ if (/^>\s?/.test(line)) {
16185
+ summaryLines.push(line.replace(/^>\s?/, "").trim());
16186
+ continue;
16187
+ }
16188
+ if (summaryLines.length > 0 && line.trim() === "") {
16189
+ continue;
16190
+ }
16191
+ if (line.trim() !== "") {
16192
+ collectingSummary = false;
16193
+ }
16194
+ }
16195
+ const linkMatch = markdownLinkPattern.exec(line);
16196
+ if (!linkMatch) {
16197
+ continue;
16198
+ }
16199
+ const link = {
16200
+ title: linkMatch[1].trim(),
16201
+ url: linkMatch[2].trim(),
16202
+ optional: currentSection?.optional ?? false,
16203
+ ...currentSection ? { section: currentSection.title } : {},
16204
+ ...linkMatch[3]?.trim() ? { description: linkMatch[3].trim() } : {}
16205
+ };
16206
+ currentSection?.links.push(link);
16207
+ result.links.push(link);
16208
+ }
16209
+ if (summaryLines.length > 0) {
16210
+ result.summary = summaryLines.join("\n");
16211
+ }
16212
+ if (result.links.length === 0) {
16213
+ return emptyLlmsTxtResult();
16214
+ }
16215
+ return result;
16216
+ }
15432
16217
  const INDEX_FILE_PATTERN = /^index(\.[a-z0-9]+)?$/i;
15433
16218
  function computeBaseDirectory(pathname) {
15434
16219
  if (pathname === "" || pathname === "/") return "/";
@@ -15530,6 +16315,9 @@ class BaseScraperStrategy {
15530
16315
  * crawl queue entirely.
15531
16316
  */
15532
16317
  shouldProcessUrl(url, options, context = {}) {
16318
+ if (isLlmsTxtUrl(url)) {
16319
+ return false;
16320
+ }
15533
16321
  const isInternalArchiveMember = url.startsWith("file://") && isFileUrlInsideRoots(url, context.internalAllowedFileRoots);
15534
16322
  if (!isInternalArchiveMember) {
15535
16323
  const scope = options.scope ?? "subpages";
@@ -15631,11 +16419,17 @@ class BaseScraperStrategy {
15631
16419
  this.recordChildPageCompletion(item, result);
15632
16420
  ensureFailureRateWithinThreshold();
15633
16421
  throwIfBatchAborted();
15634
- return [];
16422
+ return result.queueItems ?? [];
15635
16423
  }
15636
16424
  if (result.status === FetchStatus.NOT_FOUND) {
15637
16425
  const isRefreshDeletion = this.isRefreshDeletion(item, result);
15638
- if (item.depth === 0 && !isRefreshDeletion) {
16426
+ const fallbackQueueItems = result.queueItems ?? [];
16427
+ const hasNewFallbackQueueItem = fallbackQueueItems.some(
16428
+ (queueItem) => !this.visited.has(
16429
+ normalizeUrl(queueItem.url, this.getUrlNormalizerOptions(options))
16430
+ )
16431
+ );
16432
+ if (item.depth === 0 && !isRefreshDeletion && !hasNewFallbackQueueItem) {
15639
16433
  throw new ScraperError(`Root page not found: ${item.url}`, false);
15640
16434
  }
15641
16435
  if (!isRefreshDeletion) {
@@ -15660,7 +16454,7 @@ class BaseScraperStrategy {
15660
16454
  }
15661
16455
  await progressCallback(progress);
15662
16456
  }
15663
- return [];
16457
+ return fallbackQueueItems;
15664
16458
  }
15665
16459
  if (result.status !== FetchStatus.SUCCESS) {
15666
16460
  logger.error(`❌ Unknown fetch status: ${result.status}`);
@@ -15697,7 +16491,7 @@ class BaseScraperStrategy {
15697
16491
  this.recordChildPageCompletion(item, result);
15698
16492
  ensureFailureRateWithinThreshold();
15699
16493
  throwIfBatchAborted();
15700
- return nextItems.map((value) => {
16494
+ const linkQueueItems = nextItems.map((value) => {
15701
16495
  try {
15702
16496
  const targetUrl = new URL$1(value, linkBaseUrl);
15703
16497
  if (!this.shouldProcessUrl(targetUrl.href, options, {
@@ -15715,6 +16509,7 @@ class BaseScraperStrategy {
15715
16509
  }
15716
16510
  return null;
15717
16511
  }).filter((item2) => item2 !== null);
16512
+ return [...result.queueItems ?? [], ...linkQueueItems];
15718
16513
  } catch (error) {
15719
16514
  if (error instanceof FailureThresholdExceededError || error instanceof CancellationError) {
15720
16515
  throw error;
@@ -17053,6 +17848,7 @@ class WebScraperStrategy extends BaseScraperStrategy {
17053
17848
  localFileStrategy;
17054
17849
  tempFiles = [];
17055
17850
  siblingwiseRedirectWarned = false;
17851
+ pendingLlmsTxtProbe = null;
17056
17852
  constructor(config, options = {}) {
17057
17853
  super(config, { urlNormalizerOptions: options.urlNormalizerOptions });
17058
17854
  this.shouldFollowLinkFn = options.shouldFollowLink;
@@ -17086,6 +17882,152 @@ class WebScraperStrategy extends BaseScraperStrategy {
17086
17882
  return actualUrl;
17087
17883
  }
17088
17884
  // Removed custom isInScope logic; using shared scope utility for consistent behavior
17885
+ createFetchOptions(item, options, signal) {
17886
+ return {
17887
+ signal,
17888
+ followRedirects: options.followRedirects,
17889
+ headers: options.headers,
17890
+ etag: item.etag,
17891
+ ...item.internalAllowedFileRoots ? { internalAllowedFileRoots: item.internalAllowedFileRoots } : {}
17892
+ };
17893
+ }
17894
+ buildMarkdownVariantUrl(url) {
17895
+ const variant = new URL(url);
17896
+ if (variant.pathname.endsWith("/")) {
17897
+ variant.pathname = `${variant.pathname}index.html.md`;
17898
+ return variant.toString();
17899
+ }
17900
+ const lastSegment = variant.pathname.split("/").at(-1) ?? "";
17901
+ if (lastSegment.includes(".")) {
17902
+ variant.pathname = `${variant.pathname}.md`;
17903
+ return variant.toString();
17904
+ }
17905
+ variant.pathname = `${variant.pathname}/index.html.md`;
17906
+ return variant.toString();
17907
+ }
17908
+ isAcceptableMarkdownVariant(rawContent) {
17909
+ const mimeType = rawContent.mimeType.toLowerCase();
17910
+ return MimeTypeUtils.isMarkdown(mimeType) || mimeType === "text/plain";
17911
+ }
17912
+ isMarkdownUrl(url) {
17913
+ const mimeType = MimeTypeUtils.detectMimeTypeFromPath(url);
17914
+ return mimeType ? MimeTypeUtils.isMarkdown(mimeType) : false;
17915
+ }
17916
+ async fetchItemContent(item, options, signal) {
17917
+ const fetchOptions = this.createFetchOptions(item, options, signal);
17918
+ if (!item.fromLlmsTxt || this.isMarkdownUrl(item.url)) {
17919
+ return this.fetcher.fetch(item.url, fetchOptions);
17920
+ }
17921
+ const markdownVariantUrl = this.buildMarkdownVariantUrl(item.url);
17922
+ try {
17923
+ const markdownContent = await this.fetcher.fetch(markdownVariantUrl, fetchOptions);
17924
+ if (markdownContent.status === FetchStatus.SUCCESS && this.isAcceptableMarkdownVariant(markdownContent)) {
17925
+ logger.debug(
17926
+ `llms.txt Markdown URL preference succeeded: ${item.url} -> ${markdownVariantUrl}`
17927
+ );
17928
+ return MimeTypeUtils.isMarkdown(markdownContent.mimeType) ? markdownContent : { ...markdownContent, mimeType: "text/markdown" };
17929
+ }
17930
+ logger.debug(
17931
+ `llms.txt Markdown URL preference fell back for ${item.url}: ${markdownVariantUrl} returned status=${markdownContent.status}, contentType=${markdownContent.mimeType}`
17932
+ );
17933
+ } catch (error) {
17934
+ logger.debug(
17935
+ `llms.txt Markdown URL preference fell back for ${item.url}: ${error}`
17936
+ );
17937
+ }
17938
+ return this.fetcher.fetch(item.url, fetchOptions);
17939
+ }
17940
+ getLlmsTxtCandidates(baseUrl, inputUrl) {
17941
+ const input = new URL(inputUrl);
17942
+ const parentPath = input.pathname.endsWith("/") ? input.pathname : input.pathname.slice(0, input.pathname.lastIndexOf("/") + 1);
17943
+ input.pathname = `${parentPath}llms.txt`.replace(/\/+/g, "/");
17944
+ input.search = "";
17945
+ input.hash = "";
17946
+ const root = new URL(baseUrl);
17947
+ root.pathname = "/llms.txt";
17948
+ root.search = "";
17949
+ root.hash = "";
17950
+ return [.../* @__PURE__ */ new Set([input.toString(), root.toString()])];
17951
+ }
17952
+ /**
17953
+ * Probes for an llms.txt file using the existing fetcher and access policy.
17954
+ * @param baseUrl The site base URL used for the root fallback probe.
17955
+ * @param inputUrl The original input URL used for the subpath probe.
17956
+ * @param options Scraper options to apply to probe requests.
17957
+ * @param signal Optional abort signal.
17958
+ * @returns The first valid llms.txt result, or null when none is available.
17959
+ */
17960
+ async probeLlmsTxt(baseUrl, inputUrl, options, signal) {
17961
+ for (const candidate of this.getLlmsTxtCandidates(baseUrl, inputUrl)) {
17962
+ try {
17963
+ const rawContent = await this.fetcher.fetch(
17964
+ candidate,
17965
+ this.createFetchOptions({ url: candidate, depth: 0 }, options, signal)
17966
+ );
17967
+ if (rawContent.status !== FetchStatus.SUCCESS) {
17968
+ logger.debug(`llms.txt probe failed for ${candidate}: ${rawContent.status}`);
17969
+ continue;
17970
+ }
17971
+ const result = parseLlmsTxt(
17972
+ convertToString(rawContent.content, rawContent.charset)
17973
+ );
17974
+ if (result.links.length === 0) {
17975
+ logger.debug(`llms.txt probe failed for ${candidate}: invalid content`);
17976
+ continue;
17977
+ }
17978
+ logger.info(
17979
+ `📄 Detected llms.txt at ${rawContent.source} (${result.links.length} URLs)`
17980
+ );
17981
+ return { url: rawContent.source, result };
17982
+ } catch (error) {
17983
+ logger.debug(`llms.txt probe failed for ${candidate}: ${error}`);
17984
+ }
17985
+ }
17986
+ return null;
17987
+ }
17988
+ createLlmsTxtQueueItems(options, probe) {
17989
+ const items = [];
17990
+ for (const link of probe.result.links) {
17991
+ try {
17992
+ const targetUrl = new URL(link.url, probe.url);
17993
+ if (targetUrl.protocol !== "http:" && targetUrl.protocol !== "https:") {
17994
+ continue;
17995
+ }
17996
+ if (!this.shouldProcessUrl(targetUrl.href, options)) {
17997
+ continue;
17998
+ }
17999
+ if (this.shouldFollowLinkFn) {
18000
+ const baseUrl = this.canonicalBaseUrl ?? new URL(options.url);
18001
+ if (!this.shouldFollowLinkFn(baseUrl, targetUrl)) {
18002
+ continue;
18003
+ }
18004
+ }
18005
+ items.push({ url: targetUrl.href, depth: 0, fromLlmsTxt: true });
18006
+ } catch {
18007
+ }
18008
+ }
18009
+ return items;
18010
+ }
18011
+ consumePendingLlmsTxtQueueItems(item, options) {
18012
+ if (item.depth !== 0) {
18013
+ return [];
18014
+ }
18015
+ const probe = this.pendingLlmsTxtProbe;
18016
+ this.pendingLlmsTxtProbe = null;
18017
+ return probe ? this.createLlmsTxtQueueItems(options, probe) : [];
18018
+ }
18019
+ updateCanonicalBaseUrl(effectiveSource, options) {
18020
+ const final = new URL(effectiveSource);
18021
+ const userPath = new URL(options.url).pathname;
18022
+ if (!isPathDescendant(userPath, final.pathname) && !this.siblingwiseRedirectWarned) {
18023
+ logger.warn(
18024
+ `⚠️ 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.`
18025
+ );
18026
+ this.siblingwiseRedirectWarned = true;
18027
+ }
18028
+ final.pathname = userPath;
18029
+ this.canonicalBaseUrl = final;
18030
+ }
17089
18031
  /**
17090
18032
  * Processes a single queue item by fetching its content and processing it through pipelines.
17091
18033
  * @param item - The queue item to process.
@@ -17097,6 +18039,10 @@ class WebScraperStrategy extends BaseScraperStrategy {
17097
18039
  async processItem(item, options, signal) {
17098
18040
  const { url } = item;
17099
18041
  try {
18042
+ if (isLlmsTxtUrl(url)) {
18043
+ logger.debug(`Skipping llms.txt meta-file: ${url}`);
18044
+ return { url, links: [], status: FetchStatus.SUCCESS };
18045
+ }
17100
18046
  if (item.etag) {
17101
18047
  logger.debug(`Processing ${url} with stored ETag: ${item.etag}`);
17102
18048
  }
@@ -17106,23 +18052,28 @@ class WebScraperStrategy extends BaseScraperStrategy {
17106
18052
  return this.processRootArchive(item, options, signal);
17107
18053
  }
17108
18054
  }
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);
18055
+ const rawContent = await this.fetchItemContent(item, options, signal);
17119
18056
  const effectiveSource = options.preserveHashes ? this.restorePreservedHash(url, rawContent.source) : rawContent.source;
18057
+ if (item.depth === 0) {
18058
+ this.updateCanonicalBaseUrl(effectiveSource, options);
18059
+ }
18060
+ const llmsTxtQueueItems = this.consumePendingLlmsTxtQueueItems(item, options);
17120
18061
  logger.debug(
17121
18062
  `Fetch result for ${url}: status=${rawContent.status}, etag=${rawContent.etag || "none"}`
17122
18063
  );
17123
18064
  if (rawContent.status !== FetchStatus.SUCCESS) {
17124
18065
  logger.debug(`Skipping pipeline for ${url} due to status: ${rawContent.status}`);
17125
- return { url: effectiveSource, links: [], status: rawContent.status };
18066
+ return {
18067
+ url: effectiveSource,
18068
+ links: [],
18069
+ queueItems: llmsTxtQueueItems,
18070
+ status: rawContent.status
18071
+ };
18072
+ }
18073
+ if (MimeTypeUtils.isMarkdown(rawContent.mimeType)) {
18074
+ logger.debug(
18075
+ `Server provided Markdown content for ${url} via content negotiation or Markdown URL (${rawContent.mimeType})`
18076
+ );
17126
18077
  }
17127
18078
  let processed;
17128
18079
  for (const pipeline of this.pipelines) {
@@ -17143,53 +18094,43 @@ class WebScraperStrategy extends BaseScraperStrategy {
17143
18094
  logger.warn(
17144
18095
  `⚠️ Unsupported content type "${rawContent.mimeType}" for URL ${url}. Skipping processing.`
17145
18096
  );
17146
- return { url: effectiveSource, links: [], status: FetchStatus.SUCCESS };
18097
+ return {
18098
+ url: effectiveSource,
18099
+ links: [],
18100
+ queueItems: llmsTxtQueueItems,
18101
+ status: FetchStatus.SUCCESS
18102
+ };
17147
18103
  }
17148
18104
  for (const err of processed.errors ?? []) {
17149
18105
  logger.warn(`⚠️ Processing error for ${url}: ${err.message}`);
17150
18106
  }
17151
- if (!processed.textContent || !processed.textContent.trim()) {
18107
+ if (!processed.textContent?.trim()) {
17152
18108
  logger.warn(
17153
18109
  `⚠️ No processable content found for ${url} after pipeline execution.`
17154
18110
  );
17155
18111
  return {
17156
18112
  url: effectiveSource,
17157
18113
  links: processed.links,
18114
+ queueItems: llmsTxtQueueItems,
17158
18115
  status: FetchStatus.SUCCESS
17159
18116
  };
17160
18117
  }
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) => {
18118
+ const filteredLinks = processed.links?.flatMap((link) => {
17178
18119
  try {
17179
- const targetUrl = new URL(link);
18120
+ const targetUrl = new URL(link, effectiveSource);
17180
18121
  if (/\.(zip|tar|gz|tgz)$/i.test(targetUrl.pathname)) {
17181
- return false;
18122
+ return [];
17182
18123
  }
17183
18124
  if (!this.shouldProcessUrl(targetUrl.href, options)) {
17184
- return false;
18125
+ return [];
17185
18126
  }
17186
18127
  if (this.shouldFollowLinkFn) {
17187
18128
  const baseUrl = this.canonicalBaseUrl ?? new URL(options.url);
17188
- return this.shouldFollowLinkFn(baseUrl, targetUrl);
18129
+ return this.shouldFollowLinkFn(baseUrl, targetUrl) ? [targetUrl.href] : [];
17189
18130
  }
17190
- return true;
18131
+ return [targetUrl.href];
17191
18132
  } catch {
17192
- return false;
18133
+ return [];
17193
18134
  }
17194
18135
  }) ?? [];
17195
18136
  return {
@@ -17200,6 +18141,7 @@ class WebScraperStrategy extends BaseScraperStrategy {
17200
18141
  contentType: processed.contentType || rawContent.mimeType,
17201
18142
  content: processed,
17202
18143
  links: filteredLinks,
18144
+ queueItems: llmsTxtQueueItems,
17203
18145
  status: FetchStatus.SUCCESS
17204
18146
  };
17205
18147
  } catch (error) {
@@ -17207,6 +18149,16 @@ class WebScraperStrategy extends BaseScraperStrategy {
17207
18149
  throw error;
17208
18150
  }
17209
18151
  }
18152
+ async scrape(options, progressCallback, signal) {
18153
+ this.pendingLlmsTxtProbe = null;
18154
+ this.pendingLlmsTxtProbe = await this.probeLlmsTxt(
18155
+ options.url,
18156
+ options.url,
18157
+ options,
18158
+ signal
18159
+ );
18160
+ await super.scrape(options, progressCallback, signal);
18161
+ }
17210
18162
  async processRootArchive(item, options, signal) {
17211
18163
  logger.info(`📦 Downloading root archive: ${item.url}`);
17212
18164
  const rawContent = await this.fetcher.fetch(item.url, {
@@ -18213,6 +19165,10 @@ function createDefaultAction(cli) {
18213
19165
  }).option("host", {
18214
19166
  type: "string",
18215
19167
  description: "Host to bind the server to"
19168
+ }).option("public-origin", {
19169
+ type: "string",
19170
+ description: "Public origin advertised to clients (e.g., https://docs.example.com)",
19171
+ alias: "publicOrigin"
18216
19172
  }).option("embedding-model", {
18217
19173
  type: "string",
18218
19174
  description: "Embedding model configuration (e.g., 'openai:text-embedding-3-small')",
@@ -18504,6 +19460,10 @@ function createMcpCommand(cli) {
18504
19460
  }).option("host", {
18505
19461
  type: "string",
18506
19462
  description: "Host to bind the MCP server to"
19463
+ }).option("public-origin", {
19464
+ type: "string",
19465
+ description: "Public origin advertised to clients (e.g., https://docs.example.com)",
19466
+ alias: "publicOrigin"
18507
19467
  }).option("embedding-model", {
18508
19468
  type: "string",
18509
19469
  description: "Embedding model configuration (e.g., 'openai:text-embedding-3-small')",
@@ -19108,6 +20068,10 @@ function createWebCommand(cli) {
19108
20068
  }).option("host", {
19109
20069
  type: "string",
19110
20070
  description: "Host to bind the web interface to"
20071
+ }).option("public-origin", {
20072
+ type: "string",
20073
+ description: "Public origin advertised to clients (e.g., https://docs.example.com)",
20074
+ alias: "publicOrigin"
19111
20075
  }).option("embedding-model", {
19112
20076
  type: "string",
19113
20077
  description: "Embedding model configuration (e.g., 'openai:text-embedding-3-small')",
@@ -19198,6 +20162,10 @@ function createWorkerCommand(cli) {
19198
20162
  }).option("host", {
19199
20163
  type: "string",
19200
20164
  description: "Host to bind the worker API to"
20165
+ }).option("public-origin", {
20166
+ type: "string",
20167
+ description: "Public origin advertised to clients (e.g., https://docs.example.com)",
20168
+ alias: "publicOrigin"
19201
20169
  }).option("embedding-model", {
19202
20170
  type: "string",
19203
20171
  description: "Embedding model configuration (e.g., 'openai:text-embedding-3-small')",
@@ -19276,7 +20244,7 @@ function createCli(argv) {
19276
20244
  let globalEventBus = null;
19277
20245
  let globalTelemetryService = null;
19278
20246
  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", {
20247
+ const cli = registerGlobalOutputOptions(yargs(hideBin(argv))).scriptName("docs-mcp-server").strict().usage("Usage: $0 <command> [options]").version("2.4.2").option("verbose", {
19280
20248
  type: "boolean",
19281
20249
  description: "Enable verbose (debug) logging",
19282
20250
  default: false
@@ -19337,7 +20305,7 @@ function createCli(argv) {
19337
20305
  if (shouldEnableTelemetry() && telemetry.isEnabled()) {
19338
20306
  const commandName = argv2._[0]?.toString() || "default";
19339
20307
  telemetry.setGlobalContext({
19340
- appVersion: "2.3.0",
20308
+ appVersion: "2.4.2",
19341
20309
  appPlatform: process.platform,
19342
20310
  appNodeVersion: process.version,
19343
20311
  appInterface: "cli",
@@ -19483,4 +20451,4 @@ export {
19483
20451
  cleanupCliCommand,
19484
20452
  runCli
19485
20453
  };
19486
- //# sourceMappingURL=main-CCLTqj8g.js.map
20454
+ //# sourceMappingURL=main-WZKPkgC6.js.map