@arabold/docs-mcp-server 2.4.5 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/assets/index-BHI6XhAh.css +1 -0
  2. package/dist/assets/index-vmw9lu8_.js +70 -0
  3. package/dist/assets/index-vmw9lu8_.js.map +1 -0
  4. package/dist/index.html +14 -0
  5. package/dist/index.js +1 -1
  6. package/dist/{main-D89k01Wy.js → main-qq21CGPf.js} +722 -2659
  7. package/dist/main-qq21CGPf.js.map +1 -0
  8. package/dist/{utils-B-zX5sgp.js → utils-DCwrdF5w.js} +2 -12
  9. package/dist/utils-DCwrdF5w.js.map +1 -0
  10. package/dist/{utils-LjYa0nIu.js → utils-DizElQoU.js} +1 -1
  11. package/package.json +11 -17
  12. package/public/assets/index-BHI6XhAh.css +1 -0
  13. package/public/assets/index-vmw9lu8_.js +70 -0
  14. package/public/assets/index-vmw9lu8_.js.map +1 -0
  15. package/public/index.html +14 -0
  16. package/dist/assets/android-icon-144x144.png +0 -0
  17. package/dist/assets/android-icon-192x192.png +0 -0
  18. package/dist/assets/android-icon-36x36.png +0 -0
  19. package/dist/assets/android-icon-48x48.png +0 -0
  20. package/dist/assets/android-icon-72x72.png +0 -0
  21. package/dist/assets/android-icon-96x96.png +0 -0
  22. package/dist/assets/apple-icon-114x114.png +0 -0
  23. package/dist/assets/apple-icon-120x120.png +0 -0
  24. package/dist/assets/apple-icon-144x144.png +0 -0
  25. package/dist/assets/apple-icon-152x152.png +0 -0
  26. package/dist/assets/apple-icon-180x180.png +0 -0
  27. package/dist/assets/apple-icon-57x57.png +0 -0
  28. package/dist/assets/apple-icon-60x60.png +0 -0
  29. package/dist/assets/apple-icon-72x72.png +0 -0
  30. package/dist/assets/apple-icon-76x76.png +0 -0
  31. package/dist/assets/apple-icon-precomposed.png +0 -0
  32. package/dist/assets/apple-icon.png +0 -0
  33. package/dist/assets/favicon-16x16.png +0 -0
  34. package/dist/assets/favicon-32x32.png +0 -0
  35. package/dist/assets/favicon-96x96.png +0 -0
  36. package/dist/assets/favicon.ico +0 -0
  37. package/dist/assets/main.css +0 -3
  38. package/dist/assets/main.js +0 -8678
  39. package/dist/assets/main.js.map +0 -1
  40. package/dist/assets/manifest.json +0 -47
  41. package/dist/assets/ms-icon-144x144.png +0 -0
  42. package/dist/assets/ms-icon-150x150.png +0 -0
  43. package/dist/assets/ms-icon-310x310.png +0 -0
  44. package/dist/assets/ms-icon-70x70.png +0 -0
  45. package/dist/main-D89k01Wy.js.map +0 -1
  46. package/dist/utils-B-zX5sgp.js.map +0 -1
  47. package/public/assets/android-icon-144x144.png +0 -0
  48. package/public/assets/android-icon-192x192.png +0 -0
  49. package/public/assets/android-icon-36x36.png +0 -0
  50. package/public/assets/android-icon-48x48.png +0 -0
  51. package/public/assets/android-icon-72x72.png +0 -0
  52. package/public/assets/android-icon-96x96.png +0 -0
  53. package/public/assets/apple-icon-114x114.png +0 -0
  54. package/public/assets/apple-icon-120x120.png +0 -0
  55. package/public/assets/apple-icon-144x144.png +0 -0
  56. package/public/assets/apple-icon-152x152.png +0 -0
  57. package/public/assets/apple-icon-180x180.png +0 -0
  58. package/public/assets/apple-icon-57x57.png +0 -0
  59. package/public/assets/apple-icon-60x60.png +0 -0
  60. package/public/assets/apple-icon-72x72.png +0 -0
  61. package/public/assets/apple-icon-76x76.png +0 -0
  62. package/public/assets/apple-icon-precomposed.png +0 -0
  63. package/public/assets/apple-icon.png +0 -0
  64. package/public/assets/favicon-16x16.png +0 -0
  65. package/public/assets/favicon-32x32.png +0 -0
  66. package/public/assets/favicon-96x96.png +0 -0
  67. package/public/assets/favicon.ico +0 -0
  68. package/public/assets/main.css +0 -3
  69. package/public/assets/main.js +0 -8678
  70. package/public/assets/main.js.map +0 -1
  71. package/public/assets/manifest.json +0 -47
  72. package/public/assets/ms-icon-144x144.png +0 -0
  73. package/public/assets/ms-icon-150x150.png +0 -0
  74. package/public/assets/ms-icon-310x310.png +0 -0
  75. package/public/assets/ms-icon-70x70.png +0 -0
@@ -1,6 +1,6 @@
1
1
  import { t as normalizeEnvValue } from "./env-DONvEfR5.js";
2
2
  import { i as setLogLevel, n as getLogLevelFromEnv, r as logger, t as LogLevel } from "./logger-BBxstTD7.js";
3
- import { C as EventType, D as resolveStorePath, E as getProjectRoot, S as PipelineJobStatus, T as shouldEnableTelemetry, _ as EventBusService, b as initTelemetry, c as parseHeaders, d as validateAuthConfig, f as validateHost, g as EmbeddingConfig, h as warnHttpUsage, i as getEventBus, o as handleEmbeddingModelChange, p as validatePort, r as ensurePlaywrightBrowsersInstalled, s as parseAuthConfig, t as createAppServerConfig, u as resolveProtocol, v as TelemetryService, w as ServerEventName, x as telemetry, y as TelemetryEvent } from "./utils-B-zX5sgp.js";
3
+ import { C as EventType, E as resolveStorePath, S as PipelineJobStatus, T as getProjectRoot, _ as EventBusService, b as initTelemetry, c as parseHeaders, d as validateAuthConfig, f as validateHost, g as EmbeddingConfig, h as warnHttpUsage, i as getEventBus, o as handleEmbeddingModelChange, p as validatePort, r as ensurePlaywrightBrowsersInstalled, s as parseAuthConfig, t as createAppServerConfig, u as resolveProtocol, v as TelemetryService, w as shouldEnableTelemetry, x as telemetry, y as TelemetryEvent } from "./utils-DCwrdF5w.js";
4
4
  import { BedrockEmbeddings } from "@langchain/aws";
5
5
  import { GoogleGenerativeAIEmbeddings } from "@langchain/google-genai";
6
6
  import { VertexAIEmbeddings } from "@langchain/google-vertexai";
@@ -16,6 +16,7 @@ import { hideBin } from "yargs/helpers";
16
16
  import yaml from "yaml";
17
17
  import { z } from "zod";
18
18
  import { encode } from "@toon-format/toon";
19
+ import fs$1, { readFile } from "node:fs/promises";
19
20
  import formBody from "@fastify/formbody";
20
21
  import fastifyStatic from "@fastify/static";
21
22
  import Fastify from "fastify";
@@ -30,7 +31,6 @@ import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mc
30
31
  import { z as z$1 } from "zod/v3";
31
32
  import { chromium } from "playwright";
32
33
  import { lookup } from "node:dns/promises";
33
- import fs$1 from "node:fs/promises";
34
34
  import net from "node:net";
35
35
  import os from "node:os";
36
36
  import { minimatch } from "minimatch";
@@ -38,7 +38,7 @@ import mime from "mime";
38
38
  import { HeaderGenerator } from "header-generator";
39
39
  import https from "node:https";
40
40
  import axios from "axios";
41
- import { extractBytes } from "@kreuzberg/node";
41
+ import { ExtractInputKind, OutputFormat, extract } from "@xberg-io/xberg";
42
42
  import { JSDOM, VirtualConsole } from "jsdom";
43
43
  import psl from "psl";
44
44
  import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";
@@ -59,13 +59,10 @@ import semver from "semver";
59
59
  import Fuse from "fuse.js";
60
60
  import Database from "better-sqlite3";
61
61
  import * as sqliteVec from "sqlite-vec";
62
- import { initTRPC } from "@trpc/server";
63
62
  import { fastifyTRPCPlugin } from "@trpc/server/adapters/fastify";
64
63
  import { applyWSSHandler } from "@trpc/server/adapters/ws";
64
+ import { initTRPC } from "@trpc/server";
65
65
  import { observable } from "@trpc/server/observable";
66
- import { Fragment, jsx, jsxs } from "@kitajs/html/jsx-runtime";
67
- import DOMPurify from "dompurify";
68
- import { escapeHtml } from "@kitajs/html";
69
66
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
70
67
  import { v4 } from "uuid";
71
68
  import { exec } from "node:child_process";
@@ -2348,6 +2345,17 @@ var ARCHIVE_EXTENSIONS = /* @__PURE__ */ new Set([
2348
2345
  ".tgz"
2349
2346
  ]);
2350
2347
  /**
2348
+ * Where users go to change file access decisions.
2349
+ *
2350
+ * Rejections state which rule blocked the path and point here, rather than
2351
+ * naming individual settings and environment variables. Every setting named in
2352
+ * an error is one more thing a rename can silently invalidate, and the docs
2353
+ * carry the full picture — config file, env vars, and tokens — in one place
2354
+ * that is already maintained. Deep-linked without an anchor on purpose: a stale
2355
+ * anchor fails quietly.
2356
+ */
2357
+ var FILE_ACCESS_DOCS = "https://github.com/arabold/docs-mcp-server/blob/main/docs/setup/configuration.md";
2358
+ /**
2351
2359
  * Shared access policy for outbound network and local file access.
2352
2360
  */
2353
2361
  var ScraperAccessPolicy = class {
@@ -2355,6 +2363,10 @@ var ScraperAccessPolicy = class {
2355
2363
  allowedCidrs = new net.BlockList();
2356
2364
  specialUseCidrs = new net.BlockList();
2357
2365
  allowedHosts;
2366
+ /** Roots already reported as unresolvable, so each is warned about once. */
2367
+ warnedUnresolvedRoots = /* @__PURE__ */ new Set();
2368
+ hasWarnedUnavailableAllowlist = false;
2369
+ hasLoggedConfiguredRoots = false;
2358
2370
  constructor(security) {
2359
2371
  this.security = security;
2360
2372
  this.allowedHosts = security.network.allowedHosts;
@@ -2407,6 +2419,15 @@ var ScraperAccessPolicy = class {
2407
2419
  }
2408
2420
  /**
2409
2421
  * Resolves and validates a file URL against the configured file access policy.
2422
+ *
2423
+ * Rejections name the specific policy rule that blocked the path and link to
2424
+ * the configuration documentation rather than naming individual settings.
2425
+ * Filesystem paths — configured or resolved — stay out of the thrown message
2426
+ * because it reaches MCP clients and the web UI; they are logged instead,
2427
+ * where only the operator sees them. Root tokens such as `$DOCUMENTS` are
2428
+ * named in the message: they are runtime state rather than host detail, and
2429
+ * warn-level logs are suppressed on the non-interactive runs where an
2430
+ * unresolvable token is most likely.
2410
2431
  */
2411
2432
  async resolveFileAccess(url, additionalAllowedRoots = []) {
2412
2433
  const filePath = fileUrlToPathLoose(url);
@@ -2415,19 +2436,25 @@ var ScraperAccessPolicy = class {
2415
2436
  const bypassRoots = await this.expandRoots(additionalAllowedRoots);
2416
2437
  const matchedBypassRoot = await this.findContainingRoot(accessPath, bypassRoots, false);
2417
2438
  let matchedRoot = matchedBypassRoot;
2418
- if (this.security.fileAccess.mode === "disabled" && !matchedBypassRoot) throw new AccessPolicyError(`Security policy blocked local file access for ${url}`);
2439
+ if (this.security.fileAccess.mode === "disabled" && !matchedBypassRoot) throw new AccessPolicyError(`Local file access is disabled by the scraper security policy, so ${url} cannot be indexed. See ${FILE_ACCESS_DOCS} to configure local file access.`);
2419
2440
  if (this.security.fileAccess.mode === "allowedRoots" && !matchedBypassRoot) {
2420
- const configuredRoots = await this.expandRoots(this.security.fileAccess.allowedRoots);
2421
- if (configuredRoots.length === 0) throw new AccessPolicyError(`Security policy blocked local file access for ${url}`);
2441
+ const configuredRoots = await this.expandRoots(this.security.fileAccess.allowedRoots, true);
2442
+ if (configuredRoots.length === 0) {
2443
+ this.warnUnavailableAllowlist();
2444
+ throw new AccessPolicyError(`Local file access is limited to configured roots, but ${describeUnavailableRoots(this.security.fileAccess.allowedRoots)}, so ${url} cannot be indexed. See ${FILE_ACCESS_DOCS} to configure the allowed roots.`);
2445
+ }
2422
2446
  matchedRoot = await this.findContainingRoot(accessPath, configuredRoots, this.security.fileAccess.followSymlinks);
2423
- if (!matchedRoot) throw new AccessPolicyError(`Security policy blocked local file access for ${url}`);
2447
+ if (!matchedRoot) {
2448
+ this.logConfiguredRoots(configuredRoots);
2449
+ throw new AccessPolicyError(`${url} is outside the configured allowed roots, so it cannot be indexed. See ${FILE_ACCESS_DOCS} to allow this folder.`);
2450
+ }
2424
2451
  }
2425
2452
  if (!this.security.fileAccess.followSymlinks && !matchedBypassRoot) {
2426
- if (await findSymlinkInPath(accessPath)) throw new AccessPolicyError(`Security policy blocked symlink access for ${url}`);
2453
+ if (await findSymlinkInPath(accessPath)) throw new AccessPolicyError(`${url} resolves through a symlink, which the security policy blocks by default, so it cannot be indexed. See ${FILE_ACCESS_DOCS} to allow symlinked paths.`);
2427
2454
  }
2428
2455
  if (!this.security.fileAccess.includeHidden) {
2429
- if (hasHiddenSegmentBelowRoot(filePath, matchedRoot)) throw new AccessPolicyError(`Security policy blocked hidden file access for ${url}`);
2430
- if (resolved.virtualArchivePath && hasHiddenArchiveSegment(resolved.virtualArchivePath)) throw new AccessPolicyError(`Security policy blocked hidden archive entry access for ${url}`);
2456
+ if (hasHiddenSegmentBelowRoot(filePath, matchedRoot)) throw new AccessPolicyError(`${url} contains a hidden path segment (a name starting with "."), which the security policy blocks by default, so it cannot be indexed. See ${FILE_ACCESS_DOCS} to allow hidden files and folders.`);
2457
+ if (resolved.virtualArchivePath && hasHiddenArchiveSegment(resolved.virtualArchivePath)) throw new AccessPolicyError(`The archive entry requested by ${url} is hidden (a name starting with "."), which the security policy blocks by default. See ${FILE_ACCESS_DOCS} to allow hidden archive entries.`);
2431
2458
  }
2432
2459
  return {
2433
2460
  filePath,
@@ -2455,14 +2482,47 @@ var ScraperAccessPolicy = class {
2455
2482
  if (family === 0 || prefix === void 0) return;
2456
2483
  blockList.addSubnet(network, Number.parseInt(prefix, 10), family === 6 ? "ipv6" : "ipv4");
2457
2484
  }
2458
- async expandRoots(roots) {
2485
+ /**
2486
+ * Expands configured root entries into concrete paths, dropping those that do
2487
+ * not resolve on this system. With `warnOnUnresolved`, every dropped entry is
2488
+ * reported once — silently discarding them makes `allowedRoots` look active
2489
+ * when it grants nothing.
2490
+ */
2491
+ async expandRoots(roots, warnOnUnresolved = false) {
2459
2492
  const expanded = [];
2460
2493
  for (const root of roots) {
2461
2494
  const value = await expandConfiguredRoot(root);
2462
- if (value) expanded.push(value);
2495
+ if (value) {
2496
+ expanded.push(value);
2497
+ continue;
2498
+ }
2499
+ if (warnOnUnresolved && !this.warnedUnresolvedRoots.has(root)) {
2500
+ this.warnedUnresolvedRoots.add(root);
2501
+ logger.warn(`⚠️ Ignoring allowed file root "${root}": it does not resolve to an existing directory on this system.`);
2502
+ }
2463
2503
  }
2464
2504
  return expanded;
2465
2505
  }
2506
+ /**
2507
+ * Warns that `allowedRoots` mode is active but grants nothing, which blocks
2508
+ * all local file access. Emitted once per policy instance.
2509
+ */
2510
+ warnUnavailableAllowlist() {
2511
+ if (this.hasWarnedUnavailableAllowlist) return;
2512
+ this.hasWarnedUnavailableAllowlist = true;
2513
+ const configured = this.security.fileAccess.allowedRoots;
2514
+ const cause = configured.length === 0 ? "no roots are configured" : `none of the configured roots (${configured.join(", ")}) exist on this system`;
2515
+ logger.warn(`⚠️ Local file access is limited to configured roots, but ${cause}, so all file:// indexing is blocked. See ${FILE_ACCESS_DOCS} to configure the allowed roots.`);
2516
+ }
2517
+ /**
2518
+ * Logs the roots that local file access is limited to. Emitted once per policy
2519
+ * instance, alongside the first out-of-root rejection.
2520
+ */
2521
+ logConfiguredRoots(roots) {
2522
+ if (this.hasLoggedConfiguredRoots) return;
2523
+ this.hasLoggedConfiguredRoots = true;
2524
+ logger.warn(`⚠️ Local file access is limited to: ${roots.join(", ")}`);
2525
+ }
2466
2526
  async findContainingRoot(accessPath, roots, followSymlinks) {
2467
2527
  const resolvedAccessPath = await resolveContainmentPath(accessPath, followSymlinks);
2468
2528
  for (const root of roots) {
@@ -2514,6 +2574,33 @@ var USER_DIR_TOKENS = {
2514
2574
  $DOWNLOADS: "Downloads",
2515
2575
  $DESKTOP: "Desktop"
2516
2576
  };
2577
+ var ROOT_TOKENS = /* @__PURE__ */ new Set([
2578
+ "$HOME",
2579
+ "$CWD",
2580
+ ...Object.keys(USER_DIR_TOKENS)
2581
+ ]);
2582
+ /**
2583
+ * Describes why an `allowedRoots` allowlist grants no access, for an error that
2584
+ * also reaches MCP clients and the web UI.
2585
+ *
2586
+ * Configured tokens are named because they are fixed vocabulary that says
2587
+ * nothing about the host. Literal paths are only counted: even a path that does
2588
+ * not exist reveals the layout an operator intended, so `/mnt/acme-secrets/docs`
2589
+ * must not travel back to a caller.
2590
+ *
2591
+ * Today `expandConfiguredRoot` resolves literal paths unconditionally, so only
2592
+ * tokens reach this function and the count stays at zero. The branch guards the
2593
+ * day that changes — validating literal roots must not start leaking them.
2594
+ */
2595
+ function describeUnavailableRoots(configured) {
2596
+ if (configured.length === 0) return "no roots are configured";
2597
+ const tokens = configured.filter((root) => ROOT_TOKENS.has(root));
2598
+ const literalCount = configured.length - tokens.length;
2599
+ const parts = [];
2600
+ if (tokens.length > 0) parts.push(`${tokens.join(", ")} did not resolve`);
2601
+ if (literalCount > 0) parts.push(`${literalCount} configured path(s) do not exist`);
2602
+ return `none of its entries are available on this system (${parts.join("; ")})`;
2603
+ }
2517
2604
  /**
2518
2605
  * Expands user-facing configured root tokens into concrete filesystem paths.
2519
2606
  *
@@ -3650,43 +3737,6 @@ var CancelJobTool = class {
3650
3737
  }
3651
3738
  };
3652
3739
  //#endregion
3653
- //#region src/tools/ClearCompletedJobsTool.ts
3654
- /**
3655
- * Tool for clearing all completed, cancelled, and failed jobs from the pipeline.
3656
- * This helps keep the job queue clean by removing jobs that are no longer active.
3657
- */
3658
- var ClearCompletedJobsTool = class {
3659
- pipeline;
3660
- /**
3661
- * Creates an instance of ClearCompletedJobsTool.
3662
- * @param pipeline The pipeline instance.
3663
- */
3664
- constructor(pipeline) {
3665
- this.pipeline = pipeline;
3666
- }
3667
- /**
3668
- * Executes the tool to clear all completed jobs from the pipeline.
3669
- * @param input - The input parameters (currently unused).
3670
- * @returns A promise that resolves with the outcome of the clear operation.
3671
- * @throws {ToolError} If the clear operation fails.
3672
- */
3673
- async execute(_input) {
3674
- try {
3675
- const clearedCount = await this.pipeline.clearCompletedJobs();
3676
- const message = clearedCount > 0 ? `Successfully cleared ${clearedCount} completed job${clearedCount === 1 ? "" : "s"} from the queue.` : "No completed jobs to clear.";
3677
- logger.debug(message);
3678
- return {
3679
- message,
3680
- clearedCount
3681
- };
3682
- } catch (error) {
3683
- const errorMessage = `Failed to clear completed jobs: ${error instanceof Error ? error.message : String(error)}`;
3684
- logger.error(`❌ ${errorMessage}`);
3685
- throw new ToolError(errorMessage, this.constructor.name);
3686
- }
3687
- }
3688
- };
3689
- //#endregion
3690
3740
  //#region src/utils/dom.ts
3691
3741
  /**
3692
3742
  * Creates a JSDOM instance with a pre-configured virtual console to suppress console noise.
@@ -4619,7 +4669,7 @@ var BasePipeline = class {
4619
4669
  //#endregion
4620
4670
  //#region src/scraper/pipelines/DocumentPipeline.ts
4621
4671
  /**
4622
- * DocumentPipeline - Processes binary document formats using Kreuzberg for text extraction,
4672
+ * DocumentPipeline - Processes binary document formats using Xberg for text extraction,
4623
4673
  * then splits semantically.
4624
4674
  *
4625
4675
  * Supported formats:
@@ -4631,11 +4681,12 @@ var BasePipeline = class {
4631
4681
  * - eBooks: EPUB (.epub), FictionBook (.fb2)
4632
4682
  * - Jupyter Notebook (.ipynb)
4633
4683
  *
4634
- * The pipeline requests Markdown output from Kreuzberg (`@kreuzberg/node`) via
4635
- * `outputFormat: "markdown"`, aligning with the project's Markdown-first processing
4636
- * pipeline. For spreadsheet-type documents where `result.content` is flat text,
4637
- * the pipeline prefers pre-rendered Markdown from `tables[].markdown` which includes
4638
- * sheet names as headings and properly formatted Markdown tables.
4684
+ * The pipeline requests Markdown output from Xberg (`@xberg-io/xberg`) via
4685
+ * `outputFormat: OutputFormat.Markdown`, aligning with the project's Markdown-first
4686
+ * processing pipeline. Xberg's Markdown renderer emits fully structured output for
4687
+ * every format — including spreadsheets, where each sheet appears as a heading
4688
+ * followed by a Markdown table — so `content` is the preferred representation and
4689
+ * `tables[].markdown` only serves as a fallback when `content` comes back empty.
4639
4690
  *
4640
4691
  * Documents exceeding the configured maximum size are skipped with a warning.
4641
4692
  */
@@ -4677,8 +4728,17 @@ var DocumentPipeline = class extends BasePipeline {
4677
4728
  };
4678
4729
  }
4679
4730
  try {
4680
- const result = await extractBytes(buffer, mimeType, { outputFormat: "markdown" });
4681
- const content = this.extractContent(result, mimeType);
4731
+ const result = await extract({
4732
+ kind: ExtractInputKind.Bytes,
4733
+ bytes: buffer,
4734
+ mimeType
4735
+ }, { outputFormat: OutputFormat.Markdown });
4736
+ const document = result.results?.[0];
4737
+ if (!document) {
4738
+ const reason = result.errors?.[0]?.message;
4739
+ throw new Error(reason ? `Extraction produced no result: ${reason}` : "Extraction produced no result");
4740
+ }
4741
+ const content = this.extractContent(document);
4682
4742
  if (!content) {
4683
4743
  logger.warn(`No content extracted from document: ${rawContent.source}`);
4684
4744
  return {
@@ -4691,7 +4751,7 @@ var DocumentPipeline = class extends BasePipeline {
4691
4751
  };
4692
4752
  }
4693
4753
  return {
4694
- title: result.metadata?.title || this.extractFilename(rawContent.source),
4754
+ title: document.metadata?.title || this.extractFilename(rawContent.source),
4695
4755
  contentType: "text/markdown",
4696
4756
  textContent: content,
4697
4757
  links: [],
@@ -4715,29 +4775,18 @@ var DocumentPipeline = class extends BasePipeline {
4715
4775
  }
4716
4776
  }
4717
4777
  /**
4718
- * Selects the best content representation from a Kreuzberg extraction result.
4719
- * For spreadsheet-type documents, prefer pre-rendered Markdown from `tables[].markdown`.
4720
- * For other documents, prefer `result.content` and only fall back to tables when needed.
4778
+ * Selects the best content representation from an Xberg extraction result.
4779
+ *
4780
+ * `content` is preferred for every format: Xberg's Markdown renderer emits the
4781
+ * full document structure there, including sheet headings and Markdown tables
4782
+ * for spreadsheets, so it is always a superset of `tables[].markdown`. The
4783
+ * concatenated table Markdown is only used when `content` comes back empty.
4721
4784
  */
4722
- extractContent(result, mimeType) {
4723
- const sheetNames = result.metadata?.sheetNames;
4724
- const tableContent = result.tables.map((t, i) => {
4725
- const sheetName = sheetNames?.length === result.tables.length ? sheetNames[i] : null;
4726
- return sheetName ? `# ${sheetName}\n\n${t.markdown}` : t.markdown;
4727
- }).join("\n\n");
4728
- const hasTableContent = tableContent.trim().length > 0;
4729
- const content = result.content ?? "";
4730
- const hasContent = content.trim().length > 0;
4731
- if (this.isSpreadsheetMimeType(mimeType)) {
4732
- if (hasTableContent) return tableContent;
4733
- return hasContent ? content : null;
4734
- }
4735
- if (hasContent) return content;
4736
- if (hasTableContent) return tableContent;
4737
- return null;
4738
- }
4739
- isSpreadsheetMimeType(mimeType) {
4740
- return mimeType === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" || mimeType === "application/vnd.ms-excel" || mimeType === "application/vnd.oasis.opendocument.spreadsheet";
4785
+ extractContent(document) {
4786
+ const content = document.content ?? "";
4787
+ if (content.trim().length > 0) return content;
4788
+ const tableContent = (document.tables ?? []).map((t) => t.markdown ?? "").filter((markdown) => markdown.trim().length > 0).join("\n\n");
4789
+ return tableContent.length > 0 ? tableContent : null;
4741
4790
  }
4742
4791
  /**
4743
4792
  * Resolves the effective MIME type for document processing.
@@ -4764,7 +4813,7 @@ var DocumentPipeline = class extends BasePipeline {
4764
4813
  };
4765
4814
  /**
4766
4815
  * Maximum length (in characters) of any single error message included in
4767
- * extraction failure logs. Kreuzberg errors may embed parts of the input
4816
+ * extraction failure logs. Xberg errors may embed parts of the input
4768
4817
  * document; truncating defends the logs against accidental binary dumps
4769
4818
  * while still surfacing enough text to diagnose the root cause.
4770
4819
  */
@@ -4772,7 +4821,7 @@ var MAX_ERROR_DETAIL_LENGTH = 500;
4772
4821
  /**
4773
4822
  * Walks an `Error.cause` chain and returns a deduplicated, truncated list
4774
4823
  * of each link's `message`. Used to surface the underlying cause of a
4775
- * Kreuzberg extraction failure (e.g. "GLIBC_2.38 not found") rather than
4824
+ * Xberg extraction failure (e.g. "GLIBC_2.38 not found") rather than
4776
4825
  * just the wrapper's generic name.
4777
4826
  */
4778
4827
  function collectErrorReasons(error) {
@@ -8932,6 +8981,33 @@ var DocumentManagementClient = class {
8932
8981
  getActiveEmbeddingConfig() {
8933
8982
  return null;
8934
8983
  }
8984
+ async getEmbeddingConfigInfo() {
8985
+ return this.client.getEmbeddingConfig.query();
8986
+ }
8987
+ async listVersionChunks(ref, options) {
8988
+ return this.client.listVersionChunks.query({
8989
+ library: ref.library,
8990
+ version: ref.version,
8991
+ limit: options?.limit,
8992
+ offset: options?.offset,
8993
+ filter: options?.filter
8994
+ });
8995
+ }
8996
+ async getVersionStats(ref) {
8997
+ return this.client.getVersionStats.query({
8998
+ library: ref.library,
8999
+ version: ref.version
9000
+ });
9001
+ }
9002
+ async getActivityHistory(days) {
9003
+ return this.client.getActivityHistory.query({ days });
9004
+ }
9005
+ async getVersionComposition(ref) {
9006
+ return this.client.getVersionComposition.query({
9007
+ library: ref.library,
9008
+ version: ref.version
9009
+ });
9010
+ }
8935
9011
  };
8936
9012
  //#endregion
8937
9013
  //#region src/utils/version.ts
@@ -9622,6 +9698,13 @@ var VersionStatus = /* @__PURE__ */ function(VersionStatus) {
9622
9698
  VersionStatus["UPDATING"] = "updating";
9623
9699
  return VersionStatus;
9624
9700
  }({});
9701
+ /** Normalize a VersionRef (lowercase, trim; empty string for unversioned). */
9702
+ function normalizeVersionRef(ref) {
9703
+ return {
9704
+ library: ref.library.trim().toLowerCase(),
9705
+ version: (ref.version ?? "").trim().toLowerCase()
9706
+ };
9707
+ }
9625
9708
  /**
9626
9709
  * Helper function to convert NULL version name to empty string for API compatibility.
9627
9710
  * Database stores NULL for unversioned content, but APIs expect empty string.
@@ -9639,30 +9722,6 @@ function normalizeVersionName(name) {
9639
9722
  function denormalizeVersionName(name) {
9640
9723
  return name === "" ? "" : name;
9641
9724
  }
9642
- /**
9643
- * Gets a human-readable description of a version status.
9644
- */
9645
- function getStatusDescription(status) {
9646
- return {
9647
- ["not_indexed"]: "Version created but not yet indexed",
9648
- ["queued"]: "Waiting in queue for indexing",
9649
- ["running"]: "Currently being indexed",
9650
- ["completed"]: "Successfully indexed",
9651
- ["failed"]: "Indexing failed",
9652
- ["cancelled"]: "Indexing was cancelled",
9653
- ["updating"]: "Re-indexing in progress"
9654
- }[status] || "Unknown status";
9655
- }
9656
- /**
9657
- * Checks if a status represents an active state (job in progress).
9658
- */
9659
- function isActiveStatus(status) {
9660
- return [
9661
- "queued",
9662
- "running",
9663
- "updating"
9664
- ].includes(status);
9665
- }
9666
9725
  //#endregion
9667
9726
  //#region src/store/DocumentStore.ts
9668
9727
  /**
@@ -9813,10 +9872,16 @@ var DocumentStore = class {
9813
9872
  COALESCE(v.name, '') as version,
9814
9873
  v.id as versionId,
9815
9874
  v.status as status,
9875
+ v.error_message as errorMessage,
9816
9876
  v.progress_pages as progressPages,
9817
9877
  v.progress_max_pages as progressMaxPages,
9818
9878
  v.source_url as sourceUrl,
9819
- MIN(p.created_at) as indexedAt,
9879
+ -- "Last indexed" = when the version was last (re)indexed. Use the
9880
+ -- version's updated_at (bumped on every status/progress change during
9881
+ -- a run, including refreshes) rather than MIN(p.created_at), which is
9882
+ -- the *first*-index time and never moves on refresh. Fall back to the
9883
+ -- oldest page for versions that predate status tracking.
9884
+ COALESCE(v.updated_at, MIN(p.created_at)) as indexedAt,
9820
9885
  COUNT(d.id) as documentCount,
9821
9886
  COUNT(DISTINCT p.url) as uniqueUrlCount
9822
9887
  FROM versions v
@@ -10137,6 +10202,14 @@ var DocumentStore = class {
10137
10202
  return `${`"${tokens.join(" ").replace(/"/g, "\"\"")}"`} OR ${escapedTokens.join(" OR ")}`;
10138
10203
  }
10139
10204
  /**
10205
+ * Escapes SQL LIKE wildcard characters (`%`, `_`) and the escape character
10206
+ * itself so a user-supplied filter is matched as a literal substring rather
10207
+ * than interpreted as a pattern. Pair with `LIKE ? ESCAPE '\'`.
10208
+ */
10209
+ escapeLikePattern(value) {
10210
+ return value.replace(/[\\%_]/g, (match) => `\\${match}`);
10211
+ }
10212
+ /**
10140
10213
  * Initializes database connection and ensures readiness
10141
10214
  */
10142
10215
  async initialize() {
@@ -10469,6 +10542,7 @@ var DocumentStore = class {
10469
10542
  version: row.version,
10470
10543
  versionId: row.versionId,
10471
10544
  status: row.status,
10545
+ errorMessage: row.errorMessage,
10472
10546
  progressPages: row.progressPages,
10473
10547
  progressMaxPages: row.progressMaxPages,
10474
10548
  sourceUrl: row.sourceUrl,
@@ -10775,7 +10849,7 @@ var DocumentStore = class {
10775
10849
  AND dv.k = ?
10776
10850
  ORDER BY dv.distance
10777
10851
  ),
10778
- fts_scores AS (
10852
+ fts_scores AS MATERIALIZED (
10779
10853
  SELECT
10780
10854
  f.rowid as id,
10781
10855
  bm25(documents_fts, 10.0, 1.0, 5.0, 1.0) as fts_score
@@ -10786,6 +10860,20 @@ var DocumentStore = class {
10786
10860
  AND documents_fts MATCH ?
10787
10861
  ORDER BY fts_score
10788
10862
  LIMIT ?
10863
+ ),
10864
+ candidates AS (
10865
+ -- Union of vector and full-text candidate ids so the final query is
10866
+ -- driven by the small match set instead of scanning the entire
10867
+ -- documents table. Keeps search cost proportional to matches, not
10868
+ -- total database size.
10869
+ --
10870
+ -- Both source CTEs are referenced twice (here and in the LEFT JOINs
10871
+ -- below) and are pinned with MATERIALIZED so they are evaluated
10872
+ -- exactly once. Leaving this to the query planner is what caused
10873
+ -- the search regression in #454.
10874
+ SELECT id FROM vec_distances
10875
+ UNION
10876
+ SELECT id FROM fts_scores
10789
10877
  )
10790
10878
  SELECT
10791
10879
  d.id,
@@ -10797,15 +10885,15 @@ var DocumentStore = class {
10797
10885
  p.content_type as content_type,
10798
10886
  COALESCE(1 / (1 + v.vec_distance), 0) as vec_score,
10799
10887
  COALESCE(-MIN(f.fts_score, 0), 0) as fts_score
10800
- FROM documents d
10888
+ FROM candidates c
10889
+ JOIN documents d ON d.id = c.id
10801
10890
  JOIN pages p ON d.page_id = p.id
10802
10891
  LEFT JOIN vec_distances v ON d.id = v.id
10803
10892
  LEFT JOIN fts_scores f ON d.id = f.id
10804
- WHERE (v.id IS NOT NULL OR f.id IS NOT NULL)
10805
- AND NOT EXISTS (
10806
- SELECT 1 FROM json_each(json_extract(d.metadata, '$.types')) je
10807
- WHERE je.value = 'structural'
10808
- )
10893
+ WHERE NOT EXISTS (
10894
+ SELECT 1 FROM json_each(json_extract(d.metadata, '$.types')) je
10895
+ WHERE je.value = 'structural'
10896
+ )
10809
10897
  `).all(libraryId, versionId, JSON.stringify(embedding), vectorSearchK, versionId, ftsQuery, overfetchLimit);
10810
10898
  return this.assignRanks(rawResults).sort((a, b) => b.rrf_score - a.rrf_score).slice(0, limit).map((row) => {
10811
10899
  const result = {
@@ -10964,6 +11052,198 @@ var DocumentStore = class {
10964
11052
  throw new ConnectionError(`Failed to fetch documents by URL ${url}`, error);
10965
11053
  }
10966
11054
  }
11055
+ /**
11056
+ * Lists stored chunks for a library version with pagination and an optional
11057
+ * case-insensitive content filter. Powers the admin dashboard's chunk explorer.
11058
+ *
11059
+ * Position (`chunkIndex`/`pageChunkCount`) is computed with window functions
11060
+ * over `sort_order` rather than trusted verbatim, so results stay correct
11061
+ * even if a page's chunks were ever stored with non-contiguous ordering.
11062
+ * Token counts are never fabricated: the current schema has no per-chunk
11063
+ * token column, so every item's `tokenCount` is `null`.
11064
+ *
11065
+ * @param library Library name (case-insensitive).
11066
+ * @param version Version string (empty string for unversioned).
11067
+ * @param options Pagination (`limit`/`offset`) and optional content `filter`.
11068
+ * @returns The requested page of chunks plus the total count matching the filter.
11069
+ */
11070
+ async listVersionChunks(library, version, options) {
11071
+ try {
11072
+ const normalizedVersion = version.toLowerCase();
11073
+ const versionRow = this.statements.getVersionId.get(library.toLowerCase(), normalizedVersion);
11074
+ if (!versionRow) return {
11075
+ chunks: [],
11076
+ total: 0
11077
+ };
11078
+ const offset = options.offset ?? 0;
11079
+ const trimmedFilter = options.filter?.trim();
11080
+ const whereParams = [versionRow.id];
11081
+ let whereClause = "WHERE p.version_id = ?";
11082
+ if (trimmedFilter) {
11083
+ whereClause += " AND LOWER(d.content) LIKE LOWER(?) ESCAPE '\\'";
11084
+ whereParams.push(`%${this.escapeLikePattern(trimmedFilter)}%`);
11085
+ }
11086
+ const total = this.db.prepare(`SELECT COUNT(*) as count
11087
+ FROM documents d
11088
+ JOIN pages p ON d.page_id = p.id
11089
+ ${whereClause}`).get(...whereParams).count;
11090
+ return {
11091
+ chunks: this.db.prepare(`SELECT
11092
+ d.id,
11093
+ d.content,
11094
+ (d.embedding IS NOT NULL) as has_embedding,
11095
+ p.url as url,
11096
+ p.content_type as mime_type,
11097
+ ROW_NUMBER() OVER (PARTITION BY d.page_id ORDER BY d.sort_order, d.id) as chunk_index,
11098
+ COUNT(*) OVER (PARTITION BY d.page_id) as page_chunk_count
11099
+ FROM documents d
11100
+ JOIN pages p ON d.page_id = p.id
11101
+ ${whereClause}
11102
+ ORDER BY p.url, d.sort_order, d.id
11103
+ LIMIT ? OFFSET ?`).all(...whereParams, options.limit, offset).map((row) => ({
11104
+ id: String(row.id),
11105
+ url: row.url,
11106
+ content: row.content,
11107
+ mimeType: row.mime_type,
11108
+ chunkIndex: row.chunk_index,
11109
+ pageChunkCount: row.page_chunk_count,
11110
+ charCount: row.content.length,
11111
+ tokenCount: null,
11112
+ hasEmbedding: Boolean(row.has_embedding)
11113
+ })),
11114
+ total
11115
+ };
11116
+ } catch (error) {
11117
+ throw new ConnectionError("Failed to list version chunks", error);
11118
+ }
11119
+ }
11120
+ /**
11121
+ * Computes aggregate chunk/page/embedding statistics for a library version,
11122
+ * for the chunk explorer's header strip.
11123
+ *
11124
+ * `avgTokensPerChunk` is always `null`: the schema does not persist
11125
+ * per-chunk token counts, so this is reported as unavailable rather than
11126
+ * fabricated from character counts.
11127
+ *
11128
+ * @param library Library name (case-insensitive).
11129
+ * @param version Version string (empty string for unversioned).
11130
+ * @returns Aggregate statistics, or all-zero/`null` values if the version doesn't exist.
11131
+ */
11132
+ async getVersionStats(library, version) {
11133
+ try {
11134
+ const normalizedVersion = version.toLowerCase();
11135
+ const versionRow = this.statements.getVersionId.get(library.toLowerCase(), normalizedVersion);
11136
+ if (!versionRow) return {
11137
+ pageCount: 0,
11138
+ chunkCount: 0,
11139
+ avgChunksPerPage: null,
11140
+ avgTokensPerChunk: null,
11141
+ embeddedChunkCount: 0
11142
+ };
11143
+ const row = this.db.prepare(`SELECT
11144
+ COUNT(DISTINCT p.id) as page_count,
11145
+ COUNT(d.id) as chunk_count,
11146
+ SUM(CASE WHEN d.embedding IS NOT NULL THEN 1 ELSE 0 END) as embedded_chunk_count
11147
+ FROM pages p
11148
+ LEFT JOIN documents d ON d.page_id = p.id
11149
+ WHERE p.version_id = ?`).get(versionRow.id);
11150
+ return {
11151
+ pageCount: row.page_count,
11152
+ chunkCount: row.chunk_count,
11153
+ avgChunksPerPage: row.page_count > 0 ? row.chunk_count / row.page_count : null,
11154
+ avgTokensPerChunk: null,
11155
+ embeddedChunkCount: row.embedded_chunk_count ?? 0
11156
+ };
11157
+ } catch (error) {
11158
+ throw new ConnectionError("Failed to get version stats", error);
11159
+ }
11160
+ }
11161
+ /**
11162
+ * Returns per-day indexing activity over the trailing `days`-day window,
11163
+ * derived from the `created_at` timestamps already stored on pages and
11164
+ * chunks. Days with no activity are zero-filled so the returned series is
11165
+ * contiguous.
11166
+ *
11167
+ * Rows are grouped by UTC calendar day to match SQLite's `date('now')`.
11168
+ * `created_at` reflects first insertion, so a refresh that only updates
11169
+ * existing pages does not inflate the counts (it is genuinely new content,
11170
+ * not re-touched content, that registers as activity).
11171
+ *
11172
+ * @param days - Window length in days; clamped to 1..366.
11173
+ */
11174
+ async getActivityHistory(days) {
11175
+ try {
11176
+ const windowDays = Math.max(1, Math.min(366, Math.floor(days) || 1));
11177
+ const rows = this.db.prepare(`WITH RECURSIVE calendar(day) AS (
11178
+ SELECT date('now', '-' || (@days - 1) || ' days')
11179
+ UNION ALL
11180
+ SELECT date(day, '+1 day') FROM calendar WHERE day < date('now')
11181
+ )
11182
+ SELECT
11183
+ calendar.day AS date,
11184
+ COALESCE(pg.cnt, 0) AS pages,
11185
+ COALESCE(ch.cnt, 0) AS chunks
11186
+ FROM calendar
11187
+ LEFT JOIN (
11188
+ SELECT date(created_at) AS d, COUNT(*) AS cnt
11189
+ FROM pages
11190
+ WHERE created_at >= date('now', '-' || (@days - 1) || ' days')
11191
+ GROUP BY d
11192
+ ) pg ON pg.d = calendar.day
11193
+ LEFT JOIN (
11194
+ SELECT date(created_at) AS d, COUNT(*) AS cnt
11195
+ FROM documents
11196
+ WHERE created_at >= date('now', '-' || (@days - 1) || ' days')
11197
+ GROUP BY d
11198
+ ) ch ON ch.d = calendar.day
11199
+ ORDER BY calendar.day`).all({ days: windowDays });
11200
+ let totalPages = 0;
11201
+ let totalChunks = 0;
11202
+ for (const row of rows) {
11203
+ totalPages += row.pages;
11204
+ totalChunks += row.chunks;
11205
+ }
11206
+ return {
11207
+ days: rows.map((row) => ({
11208
+ date: row.date,
11209
+ pages: row.pages,
11210
+ chunks: row.chunks
11211
+ })),
11212
+ since: rows[0]?.date ?? "",
11213
+ until: rows[rows.length - 1]?.date ?? "",
11214
+ totalPages,
11215
+ totalChunks
11216
+ };
11217
+ } catch (error) {
11218
+ throw new ConnectionError("Failed to get activity history", error);
11219
+ }
11220
+ }
11221
+ /**
11222
+ * Returns a per-version content-type breakdown: pages grouped by MIME type
11223
+ * (`content_type`, falling back to `source_content_type`, else `unknown`),
11224
+ * most common first. Derived from the stored pages.
11225
+ *
11226
+ * @param library - Library name (case-insensitive).
11227
+ * @param version - Version name (empty string for unversioned).
11228
+ */
11229
+ async getVersionComposition(library, version) {
11230
+ try {
11231
+ const versionRow = this.statements.getVersionId.get(library.toLowerCase(), version.toLowerCase());
11232
+ if (!versionRow) return { mimeTypes: [] };
11233
+ return { mimeTypes: this.db.prepare(`SELECT
11234
+ COALESCE(NULLIF(p.content_type, ''), NULLIF(p.source_content_type, ''), 'unknown') AS label,
11235
+ COUNT(*) AS pages
11236
+ FROM pages p
11237
+ WHERE p.version_id = ?
11238
+ GROUP BY label
11239
+ ORDER BY pages DESC, label`).all(versionRow.id).map((row) => ({
11240
+ label: row.label,
11241
+ pages: row.pages
11242
+ })) };
11243
+ } catch (error) {
11244
+ throw new ConnectionError("Failed to get version composition", error);
11245
+ }
11246
+ }
10967
11247
  };
10968
11248
  //#endregion
10969
11249
  //#region src/store/DocumentManagementService.ts
@@ -10995,6 +11275,14 @@ var DocumentManagementService = class DocumentManagementService {
10995
11275
  getActiveEmbeddingConfig() {
10996
11276
  return this.store.getActiveEmbeddingConfig();
10997
11277
  }
11278
+ async getEmbeddingConfigInfo() {
11279
+ const config = this.getActiveEmbeddingConfig();
11280
+ return config ? {
11281
+ provider: config.provider,
11282
+ model: config.model,
11283
+ dimensions: config.dimensions
11284
+ } : null;
11285
+ }
10998
11286
  /**
10999
11287
  * Normalizes a version string, converting null or undefined to an empty string
11000
11288
  * and converting to lowercase.
@@ -11084,6 +11372,7 @@ var DocumentManagementService = class DocumentManagementService {
11084
11372
  version: v.version
11085
11373
  },
11086
11374
  status: v.status,
11375
+ errorMessage: v.errorMessage,
11087
11376
  progress: v.status === "completed" ? void 0 : {
11088
11377
  pages: v.progressPages,
11089
11378
  maxPages: v.progressMaxPages
@@ -11318,6 +11607,47 @@ var DocumentManagementService = class DocumentManagementService {
11318
11607
  async getLibraryById(libraryId) {
11319
11608
  return this.store.getLibraryById(libraryId);
11320
11609
  }
11610
+ /**
11611
+ * Lists stored chunks for a library version with pagination and an optional
11612
+ * content filter. Powers the admin dashboard's chunk explorer.
11613
+ * @param ref Library/version reference; normalized before querying the store.
11614
+ * @param options Pagination (`limit`, defaults to 50; `offset`) and optional content `filter`.
11615
+ */
11616
+ async listVersionChunks(ref, options = {}) {
11617
+ const normalized = normalizeVersionRef(ref);
11618
+ return this.store.listVersionChunks(normalized.library, normalized.version, {
11619
+ limit: options.limit ?? 50,
11620
+ offset: options.offset,
11621
+ filter: options.filter
11622
+ });
11623
+ }
11624
+ /**
11625
+ * Computes aggregate chunk/page/embedding statistics for a library version,
11626
+ * for the chunk explorer's header strip.
11627
+ * @param ref Library/version reference; normalized before querying the store.
11628
+ */
11629
+ async getVersionStats(ref) {
11630
+ const normalized = normalizeVersionRef(ref);
11631
+ return this.store.getVersionStats(normalized.library, normalized.version);
11632
+ }
11633
+ /**
11634
+ * Returns per-day indexing activity across the whole store over a trailing
11635
+ * window, derived from stored page/chunk creation timestamps. Powers the
11636
+ * Overview "Indexing activity" chart.
11637
+ * @param days Window length in days; defaults to 90, clamped to 1..366.
11638
+ */
11639
+ async getActivityHistory(days = 90) {
11640
+ return this.store.getActivityHistory(days);
11641
+ }
11642
+ /**
11643
+ * Computes a per-version content-type breakdown (pages grouped by MIME type)
11644
+ * for the library-detail Content types panel.
11645
+ * @param ref Library/version reference; normalized before querying the store.
11646
+ */
11647
+ async getVersionComposition(ref) {
11648
+ const normalized = normalizeVersionRef(ref);
11649
+ return this.store.getVersionComposition(normalized.library, normalized.version);
11650
+ }
11321
11651
  };
11322
11652
  //#endregion
11323
11653
  //#region src/store/index.ts
@@ -11547,12 +11877,50 @@ async function cleanupMcpService(mcpServer) {
11547
11877
  }
11548
11878
  }
11549
11879
  //#endregion
11880
+ //#region src/services/systemInfo.ts
11881
+ /**
11882
+ * Assembles the {@link SystemInfo} snapshot from server + app configuration.
11883
+ * @param serverConfig - Service composition/runtime wiring for this process.
11884
+ * @param appConfig - Resolved application configuration (env/YAML/CLI merged).
11885
+ * @returns The distilled system info to thread through the tRPC context.
11886
+ */
11887
+ function buildSystemInfo(serverConfig, appConfig) {
11888
+ const mcpEnabled = Boolean(serverConfig.enableMcpServer);
11889
+ const authEnabled = Boolean(appConfig.auth.enabled);
11890
+ return {
11891
+ version: "3.0.0",
11892
+ readOnly: Boolean(appConfig.app.readOnly),
11893
+ telemetryEnabled: Boolean(appConfig.app.telemetryEnabled),
11894
+ services: {
11895
+ web: Boolean(serverConfig.enableWebInterface),
11896
+ mcp: mcpEnabled,
11897
+ api: Boolean(serverConfig.enableApiServer),
11898
+ worker: Boolean(serverConfig.enableWorker)
11899
+ },
11900
+ worker: serverConfig.externalWorkerUrl ? {
11901
+ mode: "remote",
11902
+ url: serverConfig.externalWorkerUrl
11903
+ } : {
11904
+ mode: "embedded",
11905
+ maxConcurrency: appConfig.scraper.maxConcurrency
11906
+ },
11907
+ mcp: {
11908
+ enabled: mcpEnabled,
11909
+ endpoints: mcpEnabled ? ["/mcp", "/sse"] : []
11910
+ },
11911
+ auth: {
11912
+ enabled: authEnabled,
11913
+ issuer: authEnabled && appConfig.auth.issuerUrl ? appConfig.auth.issuerUrl : void 0
11914
+ }
11915
+ };
11916
+ }
11917
+ //#endregion
11550
11918
  //#region src/events/trpc/router.ts
11551
11919
  /**
11552
11920
  * tRPC router for event subscriptions.
11553
11921
  * Allows remote processes to subscribe to application events via tRPC.
11554
11922
  */
11555
- var t$2 = initTRPC.context().create({ transformer: superjson });
11923
+ var t$4 = initTRPC.context().create({ transformer: superjson });
11556
11924
  /**
11557
11925
  * Factory to create an events router from any t instance whose context contains `eventBus`.
11558
11926
  */
@@ -11582,7 +11950,7 @@ subscribe: tt.procedure.input(z.object({ events: z.array(z.nativeEnum(EventType)
11582
11950
  });
11583
11951
  }) });
11584
11952
  }
11585
- createEventsRouter(t$2);
11953
+ createEventsRouter(t$4);
11586
11954
  //#endregion
11587
11955
  //#region src/pipeline/trpc/router.ts
11588
11956
  /**
@@ -11592,9 +11960,13 @@ createEventsRouter(t$2);
11592
11960
  * This module now exports a factory to build the router from a provided t instance,
11593
11961
  * allowing us to compose multiple routers under a single /api endpoint.
11594
11962
  */
11595
- var t$1 = initTRPC.context().create({ transformer: superjson });
11963
+ var t$3 = initTRPC.context().create({ transformer: superjson });
11596
11964
  var nonEmptyTrimmed = z.string().transform((s) => s.trim()).refine((s) => s.length > 0, "must not be empty");
11597
- var optionalTrimmed = z.preprocess((v) => typeof v === "string" ? v.trim() : v, z.string().min(1).optional().nullable());
11965
+ var optionalTrimmed = z.preprocess((v) => {
11966
+ if (typeof v !== "string") return v;
11967
+ const trimmed = v.trim();
11968
+ return trimmed.length > 0 ? trimmed : void 0;
11969
+ }, z.string().min(1).optional().nullable());
11598
11970
  var enqueueScrapeInput = z.object({
11599
11971
  library: nonEmptyTrimmed,
11600
11972
  version: optionalTrimmed,
@@ -11635,14 +12007,14 @@ function createPipelineRouter(trpc) {
11635
12007
  })
11636
12008
  });
11637
12009
  }
11638
- createPipelineRouter(t$1);
12010
+ createPipelineRouter(t$3);
11639
12011
  //#endregion
11640
12012
  //#region src/store/trpc/router.ts
11641
12013
  /**
11642
12014
  * tRPC router exposing document data store operations via the worker API.
11643
12015
  * Only procedures actually used externally are included to keep surface minimal.
11644
12016
  */
11645
- var t = initTRPC.context().create({ transformer: superjson });
12017
+ var t$2 = initTRPC.context().create({ transformer: superjson });
11646
12018
  var nonEmpty = z.string().min(1).transform((s) => s.trim());
11647
12019
  var optionalVersion = z.string().optional().nullable().transform((v) => typeof v === "string" ? v.trim() : v);
11648
12020
  function createDataRouter(trpc) {
@@ -11719,2562 +12091,221 @@ function createDataRouter(trpc) {
11719
12091
  })).mutation(async ({ ctx, input }) => {
11720
12092
  await ctx.docService.storeScraperOptions(input.versionId, input.options);
11721
12093
  return { ok: true };
12094
+ }),
12095
+ listVersionChunks: tt.procedure.input(z.object({
12096
+ library: nonEmpty,
12097
+ version: optionalVersion,
12098
+ limit: z.number().int().positive().max(200).optional(),
12099
+ offset: z.number().int().nonnegative().optional(),
12100
+ filter: z.string().optional()
12101
+ })).query(async ({ ctx, input }) => {
12102
+ return await ctx.docService.listVersionChunks({
12103
+ library: input.library,
12104
+ version: input.version ?? ""
12105
+ }, {
12106
+ limit: input.limit ?? 50,
12107
+ offset: input.offset,
12108
+ filter: input.filter
12109
+ });
12110
+ }),
12111
+ getVersionStats: tt.procedure.input(z.object({
12112
+ library: nonEmpty,
12113
+ version: optionalVersion
12114
+ })).query(async ({ ctx, input }) => {
12115
+ return await ctx.docService.getVersionStats({
12116
+ library: input.library,
12117
+ version: input.version ?? ""
12118
+ });
12119
+ }),
12120
+ getActivityHistory: tt.procedure.input(z.object({ days: z.number().int().min(1).max(366).optional() }).optional()).query(async ({ ctx, input }) => {
12121
+ return await ctx.docService.getActivityHistory(input?.days);
12122
+ }),
12123
+ getVersionComposition: tt.procedure.input(z.object({
12124
+ library: nonEmpty,
12125
+ version: optionalVersion
12126
+ })).query(async ({ ctx, input }) => {
12127
+ return await ctx.docService.getVersionComposition({
12128
+ library: input.library,
12129
+ version: input.version ?? ""
12130
+ });
12131
+ }),
12132
+ getEmbeddingConfig: tt.procedure.query(async ({ ctx }) => {
12133
+ return ctx.docService.getEmbeddingConfigInfo();
11722
12134
  })
11723
12135
  });
11724
12136
  }
11725
- createDataRouter(t);
12137
+ createDataRouter(t$2);
11726
12138
  //#endregion
11727
- //#region src/services/trpcService.ts
12139
+ //#region src/services/systemHealthRouter.ts
11728
12140
  /**
11729
- * Fastify service to register unified tRPC API at /api.
11730
- * Merges pipeline, data store, and events routers under a single endpoint.
11731
- * Also provides WebSocket support for subscriptions.
12141
+ * tRPC router exposing a single `getSystemHealth` query that composes the
12142
+ * server's startup {@link SystemInfo} snapshot with the small amount of
12143
+ * cheaply-available live state (active embedding config, remote worker
12144
+ * connectivity). Powers the dashboard's system-health panel, sidebar status
12145
+ * footer, and Settings screen.
12146
+ */
12147
+ var t$1 = initTRPC.context().create({ transformer: superjson });
12148
+ /**
12149
+ * Factory to create the system-health router from any `t` instance whose
12150
+ * context satisfies {@link SystemHealthTrpcContext}.
12151
+ */
12152
+ function createSystemHealthRouter(trpc) {
12153
+ const tt = trpc;
12154
+ return tt.router({
12155
+ /**
12156
+ * Returns an honest snapshot of the running server's configuration:
12157
+ * which services were started, how the worker is wired, the active
12158
+ * embedding provider (if any), MCP/auth exposure, and app version.
12159
+ * Derived from startup config, not measured — nothing here is fabricated.
12160
+ */
12161
+ getSystemHealth: tt.procedure.query(async ({ ctx }) => {
12162
+ const { systemInfo } = ctx;
12163
+ const worker = systemInfo.worker.mode === "remote" ? {
12164
+ mode: "remote",
12165
+ url: systemInfo.worker.url,
12166
+ connected: ctx.isWorkerConnected?.() ?? false
12167
+ } : {
12168
+ mode: "embedded",
12169
+ maxConcurrency: systemInfo.worker.maxConcurrency
12170
+ };
12171
+ const embeddings = await ctx.docService.getEmbeddingConfigInfo();
12172
+ return {
12173
+ version: systemInfo.version,
12174
+ readOnly: systemInfo.readOnly,
12175
+ telemetryEnabled: systemInfo.telemetryEnabled,
12176
+ services: systemInfo.services,
12177
+ worker,
12178
+ embeddings,
12179
+ mcp: systemInfo.mcp,
12180
+ auth: systemInfo.auth
12181
+ };
12182
+ }) });
12183
+ }
12184
+ createSystemHealthRouter(t$1);
12185
+ //#endregion
12186
+ //#region src/services/appRouter.ts
12187
+ /**
12188
+ * Canonical tRPC router builder for the merged application API.
12189
+ * Combines the health check, pipeline, data store, and events routers into a
12190
+ * single router shape. Both the Fastify HTTP mount point and the WebSocket
12191
+ * subscription handler in {@link ./trpcService} import from this module so the
12192
+ * two transports always expose identical procedures and typing.
12193
+ */
12194
+ var t = initTRPC.context().create({ transformer: superjson });
12195
+ /**
12196
+ * Builds the merged application tRPC router (health + pipeline + data + events).
12197
+ * Kept as a factory (rather than only exporting a singleton) so future
12198
+ * transports can construct a fresh router instance if ever needed, while the
12199
+ * `appRouter` singleton below remains the single instance shared by the
12200
+ * current HTTP and WebSocket mount points.
12201
+ * @returns The merged tRPC router.
11732
12202
  */
11733
- async function registerTrpcService(server, pipeline, docService, eventBus) {
11734
- const t = initTRPC.context().create({ transformer: superjson });
12203
+ function buildAppRouter() {
11735
12204
  const healthRouter = t.router({ ping: t.procedure.query(async () => ({
11736
12205
  status: "ok",
11737
12206
  ts: Date.now()
11738
12207
  })) });
11739
- const router = t.router({
12208
+ return t.router({
11740
12209
  ...healthRouter._def.procedures,
11741
12210
  ...createPipelineRouter(t)._def.procedures,
11742
12211
  ...createDataRouter(t)._def.procedures,
12212
+ ...createSystemHealthRouter(t)._def.procedures,
11743
12213
  events: createEventsRouter(t)
11744
12214
  });
12215
+ }
12216
+ /** The canonical merged application router instance, shared by all transports. */
12217
+ var appRouter = buildAppRouter();
12218
+ /**
12219
+ * Creates the request context shared by both the HTTP and WebSocket transports.
12220
+ * @param deps - The pipeline, document store, event bus, and system info backing this request.
12221
+ * @returns The context object passed to every procedure resolver.
12222
+ */
12223
+ function createAppRouterContext(deps) {
12224
+ return {
12225
+ pipeline: deps.pipeline,
12226
+ docService: deps.docService,
12227
+ eventBus: deps.eventBus,
12228
+ systemInfo: deps.systemInfo,
12229
+ isWorkerConnected: deps.isWorkerConnected
12230
+ };
12231
+ }
12232
+ //#endregion
12233
+ //#region src/services/trpcService.ts
12234
+ /**
12235
+ * Fastify service to register unified tRPC API at /api.
12236
+ * Merges pipeline, data store, and events routers under a single endpoint.
12237
+ * Also provides WebSocket support for subscriptions.
12238
+ * Both mount points delegate to the single canonical router built in
12239
+ * {@link ../services/appRouter}, keeping HTTP and WebSocket behavior identical.
12240
+ */
12241
+ /**
12242
+ * Registers the merged tRPC router on a Fastify instance under the `/api` prefix.
12243
+ * @param server - The Fastify instance to register the plugin on.
12244
+ * @param pipeline - The pipeline instance backing pipeline procedures.
12245
+ * @param docService - The document management service backing data procedures.
12246
+ * @param eventBus - The event bus backing the events subscription router.
12247
+ * @param systemInfo - Distilled, serializable snapshot of the server's startup configuration.
12248
+ * @param isWorkerConnected - Cheap connectivity check, provided only when the worker is remote.
12249
+ */
12250
+ async function registerTrpcService(server, pipeline, docService, eventBus, systemInfo, isWorkerConnected) {
11745
12251
  await server.register(fastifyTRPCPlugin, {
11746
12252
  prefix: "/api",
11747
12253
  trpcOptions: {
11748
- router,
11749
- createContext: async () => ({
12254
+ router: appRouter,
12255
+ createContext: async () => createAppRouterContext({
11750
12256
  pipeline,
11751
12257
  docService,
11752
- eventBus
12258
+ eventBus,
12259
+ systemInfo,
12260
+ isWorkerConnected
11753
12261
  })
11754
12262
  }
11755
12263
  });
11756
12264
  }
11757
12265
  /**
11758
- * Apply WebSocket handler to a WebSocketServer for tRPC subscriptions.
12266
+ * Applies the tRPC WebSocket handler to a WebSocketServer for subscriptions.
12267
+ * @param wss - The WebSocket server to attach the tRPC handler to.
12268
+ * @param pipeline - The pipeline instance backing pipeline procedures.
12269
+ * @param docService - The document management service backing data procedures.
12270
+ * @param eventBus - The event bus backing the events subscription router.
12271
+ * @param systemInfo - Distilled, serializable snapshot of the server's startup configuration.
12272
+ * @param isWorkerConnected - Cheap connectivity check, provided only when the worker is remote.
12273
+ * @returns The tRPC WebSocket handler returned by `applyWSSHandler`.
11759
12274
  */
11760
- function applyTrpcWebSocketHandler(wss, pipeline, docService, eventBus) {
11761
- const t = initTRPC.context().create({ transformer: superjson });
11762
- const healthRouter = t.router({ ping: t.procedure.query(async () => ({
11763
- status: "ok",
11764
- ts: Date.now()
11765
- })) });
12275
+ function applyTrpcWebSocketHandler(wss, pipeline, docService, eventBus, systemInfo, isWorkerConnected) {
11766
12276
  return applyWSSHandler({
11767
12277
  wss,
11768
- router: t.router({
11769
- ...healthRouter._def.procedures,
11770
- ...createPipelineRouter(t)._def.procedures,
11771
- ...createDataRouter(t)._def.procedures,
11772
- events: createEventsRouter(t)
11773
- }),
11774
- createContext: () => ({
12278
+ router: appRouter,
12279
+ createContext: () => createAppRouterContext({
11775
12280
  pipeline,
11776
12281
  docService,
11777
- eventBus
12282
+ eventBus,
12283
+ systemInfo,
12284
+ isWorkerConnected
11778
12285
  })
11779
12286
  });
11780
12287
  }
11781
12288
  //#endregion
11782
- //#region src/web/routes/events.ts
12289
+ //#region src/services/workerService.ts
11783
12290
  /**
11784
- * Convert internal event payload to SSE payload format.
12291
+ * Register worker service to enable embedded pipeline processing.
12292
+ * This starts the pipeline and configures callbacks for job processing.
12293
+ *
12294
+ * Note: This function is now deprecated in favor of configuring callbacks
12295
+ * in AppServer.setupPipelineEventBridge(). Keeping telemetry/logging here
12296
+ * would overwrite the event bus callbacks, breaking SSE notifications.
12297
+ * Telemetry and logging should be integrated into the event bus listeners instead.
11785
12298
  */
11786
- function convertToSsePayload(eventType, payload) {
11787
- switch (eventType) {
11788
- case EventType.JOB_STATUS_CHANGE: {
11789
- const job = payload;
11790
- return {
11791
- id: job.id,
11792
- library: job.library,
11793
- version: job.version,
11794
- status: job.status,
11795
- error: job.error,
11796
- createdAt: job.createdAt.toISOString(),
11797
- startedAt: job.startedAt?.toISOString() ?? null,
11798
- finishedAt: job.finishedAt?.toISOString() ?? null,
11799
- sourceUrl: job.sourceUrl
11800
- };
11801
- }
11802
- case EventType.JOB_PROGRESS: {
11803
- const { job, progress } = payload;
11804
- return {
11805
- id: job.id,
11806
- library: job.library,
11807
- version: job.version,
11808
- progress: {
11809
- pagesScraped: progress.pagesScraped,
11810
- totalPages: progress.totalPages,
11811
- totalDiscovered: progress.totalDiscovered,
11812
- currentUrl: progress.currentUrl,
11813
- depth: progress.depth,
11814
- maxDepth: progress.maxDepth
11815
- }
11816
- };
11817
- }
11818
- case EventType.LIBRARY_CHANGE: return {};
11819
- case EventType.JOB_LIST_CHANGE: return {};
11820
- default: throw new Error(`Unhandled event type: ${eventType}`);
11821
- }
12299
+ async function registerWorkerService(pipeline) {
12300
+ await pipeline.start();
12301
+ logger.debug("Worker service started");
11822
12302
  }
11823
12303
  /**
11824
- * Send an SSE message to the client.
12304
+ * Stop the worker service and cleanup resources.
11825
12305
  */
11826
- function sendSseMessage(reply, eventName, data) {
11827
- try {
11828
- const message = `event: ${eventName}\ndata: ${JSON.stringify(data)}\n\n`;
11829
- reply.raw.write(message);
11830
- return true;
11831
- } catch (error) {
11832
- logger.error(`❌ Failed to send SSE event: ${error}`);
11833
- return false;
11834
- }
11835
- }
11836
- /**
11837
- * Registers the SSE events route.
11838
- * @param server - The Fastify instance.
11839
- * @param eventBus - The central event bus service instance.
11840
- */
11841
- function registerEventsRoute(server, eventBus) {
11842
- server.get("/web/events", async (request, reply) => {
11843
- reply.raw.writeHead(200, {
11844
- "Content-Type": "text/event-stream",
11845
- "Cache-Control": "no-cache, no-transform",
11846
- Connection: "keep-alive",
11847
- "X-Accel-Buffering": "no"
11848
- });
11849
- reply.raw.write("data: connected\n\n");
11850
- logger.debug("SSE client connected");
11851
- const allEventTypes = [
11852
- EventType.JOB_STATUS_CHANGE,
11853
- EventType.JOB_PROGRESS,
11854
- EventType.LIBRARY_CHANGE,
11855
- EventType.JOB_LIST_CHANGE
11856
- ];
11857
- const unsubscribers = [];
11858
- for (const eventType of allEventTypes) {
11859
- const unsubscribe = eventBus.on(eventType, (payload) => {
11860
- try {
11861
- const eventName = ServerEventName[eventType];
11862
- const ssePayload = convertToSsePayload(eventType, payload);
11863
- logger.debug(`SSE forwarding event: ${eventName} ${JSON.stringify(ssePayload)}`);
11864
- sendSseMessage(reply, eventName, ssePayload);
11865
- } catch (error) {
11866
- logger.error(`❌ Failed to convert/send SSE event ${eventType}: ${error}`);
11867
- }
11868
- });
11869
- unsubscribers.push(unsubscribe);
11870
- logger.debug(`SSE listener registered for: ${ServerEventName[eventType]}`);
11871
- }
11872
- const cleanup = () => {
11873
- for (const unsubscribe of unsubscribers) unsubscribe();
11874
- };
11875
- const heartbeatInterval = setInterval(() => {
11876
- try {
11877
- reply.raw.write(": heartbeat\n\n");
11878
- } catch (_error) {
11879
- logger.debug("Failed to send heartbeat, client likely disconnected");
11880
- clearInterval(heartbeatInterval);
11881
- }
11882
- }, 3e4);
11883
- request.raw.on("close", () => {
11884
- logger.debug("SSE client disconnected");
11885
- cleanup();
11886
- clearInterval(heartbeatInterval);
11887
- });
11888
- request.raw.on("error", (error) => {
11889
- logger.debug(`SSE connection error: ${error}`);
11890
- cleanup();
11891
- clearInterval(heartbeatInterval);
11892
- });
11893
- });
11894
- }
11895
- //#endregion
11896
- //#region src/web/components/PrimaryButton.tsx
11897
- /**
11898
- * A reusable primary button component with consistent styling.
11899
- * Supports additional HTML attributes via spread.
11900
- */
11901
- var PrimaryButton = ({ children, type = "button", class: className = "", disabled = false, ...rest }) => {
11902
- return /* @__PURE__ */ jsx("button", {
11903
- type,
11904
- class: `w-full flex justify-center py-1.5 px-3 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary-600 hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 transition-colors duration-150 ${disabled ? "opacity-50 cursor-not-allowed" : ""} ${className}`.trim(),
11905
- disabled,
11906
- ...rest,
11907
- children
11908
- });
11909
- };
11910
- //#endregion
11911
- //#region src/web/components/AddJobButton.tsx
11912
- /**
11913
- * A reusable button component for adding a new documentation job.
11914
- * Encapsulates both styling and HTMX behavior.
11915
- */
11916
- var AddJobButton = () => {
11917
- return /* @__PURE__ */ jsx(PrimaryButton, {
11918
- "hx-get": "/web/jobs/new",
11919
- "hx-target": "#addJobForm",
11920
- "hx-swap": "innerHTML",
11921
- children: "Add New Documentation"
11922
- });
11923
- };
11924
- //#endregion
11925
- //#region src/web/components/Toast.tsx
11926
- /**
11927
- * Toast notification component using Flowbite styling and Alpine.js for state management.
11928
- * Displays floating notifications for success, error, warning, and info messages.
11929
- */
11930
- var Toast = () => {
11931
- return /* @__PURE__ */ jsx("div", {
11932
- "x-data": true,
11933
- "x-show": "$store.toast.visible",
11934
- "x-transition:enter": "transition ease-out duration-300",
11935
- "x-transition:enter-start": "opacity-0 transform translate-y-2",
11936
- "x-transition:enter-end": "opacity-100 transform translate-y-0",
11937
- "x-transition:leave": "transition ease-in duration-200",
11938
- "x-transition:leave-start": "opacity-100",
11939
- "x-transition:leave-end": "opacity-0",
11940
- class: "fixed top-5 right-5 z-50",
11941
- style: "display: none;",
11942
- children: /* @__PURE__ */ jsxs("div", {
11943
- class: "flex items-center w-full max-w-xs p-4 text-gray-500 bg-white rounded-lg shadow dark:text-gray-400 dark:bg-gray-800",
11944
- role: "alert",
11945
- children: [
11946
- /* @__PURE__ */ jsxs("div", {
11947
- class: "inline-flex items-center justify-center shrink-0 w-8 h-8 rounded-lg",
11948
- "x-bind:class": "{\n 'text-green-500 bg-green-100 dark:bg-green-800 dark:text-green-200': $store.toast.type === 'success',\n 'text-red-500 bg-red-100 dark:bg-red-800 dark:text-red-200': $store.toast.type === 'error',\n 'text-orange-500 bg-orange-100 dark:bg-orange-700 dark:text-orange-200': $store.toast.type === 'warning',\n 'text-blue-500 bg-blue-100 dark:bg-blue-800 dark:text-blue-200': $store.toast.type === 'info'\n }",
11949
- children: [
11950
- /* @__PURE__ */ jsx("svg", {
11951
- "x-show": "$store.toast.type === 'success'",
11952
- class: "w-5 h-5",
11953
- "aria-hidden": "true",
11954
- xmlns: "http://www.w3.org/2000/svg",
11955
- fill: "currentColor",
11956
- viewBox: "0 0 20 20",
11957
- children: /* @__PURE__ */ jsx("path", { d: "M10 .5a9.5 9.5 0 1 0 9.5 9.5A9.51 9.51 0 0 0 10 .5Zm3.707 8.207-4 4a1 1 0 0 1-1.414 0l-2-2a1 1 0 0 1 1.414-1.414L9 10.586l3.293-3.293a1 1 0 0 1 1.414 1.414Z" })
11958
- }),
11959
- /* @__PURE__ */ jsx("svg", {
11960
- "x-show": "$store.toast.type === 'error'",
11961
- class: "w-5 h-5",
11962
- "aria-hidden": "true",
11963
- xmlns: "http://www.w3.org/2000/svg",
11964
- fill: "currentColor",
11965
- viewBox: "0 0 20 20",
11966
- children: /* @__PURE__ */ jsx("path", { d: "M10 .5a9.5 9.5 0 1 0 9.5 9.5A9.51 9.51 0 0 0 10 .5Zm3.707 11.793a1 1 0 1 1-1.414 1.414L10 11.414l-2.293 2.293a1 1 0 0 1-1.414-1.414L8.586 10 6.293 7.707a1 1 0 0 1 1.414-1.414L10 8.586l2.293-2.293a1 1 0 0 1 1.414 1.414L11.414 10l2.293 2.293Z" })
11967
- }),
11968
- /* @__PURE__ */ jsx("svg", {
11969
- "x-show": "$store.toast.type === 'warning'",
11970
- class: "w-5 h-5",
11971
- "aria-hidden": "true",
11972
- xmlns: "http://www.w3.org/2000/svg",
11973
- fill: "currentColor",
11974
- viewBox: "0 0 20 20",
11975
- children: /* @__PURE__ */ jsx("path", { d: "M10 .5a9.5 9.5 0 1 0 9.5 9.5A9.51 9.51 0 0 0 10 .5ZM10 15a1 1 0 1 1 0-2 1 1 0 0 1 0 2Zm1-4a1 1 0 0 1-2 0V6a1 1 0 0 1 2 0v5Z" })
11976
- }),
11977
- /* @__PURE__ */ jsx("svg", {
11978
- "x-show": "$store.toast.type === 'info'",
11979
- class: "w-5 h-5",
11980
- "aria-hidden": "true",
11981
- xmlns: "http://www.w3.org/2000/svg",
11982
- fill: "currentColor",
11983
- viewBox: "0 0 20 20",
11984
- children: /* @__PURE__ */ jsx("path", { d: "M10 .5a9.5 9.5 0 1 0 9.5 9.5A9.51 9.51 0 0 0 10 .5ZM9.5 4a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3ZM12 15H8a1 1 0 0 1 0-2h1v-3H8a1 1 0 0 1 0-2h2a1 1 0 0 1 1 1v4h1a1 1 0 0 1 0 2Z" })
11985
- })
11986
- ]
11987
- }),
11988
- /* @__PURE__ */ jsx("div", {
11989
- class: "ml-3 text-sm font-normal",
11990
- "x-text": "$store.toast.message"
11991
- }),
11992
- /* @__PURE__ */ jsxs("button", {
11993
- type: "button",
11994
- class: "ml-auto -mx-1.5 -my-1.5 bg-white text-gray-400 hover:text-gray-900 rounded-lg focus:ring-2 focus:ring-gray-300 p-1.5 hover:bg-gray-100 inline-flex items-center justify-center h-8 w-8 dark:text-gray-500 dark:hover:text-white dark:bg-gray-800 dark:hover:bg-gray-700",
11995
- "x-on:click": "$store.toast.hide()",
11996
- "aria-label": "Close",
11997
- children: [/* @__PURE__ */ jsx("span", {
11998
- class: "sr-only",
11999
- children: "Close"
12000
- }), /* @__PURE__ */ jsx("svg", {
12001
- class: "w-3 h-3",
12002
- "aria-hidden": "true",
12003
- xmlns: "http://www.w3.org/2000/svg",
12004
- fill: "none",
12005
- viewBox: "0 0 14 14",
12006
- children: /* @__PURE__ */ jsx("path", {
12007
- stroke: "currentColor",
12008
- "stroke-linecap": "round",
12009
- "stroke-linejoin": "round",
12010
- "stroke-width": "2",
12011
- d: "m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6"
12012
- })
12013
- })]
12014
- })
12015
- ]
12016
- })
12017
- });
12018
- };
12019
- //#endregion
12020
- //#region src/web/components/Layout.tsx
12021
- /**
12022
- * Base HTML layout component for all pages.
12023
- * Includes common head elements, header, and scripts.
12024
- * @param props - Component props including title, version, children, and eventClientConfig.
12025
- */
12026
- var Layout = ({ title, version, children, eventClientConfig }) => {
12027
- const versionString = version || "2.4.5";
12028
- const versionInitializer = `versionUpdate({ currentVersion: ${versionString ? `'${versionString}'` : "null"} })`;
12029
- return /* @__PURE__ */ jsxs("html", {
12030
- lang: "en",
12031
- children: [/* @__PURE__ */ jsxs("head", { children: [
12032
- /* @__PURE__ */ jsx("meta", { charset: "UTF-8" }),
12033
- /* @__PURE__ */ jsx("meta", {
12034
- name: "viewport",
12035
- content: "width=device-width, initial-scale=1.0"
12036
- }),
12037
- /* @__PURE__ */ jsx("title", {
12038
- safe: true,
12039
- children: title
12040
- }),
12041
- /* @__PURE__ */ jsx("link", {
12042
- rel: "apple-touch-icon",
12043
- sizes: "57x57",
12044
- href: "/apple-icon-57x57.png"
12045
- }),
12046
- /* @__PURE__ */ jsx("link", {
12047
- rel: "apple-touch-icon",
12048
- sizes: "60x60",
12049
- href: "/apple-icon-60x60.png"
12050
- }),
12051
- /* @__PURE__ */ jsx("link", {
12052
- rel: "apple-touch-icon",
12053
- sizes: "72x72",
12054
- href: "/apple-icon-72x72.png"
12055
- }),
12056
- /* @__PURE__ */ jsx("link", {
12057
- rel: "apple-touch-icon",
12058
- sizes: "76x76",
12059
- href: "/apple-icon-76x76.png"
12060
- }),
12061
- /* @__PURE__ */ jsx("link", {
12062
- rel: "apple-touch-icon",
12063
- sizes: "114x114",
12064
- href: "/apple-icon-114x114.png"
12065
- }),
12066
- /* @__PURE__ */ jsx("link", {
12067
- rel: "apple-touch-icon",
12068
- sizes: "120x120",
12069
- href: "/apple-icon-120x120.png"
12070
- }),
12071
- /* @__PURE__ */ jsx("link", {
12072
- rel: "apple-touch-icon",
12073
- sizes: "144x144",
12074
- href: "/apple-icon-144x144.png"
12075
- }),
12076
- /* @__PURE__ */ jsx("link", {
12077
- rel: "apple-touch-icon",
12078
- sizes: "152x152",
12079
- href: "/apple-icon-152x152.png"
12080
- }),
12081
- /* @__PURE__ */ jsx("link", {
12082
- rel: "apple-touch-icon",
12083
- sizes: "180x180",
12084
- href: "/apple-icon-180x180.png"
12085
- }),
12086
- /* @__PURE__ */ jsx("link", {
12087
- rel: "icon",
12088
- type: "image/png",
12089
- sizes: "192x192",
12090
- href: "/android-icon-192x192.png"
12091
- }),
12092
- /* @__PURE__ */ jsx("link", {
12093
- rel: "icon",
12094
- type: "image/png",
12095
- sizes: "32x32",
12096
- href: "/favicon-32x32.png"
12097
- }),
12098
- /* @__PURE__ */ jsx("link", {
12099
- rel: "icon",
12100
- type: "image/png",
12101
- sizes: "96x96",
12102
- href: "/favicon-96x96.png"
12103
- }),
12104
- /* @__PURE__ */ jsx("link", {
12105
- rel: "icon",
12106
- type: "image/png",
12107
- sizes: "16x16",
12108
- href: "/favicon-16x16.png"
12109
- }),
12110
- /* @__PURE__ */ jsx("link", {
12111
- rel: "shortcut icon",
12112
- href: "/favicon.ico"
12113
- }),
12114
- /* @__PURE__ */ jsx("link", {
12115
- rel: "manifest",
12116
- href: "/manifest.json"
12117
- }),
12118
- /* @__PURE__ */ jsx("meta", {
12119
- name: "msapplication-TileColor",
12120
- content: "#ffffff"
12121
- }),
12122
- /* @__PURE__ */ jsx("meta", {
12123
- name: "msapplication-TileImage",
12124
- content: "/ms-icon-144x144.png"
12125
- }),
12126
- /* @__PURE__ */ jsx("meta", {
12127
- name: "theme-color",
12128
- content: "#ffffff"
12129
- }),
12130
- /* @__PURE__ */ jsx("link", {
12131
- rel: "stylesheet",
12132
- href: "/assets/main.css"
12133
- }),
12134
- /* @__PURE__ */ jsx("style", { children: `
12135
- .htmx-indicator {
12136
- display: none;
12137
- }
12138
- .htmx-request .htmx-indicator {
12139
- display: block;
12140
- }
12141
- .htmx-request.htmx-indicator {
12142
- display: block;
12143
- }
12144
- /* Default: Hide skeleton, show results container */
12145
- #searchResultsContainer .search-skeleton { display: none; }
12146
- #searchResultsContainer .search-results { display: block; } /* Or as needed */
12147
-
12148
- /* Request in progress: Show skeleton, hide results */
12149
- #searchResultsContainer.htmx-request .search-skeleton { display: block; } /* Or flex etc. */
12150
- #searchResultsContainer.htmx-request .search-results { display: none; }
12151
-
12152
- /* Keep button spinner logic */
12153
- form .htmx-indicator .spinner { display: flex; }
12154
- form .htmx-indicator .search-text { display: none; }
12155
- form .spinner { display: none; }
12156
- ` })
12157
- ] }), /* @__PURE__ */ jsxs("body", {
12158
- class: "bg-gray-50 dark:bg-gray-900",
12159
- "hx-ext": "morph",
12160
- children: [
12161
- /* @__PURE__ */ jsx(Toast, {}),
12162
- /* @__PURE__ */ jsx("header", {
12163
- class: "bg-white border-b border-gray-200 dark:bg-gray-800 dark:border-gray-700",
12164
- "x-data": versionInitializer,
12165
- "x-init": "queueCheck()",
12166
- children: /* @__PURE__ */ jsxs("div", {
12167
- class: "container max-w-2xl mx-auto px-4 py-4",
12168
- children: [/* @__PURE__ */ jsxs("div", {
12169
- class: "hidden sm:flex items-center justify-between",
12170
- children: [/* @__PURE__ */ jsxs("div", {
12171
- class: "flex items-center gap-3",
12172
- children: [
12173
- /* @__PURE__ */ jsxs("a", {
12174
- href: "https://grounded.tools",
12175
- target: "_blank",
12176
- rel: "noopener noreferrer",
12177
- class: "text-xl font-medium text-gray-900 dark:text-white hover:text-primary-500 dark:hover:text-primary-400 transition-colors font-brand",
12178
- children: [
12179
- /* @__PURE__ */ jsx("span", {
12180
- class: "text-primary-600 dark:text-primary-300",
12181
- children: "grounded"
12182
- }),
12183
- /* @__PURE__ */ jsx("span", {
12184
- class: "text-accent-500",
12185
- children: "."
12186
- }),
12187
- /* @__PURE__ */ jsx("span", {
12188
- class: "text-gray-900 dark:text-gray-100",
12189
- children: "tools"
12190
- })
12191
- ]
12192
- }),
12193
- /* @__PURE__ */ jsx("span", {
12194
- class: "text-gray-400 dark:text-gray-400",
12195
- children: "|"
12196
- }),
12197
- /* @__PURE__ */ jsx("a", {
12198
- href: "/",
12199
- class: "text-lg font-semibold text-gray-900 dark:text-white hover:text-primary-500 dark:hover:text-primary-400 transition-colors font-brand",
12200
- children: "Docs MCP Server"
12201
- }),
12202
- versionString ? /* @__PURE__ */ jsxs("span", {
12203
- safe: true,
12204
- class: "text-sm font-normal text-gray-500 dark:text-slate-400",
12205
- title: `Version ${versionString}`,
12206
- children: ["v", versionString]
12207
- }) : null
12208
- ]
12209
- }), /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsxs("span", {
12210
- "x-show": "hasUpdate",
12211
- "x-cloak": true,
12212
- class: "inline-flex items-center gap-2 rounded-full bg-amber-100 dark:bg-amber-500/20 px-3 py-1.5 text-sm font-medium text-amber-700 dark:text-amber-300 border border-amber-200 dark:border-amber-500/30",
12213
- role: "status",
12214
- "aria-live": "polite",
12215
- children: [/* @__PURE__ */ jsx("span", {
12216
- class: "flex h-4 w-4 items-center justify-center rounded-full bg-amber-500 text-amber-800 dark:text-amber-900 text-xs font-bold",
12217
- children: "!"
12218
- }), /* @__PURE__ */ jsx("a", {
12219
- "x-bind:href": "latestReleaseUrl",
12220
- target: "_blank",
12221
- rel: "noopener noreferrer",
12222
- class: "hover:text-amber-800 dark:hover:text-amber-200 transition-colors",
12223
- children: /* @__PURE__ */ jsx("span", {
12224
- class: "mr-1",
12225
- children: "Update available"
12226
- })
12227
- })]
12228
- }) })]
12229
- }), /* @__PURE__ */ jsxs("div", {
12230
- class: "sm:hidden space-y-2",
12231
- children: [
12232
- /* @__PURE__ */ jsx("div", {
12233
- class: "flex justify-center",
12234
- children: /* @__PURE__ */ jsxs("a", {
12235
- href: "https://grounded.tools",
12236
- target: "_blank",
12237
- rel: "noopener noreferrer",
12238
- class: "text-xl font-medium text-gray-900 dark:text-white hover:text-primary-500 dark:hover:text-primary-400 transition-colors font-brand",
12239
- children: [
12240
- /* @__PURE__ */ jsx("span", {
12241
- class: "text-primary-600 dark:text-primary-300",
12242
- children: "grounded"
12243
- }),
12244
- /* @__PURE__ */ jsx("span", {
12245
- class: "text-accent-500",
12246
- children: "."
12247
- }),
12248
- /* @__PURE__ */ jsx("span", {
12249
- class: "text-gray-900 dark:text-gray-100",
12250
- children: "tools"
12251
- })
12252
- ]
12253
- })
12254
- }),
12255
- /* @__PURE__ */ jsxs("div", {
12256
- class: "flex items-center justify-center gap-2",
12257
- children: [/* @__PURE__ */ jsx("a", {
12258
- href: "/",
12259
- class: "text-lg font-semibold text-gray-900 dark:text-white hover:text-primary-500 dark:hover:text-primary-400 transition-colors font-brand",
12260
- children: "Docs MCP Server"
12261
- }), versionString ? /* @__PURE__ */ jsxs("span", {
12262
- safe: true,
12263
- class: "text-sm font-normal text-gray-500 dark:text-slate-400",
12264
- title: `Version ${versionString}`,
12265
- children: ["v", versionString]
12266
- }) : null]
12267
- }),
12268
- /* @__PURE__ */ jsx("div", {
12269
- class: "flex justify-center",
12270
- children: /* @__PURE__ */ jsxs("span", {
12271
- "x-show": "hasUpdate",
12272
- "x-cloak": true,
12273
- class: "inline-flex items-center gap-2 rounded-full bg-amber-100 dark:bg-amber-500/20 px-3 py-1.5 text-sm font-medium text-amber-700 dark:text-amber-300 border border-amber-200 dark:border-amber-500/30",
12274
- role: "status",
12275
- "aria-live": "polite",
12276
- children: [/* @__PURE__ */ jsx("span", {
12277
- class: "flex h-4 w-4 items-center justify-center rounded-full bg-amber-500 text-amber-800 dark:text-amber-900 text-xs font-bold",
12278
- children: "!"
12279
- }), /* @__PURE__ */ jsx("a", {
12280
- "x-bind:href": "latestReleaseUrl",
12281
- target: "_blank",
12282
- rel: "noopener noreferrer",
12283
- class: "hover:text-amber-800 dark:hover:text-amber-200 transition-colors",
12284
- children: /* @__PURE__ */ jsx("span", {
12285
- class: "mr-1",
12286
- children: "Update available"
12287
- })
12288
- })]
12289
- })
12290
- })
12291
- ]
12292
- })]
12293
- })
12294
- }),
12295
- /* @__PURE__ */ jsx("div", {
12296
- class: "container max-w-2xl mx-auto px-4 py-6",
12297
- children: /* @__PURE__ */ jsx("main", { children })
12298
- }),
12299
- /* @__PURE__ */ jsx("script", { children: `window.__EVENT_CLIENT_CONFIG__ = ${JSON.stringify(eventClientConfig)};` }),
12300
- /* @__PURE__ */ jsx("script", {
12301
- type: "module",
12302
- src: "/assets/main.js"
12303
- })
12304
- ]
12305
- })]
12306
- });
12307
- };
12308
- //#endregion
12309
- //#region src/web/routes/index.tsx
12310
- /**
12311
- * Registers the root route that serves the main HTML page.
12312
- * @param server - The Fastify instance.
12313
- * @param externalWorkerUrl - Optional URL for external worker service.
12314
- */
12315
- function registerIndexRoute(server, externalWorkerUrl) {
12316
- server.get("/", async (_, reply) => {
12317
- reply.type("text/html");
12318
- return "<!DOCTYPE html>" + /* @__PURE__ */ jsxs(Layout, {
12319
- title: "MCP Docs",
12320
- eventClientConfig: {
12321
- useRemoteWorker: Boolean(externalWorkerUrl),
12322
- trpcUrl: externalWorkerUrl ? `${externalWorkerUrl}/api` : void 0
12323
- },
12324
- children: [
12325
- /* @__PURE__ */ jsx("div", {
12326
- id: "analytics-stats",
12327
- "hx-get": "/web/stats",
12328
- "hx-trigger": "load, library-change from:body",
12329
- "hx-swap": "morph:innerHTML",
12330
- children: /* @__PURE__ */ jsxs("div", {
12331
- class: "grid grid-cols-1 sm:grid-cols-3 gap-4 mb-4 animate-pulse",
12332
- children: [
12333
- /* @__PURE__ */ jsx("div", { class: "p-4 bg-white rounded-lg shadow dark:bg-gray-800 border border-gray-300 dark:border-gray-600 h-20" }),
12334
- /* @__PURE__ */ jsx("div", { class: "p-4 bg-white rounded-lg shadow dark:bg-gray-800 border border-gray-300 dark:border-gray-600 h-20" }),
12335
- /* @__PURE__ */ jsx("div", { class: "p-4 bg-white rounded-lg shadow dark:bg-gray-800 border border-gray-300 dark:border-gray-600 h-20" })
12336
- ]
12337
- })
12338
- }),
12339
- /* @__PURE__ */ jsxs("section", {
12340
- class: "mb-4 p-4 bg-white rounded-lg shadow dark:bg-gray-800 border border-gray-300 dark:border-gray-600",
12341
- children: [/* @__PURE__ */ jsxs("div", {
12342
- class: "flex items-center justify-between mb-2",
12343
- children: [/* @__PURE__ */ jsx("h2", {
12344
- class: "text-xl font-semibold text-gray-900 dark:text-white",
12345
- children: "Job Queue"
12346
- }), /* @__PURE__ */ jsx("button", {
12347
- id: "clear-completed-btn",
12348
- type: "button",
12349
- class: "text-xs px-3 py-1.5 text-gray-400 bg-gray-50 border border-gray-200 rounded-lg cursor-not-allowed focus:ring-4 focus:outline-none transition-colors duration-150 dark:bg-gray-700 dark:text-gray-500 dark:border-gray-600",
12350
- title: "Clear all completed, cancelled, and failed jobs",
12351
- "hx-post": "/web/jobs/clear-completed",
12352
- "hx-trigger": "click",
12353
- "hx-on": "htmx:afterRequest: document.dispatchEvent(new Event('job-list-refresh'))",
12354
- "hx-swap": "none",
12355
- disabled: true,
12356
- children: "Clear Completed Jobs"
12357
- })]
12358
- }), /* @__PURE__ */ jsx("div", {
12359
- id: "job-queue",
12360
- "hx-get": "/web/jobs",
12361
- "hx-trigger": "load, job-status-change from:body, job-progress from:body, job-list-change from:body, job-list-refresh from:body",
12362
- "hx-swap": "morph:innerHTML",
12363
- children: /* @__PURE__ */ jsxs("div", {
12364
- class: "animate-pulse",
12365
- children: [
12366
- /* @__PURE__ */ jsx("div", { class: "h-[0.8em] bg-gray-200 rounded-full dark:bg-gray-700 w-48 mb-4" }),
12367
- /* @__PURE__ */ jsx("div", { class: "h-[0.8em] bg-gray-200 rounded-full dark:bg-gray-700 w-full mb-2.5" }),
12368
- /* @__PURE__ */ jsx("div", { class: "h-[0.8em] bg-gray-200 rounded-full dark:bg-gray-700 w-full mb-2.5" })
12369
- ]
12370
- })
12371
- })]
12372
- }),
12373
- /* @__PURE__ */ jsx("section", {
12374
- class: "mb-8",
12375
- children: /* @__PURE__ */ jsx("div", {
12376
- id: "addJobForm",
12377
- children: /* @__PURE__ */ jsx(AddJobButton, {})
12378
- })
12379
- }),
12380
- /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("h2", {
12381
- class: "text-xl font-semibold mb-2 text-gray-900 dark:text-white",
12382
- children: "Indexed Documentation"
12383
- }), /* @__PURE__ */ jsx("div", {
12384
- id: "indexed-docs",
12385
- "hx-get": "/web/libraries",
12386
- "hx-trigger": "load, library-change from:body",
12387
- "hx-swap": "morph:innerHTML",
12388
- children: /* @__PURE__ */ jsxs("div", {
12389
- class: "animate-pulse",
12390
- children: [
12391
- /* @__PURE__ */ jsx("div", { class: "h-[0.8em] bg-gray-200 rounded-full dark:bg-gray-700 w-48 mb-4" }),
12392
- /* @__PURE__ */ jsx("div", { class: "h-[0.8em] bg-gray-200 rounded-full dark:bg-gray-700 w-full mb-2.5" }),
12393
- /* @__PURE__ */ jsx("div", { class: "h-[0.8em] bg-gray-200 rounded-full dark:bg-gray-700 w-full mb-2.5" })
12394
- ]
12395
- })
12396
- })] })
12397
- ]
12398
- });
12399
- });
12400
- }
12401
- //#endregion
12402
- //#region src/web/routes/jobs/cancel.tsx
12403
- /**
12404
- * Registers the API route for cancelling jobs.
12405
- * @param server - The Fastify instance.
12406
- * @param cancelJobTool - The tool instance for cancelling jobs.
12407
- */
12408
- function registerCancelJobRoute(server, cancelJobTool) {
12409
- server.post("/web/jobs/:jobId/cancel", async (request, reply) => {
12410
- const { jobId } = request.params;
12411
- try {
12412
- await cancelJobTool.execute({ jobId });
12413
- return {
12414
- success: true,
12415
- message: "Job cancelled successfully"
12416
- };
12417
- } catch (error) {
12418
- if (error instanceof ToolError) {
12419
- reply.status(400);
12420
- return {
12421
- success: false,
12422
- message: error.message
12423
- };
12424
- } else {
12425
- reply.status(500);
12426
- return {
12427
- success: false,
12428
- message: "Internal server error"
12429
- };
12430
- }
12431
- }
12432
- });
12433
- }
12434
- //#endregion
12435
- //#region src/web/routes/jobs/clear-completed.tsx
12436
- /**
12437
- * Registers the API route for clearing completed jobs.
12438
- * @param server - The Fastify instance.
12439
- * @param clearCompletedJobsTool - The tool instance for clearing completed jobs.
12440
- */
12441
- function registerClearCompletedJobsRoute(server, clearCompletedJobsTool) {
12442
- server.post("/web/jobs/clear-completed", async (_, reply) => {
12443
- try {
12444
- await clearCompletedJobsTool.execute({});
12445
- reply.type("application/json");
12446
- return {
12447
- success: true,
12448
- message: "Completed jobs cleared successfully"
12449
- };
12450
- } catch (error) {
12451
- if (error instanceof ToolError) {
12452
- reply.code(400);
12453
- return {
12454
- success: false,
12455
- message: error.message
12456
- };
12457
- } else {
12458
- reply.code(500);
12459
- return {
12460
- success: false,
12461
- message: `Internal server error: ${error instanceof Error ? error.message : String(error)}`
12462
- };
12463
- }
12464
- }
12465
- });
12466
- }
12467
- //#endregion
12468
- //#region src/web/components/VersionBadge.tsx
12469
- var VersionBadge = ({ version }) => {
12470
- if (!version) return null;
12471
- return /* @__PURE__ */ jsx("span", {
12472
- class: "bg-primary-100 text-primary-800 text-xs font-medium me-2 px-1.5 py-0.5 rounded dark:bg-primary-900 dark:text-primary-300",
12473
- children: /* @__PURE__ */ jsx("span", {
12474
- safe: true,
12475
- children: version
12476
- })
12477
- });
12478
- };
12479
- //#endregion
12480
- //#region src/web/components/StatusBadge.tsx
12481
- /**
12482
- * StatusBadge component displays version status with appropriate styling.
12483
- * Uses database VersionStatus and helper functions for proper display.
12484
- */
12485
- /**
12486
- * Get CSS classes for status badge based on status type.
12487
- */
12488
- function getStatusClasses(status) {
12489
- const baseClasses = "px-1.5 py-0.5 text-xs font-medium rounded";
12490
- switch (status) {
12491
- case VersionStatus.COMPLETED: return `${baseClasses} bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300`;
12492
- case VersionStatus.RUNNING:
12493
- case VersionStatus.UPDATING: return `${baseClasses} bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300`;
12494
- case VersionStatus.QUEUED: return `${baseClasses} bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300`;
12495
- case VersionStatus.FAILED: return `${baseClasses} bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300`;
12496
- case VersionStatus.CANCELLED: return `${baseClasses} bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-300`;
12497
- case VersionStatus.NOT_INDEXED:
12498
- default: return `${baseClasses} bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400`;
12499
- }
12500
- }
12501
- var StatusBadge = ({ status, showDescription = true }) => /* @__PURE__ */ jsx("span", {
12502
- class: getStatusClasses(status),
12503
- children: showDescription ? getStatusDescription(status) : status
12504
- });
12505
- //#endregion
12506
- //#region src/web/components/ProgressBar.tsx
12507
- var ProgressBar = ({ progress, showText = true }) => {
12508
- const isIndeterminate = progress.totalDiscovered === 1;
12509
- const percentage = progress.totalPages > 0 ? Math.round(progress.pages / progress.totalPages * 100) : 0;
12510
- const getProgressText = () => {
12511
- if (isIndeterminate) return "Discovering pages...";
12512
- const baseText = `${progress.pages}/${progress.totalPages} pages (${percentage}%)`;
12513
- if (progress.totalDiscovered > progress.totalPages) return `${baseText} • ${progress.totalDiscovered} total`;
12514
- return baseText;
12515
- };
12516
- return /* @__PURE__ */ jsxs("div", {
12517
- class: "w-full",
12518
- children: [showText && /* @__PURE__ */ jsxs("div", {
12519
- class: "flex justify-between text-xs text-gray-600 dark:text-gray-400 mb-1",
12520
- children: [/* @__PURE__ */ jsx("span", { children: "Progress" }), /* @__PURE__ */ jsx("span", {
12521
- safe: true,
12522
- children: getProgressText()
12523
- })]
12524
- }), /* @__PURE__ */ jsx("div", {
12525
- class: "w-full bg-gray-200 rounded-full h-2 dark:bg-gray-700",
12526
- children: isIndeterminate ? /* @__PURE__ */ jsx("div", {
12527
- class: "bg-blue-600 h-2 rounded-full animate-pulse",
12528
- style: "width: 30%"
12529
- }) : /* @__PURE__ */ jsx("div", {
12530
- class: "bg-blue-600 h-2 rounded-full transition-all duration-300",
12531
- style: `width: ${percentage}%`
12532
- })
12533
- })]
12534
- });
12535
- };
12536
- //#endregion
12537
- //#region src/web/components/LoadingSpinner.tsx
12538
- /**
12539
- * Renders an SVG loading spinner icon.
12540
- * Used for indicating loading states in buttons or other elements.
12541
- */
12542
- var LoadingSpinner = ({ class: className = "text-white" }) => /* @__PURE__ */ jsxs("svg", {
12543
- class: `animate-spin h-4 w-4 ${className}`,
12544
- xmlns: "http://www.w3.org/2000/svg",
12545
- fill: "none",
12546
- viewBox: "0 0 24 24",
12547
- children: [/* @__PURE__ */ jsx("circle", {
12548
- class: "opacity-25",
12549
- cx: "12",
12550
- cy: "12",
12551
- r: "10",
12552
- stroke: "currentColor",
12553
- "stroke-width": "4"
12554
- }), /* @__PURE__ */ jsx("path", {
12555
- class: "opacity-75",
12556
- fill: "currentColor",
12557
- d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
12558
- })]
12559
- });
12560
- //#endregion
12561
- //#region src/web/components/JobItem.tsx
12562
- /**
12563
- * Renders a single job item with its details and status.
12564
- * @param props - Component props including the job information.
12565
- */
12566
- var JobItem = ({ job }) => {
12567
- job.dbStatus || job.status;
12568
- const isActiveJob = job.dbStatus ? isActiveStatus(job.dbStatus) : job.status === PipelineJobStatus.QUEUED || job.status === PipelineJobStatus.RUNNING;
12569
- return /* @__PURE__ */ jsx("div", {
12570
- id: `job-item-${job.id}`,
12571
- class: "block p-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600",
12572
- "data-job-id": job.id,
12573
- "x-data": "{ jobId: $el.dataset.jobId, confirming: $el.dataset.confirming === 'true', isStopping: false }",
12574
- children: /* @__PURE__ */ jsxs("div", {
12575
- class: "flex items-start justify-between",
12576
- children: [/* @__PURE__ */ jsxs("div", {
12577
- class: "flex-1",
12578
- children: [
12579
- /* @__PURE__ */ jsxs("p", {
12580
- class: "text-sm font-medium text-gray-900 dark:text-white",
12581
- children: [
12582
- /* @__PURE__ */ jsx("span", {
12583
- safe: true,
12584
- children: job.library
12585
- }),
12586
- " ",
12587
- /* @__PURE__ */ jsx(VersionBadge, { version: job.version })
12588
- ]
12589
- }),
12590
- /* @__PURE__ */ jsx("div", {
12591
- class: "text-xs text-gray-500 dark:text-gray-400 mt-1",
12592
- children: job.startedAt ? /* @__PURE__ */ jsxs("div", { children: [
12593
- "Last Indexed:",
12594
- " ",
12595
- /* @__PURE__ */ jsx("span", {
12596
- safe: true,
12597
- children: new Date(job.startedAt).toLocaleString()
12598
- })
12599
- ] }) : null
12600
- }),
12601
- job.progress && job.progress.totalPages > 0 && isActiveJob ? /* @__PURE__ */ jsx("div", {
12602
- class: "mt-2",
12603
- children: /* @__PURE__ */ jsx(ProgressBar, { progress: job.progress })
12604
- }) : null,
12605
- job.errorMessage || job.error ? /* @__PURE__ */ jsxs("div", {
12606
- class: "mt-2 p-2 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded text-xs",
12607
- children: [/* @__PURE__ */ jsx("div", {
12608
- class: "font-medium text-red-800 dark:text-red-300 mb-1",
12609
- children: "Error:"
12610
- }), /* @__PURE__ */ jsx("div", {
12611
- safe: true,
12612
- class: "text-red-700 dark:text-red-400",
12613
- children: job.errorMessage || job.error
12614
- })]
12615
- }) : null
12616
- ]
12617
- }), /* @__PURE__ */ jsxs("div", {
12618
- class: "flex flex-col items-end gap-2 ml-4",
12619
- children: [/* @__PURE__ */ jsxs("div", {
12620
- class: "flex items-center gap-2",
12621
- children: [job.dbStatus ? /* @__PURE__ */ jsx(StatusBadge, { status: job.dbStatus }) : /* @__PURE__ */ jsx("span", {
12622
- class: `px-1.5 py-0.5 text-xs font-medium rounded ${job.status === PipelineJobStatus.COMPLETED ? "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300" : job.error ? "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300" : "bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300"}`,
12623
- children: job.status
12624
- }), isActiveJob && /* @__PURE__ */ jsxs("button", {
12625
- type: "button",
12626
- class: "font-medium rounded-lg text-xs p-1 text-center inline-flex items-center transition-colors duration-150 ease-in-out",
12627
- title: "Stop this job",
12628
- "x-bind:class": `confirming ? 'bg-red-600 text-white border-red-600 focus:ring-4 focus:outline-none focus:ring-red-300 dark:bg-red-700 dark:border-red-700 dark:focus:ring-red-800' : 'border border-gray-300 bg-white text-red-600 hover:bg-red-50 focus:ring-4 focus:outline-none focus:ring-red-100 dark:border-gray-600 dark:bg-gray-800 dark:text-red-400 dark:hover:bg-gray-700 dark:focus:ring-red-900'`,
12629
- "x-on:click": "\n if (confirming) {\n isStopping = true;\n window.confirmationManager.clear($root.id);\n fetch('/web/jobs/' + jobId + '/cancel', {\n method: 'POST',\n headers: { 'Accept': 'application/json' },\n })\n .then(r => r.json())\n .then(() => {\n confirming = false;\n isStopping = false;\n document.dispatchEvent(new CustomEvent('job-list-refresh'));\n })\n .catch(() => { isStopping = false; });\n } else {\n confirming = true;\n isStopping = false;\n window.confirmationManager.start($root.id);\n }\n ",
12630
- "x-bind:disabled": "isStopping",
12631
- children: [
12632
- /* @__PURE__ */ jsxs("span", {
12633
- "x-show": "!confirming && !isStopping",
12634
- children: [/* @__PURE__ */ jsx("svg", {
12635
- class: "w-4 h-4",
12636
- "aria-hidden": "true",
12637
- fill: "currentColor",
12638
- viewBox: "0 0 20 20",
12639
- children: /* @__PURE__ */ jsx("rect", {
12640
- x: "5",
12641
- y: "5",
12642
- width: "10",
12643
- height: "10",
12644
- rx: "2"
12645
- })
12646
- }), /* @__PURE__ */ jsx("span", {
12647
- class: "sr-only",
12648
- children: "Stop job"
12649
- })]
12650
- }),
12651
- /* @__PURE__ */ jsx("span", {
12652
- "x-show": "confirming && !isStopping",
12653
- class: "px-2",
12654
- children: "Cancel?"
12655
- }),
12656
- /* @__PURE__ */ jsxs("span", {
12657
- "x-show": "isStopping",
12658
- children: [/* @__PURE__ */ jsx(LoadingSpinner, {}), /* @__PURE__ */ jsx("span", {
12659
- class: "sr-only",
12660
- children: "Stopping..."
12661
- })]
12662
- })
12663
- ]
12664
- })]
12665
- }), job.error ? /* @__PURE__ */ jsx("span", {
12666
- class: "bg-red-100 text-red-800 text-xs font-medium px-1.5 py-0.5 rounded dark:bg-red-900 dark:text-red-300",
12667
- children: "Error"
12668
- }) : null]
12669
- })]
12670
- })
12671
- });
12672
- };
12673
- //#endregion
12674
- //#region src/web/components/JobList.tsx
12675
- /**
12676
- * Renders a list of JobItem components or a message if the list is empty.
12677
- * Also renders an out-of-band swap for the "Clear Completed Jobs" button state.
12678
- * @param props - Component props including the array of jobs.
12679
- */
12680
- var JobList = ({ jobs }) => {
12681
- const hasJobs = jobs.length > 0;
12682
- return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("div", {
12683
- id: "job-list",
12684
- class: "space-y-2 animate-[fadeSlideIn_0.2s_ease-out]",
12685
- children: hasJobs ? jobs.map((job) => /* @__PURE__ */ jsx(JobItem, { job })) : /* @__PURE__ */ jsx("p", {
12686
- class: "text-center text-gray-500 dark:text-gray-400",
12687
- children: "No pending jobs."
12688
- })
12689
- }), /* @__PURE__ */ jsx("button", {
12690
- id: "clear-completed-btn",
12691
- "hx-swap-oob": "true",
12692
- type: "button",
12693
- class: `text-xs px-3 py-1.5 rounded-lg focus:ring-4 focus:outline-none transition-colors duration-150 ${hasJobs ? "text-gray-700 bg-gray-100 border border-gray-300 hover:bg-gray-200 focus:ring-gray-100 dark:bg-gray-600 dark:text-gray-300 dark:border-gray-500 dark:hover:bg-gray-700 dark:focus:ring-gray-700" : "text-gray-400 bg-gray-50 border border-gray-200 cursor-not-allowed dark:bg-gray-700 dark:text-gray-500 dark:border-gray-600"}`,
12694
- title: "Clear all completed, cancelled, and failed jobs",
12695
- "hx-post": "/web/jobs/clear-completed",
12696
- "hx-trigger": "click",
12697
- "hx-on": "htmx:afterRequest: document.dispatchEvent(new Event('job-list-refresh'))",
12698
- "hx-swap": "none",
12699
- disabled: !hasJobs,
12700
- children: "Clear Completed Jobs"
12701
- })] });
12702
- };
12703
- //#endregion
12704
- //#region src/web/routes/jobs/list.tsx
12705
- /**
12706
- * Registers the API route for listing jobs.
12707
- * @param server - The Fastify instance.
12708
- * @param listJobsTool - The tool instance for listing jobs.
12709
- */
12710
- function registerJobListRoutes(server, listJobsTool) {
12711
- server.get("/web/jobs", async () => {
12712
- return /* @__PURE__ */ jsx(JobList, { jobs: (await listJobsTool.execute({})).jobs });
12713
- });
12714
- }
12715
- //#endregion
12716
- //#region src/web/components/AddVersionButton.tsx
12717
- /**
12718
- * A reusable button component for adding a new version to a library.
12719
- * Encapsulates both styling and HTMX behavior.
12720
- */
12721
- var AddVersionButton = ({ libraryName }) => {
12722
- return /* @__PURE__ */ jsx(PrimaryButton, {
12723
- "hx-get": `/web/libraries/${encodeURIComponent(libraryName)}/add-version-form`,
12724
- "hx-target": "#add-version-form-container",
12725
- "hx-swap": "innerHTML",
12726
- children: "Add New Version"
12727
- });
12728
- };
12729
- //#endregion
12730
- //#region src/web/components/Alert.tsx
12731
- /**
12732
- * Reusable Alert component using Flowbite styling.
12733
- * Displays messages with appropriate colors and icons based on the type.
12734
- * @param props - Component props including type, title (optional), and message.
12735
- */
12736
- var Alert = ({ type, title, message }) => {
12737
- let iconSvg;
12738
- let colorClasses;
12739
- let defaultTitle;
12740
- switch (type) {
12741
- case "success":
12742
- defaultTitle = "Success:";
12743
- colorClasses = "text-green-800 border-green-300 bg-green-50 dark:bg-gray-800 dark:text-green-400 dark:border-green-800";
12744
- iconSvg = /* @__PURE__ */ jsx("svg", {
12745
- class: "shrink-0 inline w-4 h-4 me-3",
12746
- "aria-hidden": "true",
12747
- xmlns: "http://www.w3.org/2000/svg",
12748
- fill: "currentColor",
12749
- viewBox: "0 0 20 20",
12750
- children: /* @__PURE__ */ jsx("path", { d: "M10 .5a9.5 9.5 0 1 0 9.5 9.5A9.51 9.51 0 0 0 10 .5Zm9.5 9.5A9.5 9.5 0 0 1 10 19a9.46 9.46 0 0 1-1.671-.14c-.165-.05-.3-.19-.42-.335l-.165-.165c-.19-.2-.3-.425-.3-.655A4.2 4.2 0 0 1 4.5 10a4.25 4.25 0 0 1 7.462-2.882l1.217 1.217a3.175 3.175 0 0 0 4.5.01l.106-.106a.934.934 0 0 0 .1-.36ZM10 11a1 1 0 1 0 0 2 1 1 0 0 0 0-2Z" })
12751
- });
12752
- break;
12753
- case "error":
12754
- defaultTitle = "Error:";
12755
- colorClasses = "text-red-800 border-red-300 bg-red-50 dark:bg-gray-800 dark:text-red-400 dark:border-red-800";
12756
- iconSvg = /* @__PURE__ */ jsx("svg", {
12757
- class: "shrink-0 inline w-4 h-4 me-3",
12758
- "aria-hidden": "true",
12759
- xmlns: "http://www.w3.org/2000/svg",
12760
- fill: "currentColor",
12761
- viewBox: "0 0 20 20",
12762
- children: /* @__PURE__ */ jsx("path", { d: "M10 .5a9.5 9.5 0 1 0 9.5 9.5A9.51 9.51 0 0 0 10 .5ZM9.5 4a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3ZM12 15H8a1 1 0 0 1 0-2h1v-3h-1a1 1 0 0 1 0-2h2a1 1 0 0 1 1 1v4h1a1 1 0 0 1 0 2Z" })
12763
- });
12764
- break;
12765
- case "warning":
12766
- defaultTitle = "Warning:";
12767
- colorClasses = "text-yellow-800 border-yellow-300 bg-yellow-50 dark:bg-gray-800 dark:text-yellow-300 dark:border-yellow-800";
12768
- iconSvg = /* @__PURE__ */ jsx("svg", {
12769
- class: "shrink-0 inline w-4 h-4 me-3",
12770
- "aria-hidden": "true",
12771
- xmlns: "http://www.w3.org/2000/svg",
12772
- fill: "currentColor",
12773
- viewBox: "0 0 20 20",
12774
- children: /* @__PURE__ */ jsx("path", { d: "M10 .5a9.5 9.5 0 1 0 9.5 9.5A9.51 9.51 0 0 0 10 .5ZM9.5 4a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3ZM12 15H8a1 1 0 0 1 0-2h1v-3h-1a1 1 0 0 1 0-2h2a1 1 0 0 1 1 1v4h1a1 1 0 0 1 0 2Z" })
12775
- });
12776
- break;
12777
- default:
12778
- defaultTitle = "Info:";
12779
- colorClasses = "text-blue-800 border-blue-300 bg-blue-50 dark:bg-gray-800 dark:text-blue-400 dark:border-blue-800";
12780
- iconSvg = /* @__PURE__ */ jsx("svg", {
12781
- class: "shrink-0 inline w-4 h-4 me-3",
12782
- "aria-hidden": "true",
12783
- xmlns: "http://www.w3.org/2000/svg",
12784
- fill: "currentColor",
12785
- viewBox: "0 0 20 20",
12786
- children: /* @__PURE__ */ jsx("path", { d: "M10 .5a9.5 9.5 0 1 0 9.5 9.5A9.51 9.51 0 0 0 10 .5ZM9.5 4a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3ZM12 15H8a1 1 0 0 1 0-2h1v-3H8a1 1 0 0 1 0-2h2a1 1 0 0 1 1 1v4h1a1 1 0 0 1 0 2Z" })
12787
- });
12788
- break;
12789
- }
12790
- const displayTitle = title ?? defaultTitle;
12791
- return /* @__PURE__ */ jsxs("div", {
12792
- class: `flex items-center p-4 mb-4 text-sm border rounded-lg ${colorClasses}`,
12793
- role: "alert",
12794
- children: [
12795
- iconSvg,
12796
- /* @__PURE__ */ jsx("span", {
12797
- class: "sr-only",
12798
- children: "Info"
12799
- }),
12800
- /* @__PURE__ */ jsxs("div", { children: [
12801
- displayTitle ? /* @__PURE__ */ jsx("span", {
12802
- class: "font-medium",
12803
- safe: true,
12804
- children: displayTitle
12805
- }) : null,
12806
- " ",
12807
- message
12808
- ] })
12809
- ]
12810
- });
12811
- };
12812
- //#endregion
12813
- //#region src/web/components/Tooltip.tsx
12814
- /**
12815
- * Reusable Tooltip component using Alpine.js for state management.
12816
- * Displays a help icon that shows a tooltip on hover/focus.
12817
- *
12818
- * @param props - Component props including text and optional position.
12819
- */
12820
- var Tooltip = ({ text, position = "top" }) => {
12821
- return /* @__PURE__ */ jsxs("div", {
12822
- class: "relative ml-1.5 flex items-center",
12823
- "x-data": "{ isVisible: false }",
12824
- children: [/* @__PURE__ */ jsx("button", {
12825
- type: "button",
12826
- class: "text-gray-400 hover:text-gray-500 dark:text-gray-500 dark:hover:text-gray-400 focus:outline-none flex items-center",
12827
- "aria-label": "Help",
12828
- "x-on:mouseenter": "isVisible = true",
12829
- "x-on:mouseleave": "isVisible = false",
12830
- "x-on:focus": "isVisible = true",
12831
- "x-on:blur": "isVisible = false",
12832
- tabindex: "0",
12833
- children: /* @__PURE__ */ jsx("svg", {
12834
- xmlns: "http://www.w3.org/2000/svg",
12835
- fill: "none",
12836
- viewBox: "0 0 24 24",
12837
- "stroke-width": "1.5",
12838
- stroke: "currentColor",
12839
- class: "w-4 h-4",
12840
- children: /* @__PURE__ */ jsx("path", {
12841
- "stroke-linecap": "round",
12842
- "stroke-linejoin": "round",
12843
- d: "M9.879 7.519c1.171-1.025 3.071-1.025 4.242 0 1.172 1.025 1.172 2.687 0 3.712-.203.179-.43.326-.67.442-.745.361-1.45.999-1.45 1.827v.75M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-9 5.25h.008v.008H12v-.008z"
12844
- })
12845
- })
12846
- }), /* @__PURE__ */ jsx("div", {
12847
- "x-show": "isVisible",
12848
- "x-cloak": true,
12849
- class: `absolute z-10 w-64 p-2 text-sm text-gray-500 bg-white border border-gray-200 rounded-lg shadow-sm dark:bg-gray-800 dark:border-gray-600 dark:text-gray-400 ${{
12850
- top: "bottom-full left-1/2 transform -translate-x-1/2 -translate-y-1 mb-1",
12851
- right: "left-full top-1/2 transform -translate-y-1/2 translate-x-1 ml-1",
12852
- bottom: "top-full left-1/2 transform -translate-x-1/2 translate-y-1 mt-1",
12853
- left: "right-full top-1/2 transform -translate-y-1/2 -translate-x-1 mr-1"
12854
- }[position]}`,
12855
- children: text
12856
- })]
12857
- });
12858
- };
12859
- //#endregion
12860
- //#region src/web/components/ScrapeFormContent.tsx
12861
- /**
12862
- * Renders the form fields for queuing a new scrape job.
12863
- * Includes basic fields (URL, Library, Version) and advanced options.
12864
- * Supports pre-filling values when adding a new version to an existing library.
12865
- */
12866
- var ScrapeFormContent = ({ defaultExcludePatterns, initialValues, mode = "new", scraperConfig }) => {
12867
- const isAddVersionMode = mode === "add-version";
12868
- const urlValue = initialValues?.url || "";
12869
- const libraryValue = initialValues?.library || "";
12870
- const maxPagesValue = initialValues?.maxPages?.toString() || "";
12871
- const maxDepthValue = initialValues?.maxDepth?.toString() || "";
12872
- const scopeValue = initialValues?.scope || "subpages";
12873
- const includePatternsValue = initialValues?.includePatterns || "";
12874
- const scrapeModeValue = initialValues?.scrapeMode || ScrapeMode.Auto;
12875
- const followRedirectsValue = initialValues?.followRedirects ?? true;
12876
- const ignoreErrorsValue = initialValues?.ignoreErrors ?? true;
12877
- const preserveHashesValue = initialValues?.preserveHashes ?? scraperConfig?.preserveHashes ?? false;
12878
- const excludePatternsText = initialValues?.excludePatterns !== void 0 ? initialValues.excludePatterns : defaultExcludePatterns?.join("\n") || "";
12879
- const headersJson = JSON.stringify(initialValues?.headers || []);
12880
- const closeButtonAttrs = isAddVersionMode ? {
12881
- "hx-get": `/web/libraries/${encodeURIComponent(libraryValue)}/add-version-button`,
12882
- "hx-target": "#add-version-form-container",
12883
- "hx-swap": "innerHTML"
12884
- } : {
12885
- "hx-get": "/web/jobs/new-button",
12886
- "hx-target": "#addJobForm",
12887
- "hx-swap": "innerHTML"
12888
- };
12889
- const formTarget = isAddVersionMode ? "#add-version-form-container" : "#addJobForm";
12890
- const title = isAddVersionMode ? "Add New Version" : "Add New Documentation";
12891
- return /* @__PURE__ */ jsxs("div", {
12892
- class: "mt-4 p-4 bg-white dark:bg-gray-800 rounded-lg shadow border border-gray-300 dark:border-gray-600 relative animate-[fadeSlideIn_0.2s_ease-out]",
12893
- children: [
12894
- /* @__PURE__ */ jsx("button", {
12895
- type: "button",
12896
- ...closeButtonAttrs,
12897
- class: "absolute top-3 right-3 p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors duration-150",
12898
- title: "Close",
12899
- children: /* @__PURE__ */ jsx("svg", {
12900
- class: "w-5 h-5",
12901
- fill: "none",
12902
- stroke: "currentColor",
12903
- viewBox: "0 0 24 24",
12904
- xmlns: "http://www.w3.org/2000/svg",
12905
- children: /* @__PURE__ */ jsx("path", {
12906
- "stroke-linecap": "round",
12907
- "stroke-linejoin": "round",
12908
- "stroke-width": "2",
12909
- d: "M6 18L18 6M6 6l12 12"
12910
- })
12911
- })
12912
- }),
12913
- /* @__PURE__ */ jsx("h3", {
12914
- class: "text-xl font-semibold text-gray-900 dark:text-white mb-2 pr-8",
12915
- children: title
12916
- }),
12917
- /* @__PURE__ */ jsxs("form", {
12918
- "hx-post": "/web/jobs/scrape",
12919
- "hx-target": formTarget,
12920
- "hx-swap": "innerHTML",
12921
- class: "space-y-2",
12922
- "data-initial-url": urlValue,
12923
- "data-initial-headers": headersJson,
12924
- "x-data": "{\n url: '',\n hasPath: false,\n headers: [],\n checkUrlPath() {\n try {\n const url = new URL(this.url);\n this.hasPath = url.pathname !== '/' && url.pathname !== '';\n } catch (e) {\n this.hasPath = false;\n }\n }\n }",
12925
- "x-init": "\n url = $el.dataset.initialUrl || '';\n headers = JSON.parse($el.dataset.initialHeaders || '[]');\n checkUrlPath();\n ",
12926
- children: [
12927
- /* @__PURE__ */ jsx("input", {
12928
- type: "hidden",
12929
- name: "formMode",
12930
- value: mode
12931
- }),
12932
- /* @__PURE__ */ jsxs("div", { children: [
12933
- /* @__PURE__ */ jsxs("div", {
12934
- class: "flex items-center",
12935
- children: [/* @__PURE__ */ jsx("label", {
12936
- for: "url",
12937
- class: "block text-sm font-medium text-gray-700 dark:text-gray-300",
12938
- children: "URL"
12939
- }), /* @__PURE__ */ jsx(Tooltip, { text: /* @__PURE__ */ jsxs("div", { children: [
12940
- /* @__PURE__ */ jsx("p", { children: "Enter the URL of the documentation you want to scrape." }),
12941
- /* @__PURE__ */ jsxs("p", {
12942
- class: "mt-2",
12943
- children: [
12944
- "For local files/folders, you must use the",
12945
- " ",
12946
- /* @__PURE__ */ jsx("code", { children: "file://" }),
12947
- " prefix and ensure the path is accessible to the server."
12948
- ]
12949
- }),
12950
- /* @__PURE__ */ jsxs("p", {
12951
- class: "mt-2",
12952
- children: [
12953
- "If running in Docker, ",
12954
- /* @__PURE__ */ jsx("b", { children: "mount the folder" }),
12955
- " (see README for details)."
12956
- ]
12957
- })
12958
- ] }) })]
12959
- }),
12960
- /* @__PURE__ */ jsx("input", {
12961
- type: "url",
12962
- name: "url",
12963
- id: "url",
12964
- required: true,
12965
- "x-model": "url",
12966
- "x-on:input": "checkUrlPath",
12967
- "x-on:paste": "$nextTick(() => checkUrlPath())",
12968
- placeholder: "https://docs.example.com/library/",
12969
- class: "mt-0.5 block w-full px-2 py-1 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
12970
- }),
12971
- /* @__PURE__ */ jsx("div", {
12972
- "x-show": "hasPath && !(url.startsWith('file://'))",
12973
- "x-cloak": true,
12974
- "x-transition:enter": "transition ease-out duration-300",
12975
- "x-transition:enter-start": "opacity-0 transform -translate-y-2",
12976
- "x-transition:enter-end": "opacity-100 transform translate-y-0",
12977
- class: "mt-2",
12978
- children: /* @__PURE__ */ jsx(Alert, {
12979
- type: "info",
12980
- message: "By default, only subpages under the given URL will be scraped. To scrape the whole website, adjust the 'Scope' option in Advanced Options."
12981
- })
12982
- })
12983
- ] }),
12984
- /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsxs("div", {
12985
- class: "flex items-center",
12986
- children: [/* @__PURE__ */ jsx("label", {
12987
- for: "library",
12988
- class: "block text-sm font-medium text-gray-700 dark:text-gray-300",
12989
- children: "Library Name"
12990
- }), /* @__PURE__ */ jsx(Tooltip, { text: "The name of the library you're documenting. This will be used when searching." })]
12991
- }), isAddVersionMode ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("input", {
12992
- type: "hidden",
12993
- name: "library",
12994
- value: libraryValue
12995
- }), /* @__PURE__ */ jsx("div", {
12996
- class: "mt-0.5 px-2 py-1 text-sm text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 rounded-md border border-gray-300 dark:border-gray-600",
12997
- children: /* @__PURE__ */ jsx("span", {
12998
- safe: true,
12999
- children: libraryValue
13000
- })
13001
- })] }) : /* @__PURE__ */ jsx("input", {
13002
- type: "text",
13003
- name: "library",
13004
- id: "library",
13005
- required: true,
13006
- value: libraryValue,
13007
- placeholder: "e.g. react, vue, express",
13008
- class: "mt-0.5 block w-full px-2 py-1 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
13009
- })] }),
13010
- /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsxs("div", {
13011
- class: "flex items-center",
13012
- children: [/* @__PURE__ */ jsx("label", {
13013
- for: "version",
13014
- class: "block text-sm font-medium text-gray-700 dark:text-gray-300",
13015
- children: "Version (optional)"
13016
- }), /* @__PURE__ */ jsx(Tooltip, { text: "Specify the version of the library documentation you're indexing (e.g. 2.0.0). Leave empty or enter 'latest' to index without a specific version. This allows for version-specific searches." })]
13017
- }), /* @__PURE__ */ jsx("input", {
13018
- type: "text",
13019
- name: "version",
13020
- id: "version",
13021
- placeholder: "e.g. 2.0.0 or leave empty for latest",
13022
- class: "mt-0.5 block w-full max-w-sm px-2 py-1 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
13023
- })] }),
13024
- /* @__PURE__ */ jsxs("div", {
13025
- class: "bg-gray-50 dark:bg-gray-900 p-2 rounded-md",
13026
- "data-should-open": isAddVersionMode && (maxPagesValue || maxDepthValue || scopeValue !== "subpages" || includePatternsValue || excludePatternsText || scrapeModeValue !== ScrapeMode.Auto || preserveHashesValue) ? "true" : "false",
13027
- "x-data": "{ open: false }",
13028
- "x-init": "open = $el.dataset.shouldOpen === 'true'",
13029
- children: [/* @__PURE__ */ jsxs("button", {
13030
- type: "button",
13031
- class: "w-full flex items-center gap-1.5 cursor-pointer text-sm font-medium text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 transition-colors",
13032
- "x-on:click": "open = !open",
13033
- children: [/* @__PURE__ */ jsx("svg", {
13034
- class: "w-4 h-4 transform transition-transform duration-200",
13035
- "x-bind:class": "{ 'rotate-90': open }",
13036
- fill: "none",
13037
- stroke: "currentColor",
13038
- viewBox: "0 0 24 24",
13039
- children: /* @__PURE__ */ jsx("path", {
13040
- "stroke-linecap": "round",
13041
- "stroke-linejoin": "round",
13042
- "stroke-width": "2",
13043
- d: "M9 5l7 7-7 7"
13044
- })
13045
- }), /* @__PURE__ */ jsx("span", { children: "Advanced Options" })]
13046
- }), /* @__PURE__ */ jsxs("div", {
13047
- "x-show": "open",
13048
- "x-cloak": true,
13049
- "x-collapse": true,
13050
- class: "mt-2 space-y-2",
13051
- children: [
13052
- /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsxs("div", {
13053
- class: "flex items-center",
13054
- children: [/* @__PURE__ */ jsx("label", {
13055
- for: "maxPages",
13056
- class: "block text-sm font-medium text-gray-700 dark:text-gray-300",
13057
- children: "Max Pages"
13058
- }), /* @__PURE__ */ jsx(Tooltip, { text: `The maximum number of pages to scrape. Default is ${scraperConfig?.maxPages ?? 1e3}. Setting this too high may result in longer processing times.` })]
13059
- }), /* @__PURE__ */ jsx("input", {
13060
- type: "number",
13061
- name: "maxPages",
13062
- id: "maxPages",
13063
- min: "1",
13064
- placeholder: scraperConfig?.maxPages?.toString() || "1000",
13065
- value: maxPagesValue,
13066
- class: "mt-0.5 block w-full max-w-sm px-2 py-1 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
13067
- })] }),
13068
- /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsxs("div", {
13069
- class: "flex items-center",
13070
- children: [/* @__PURE__ */ jsx("label", {
13071
- for: "maxDepth",
13072
- class: "block text-sm font-medium text-gray-700 dark:text-gray-300",
13073
- children: "Max Depth"
13074
- }), /* @__PURE__ */ jsx(Tooltip, { text: `How many links deep the scraper should follow. Default is ${scraperConfig?.maxDepth || 3}. Higher values capture more content but increase processing time.` })]
13075
- }), /* @__PURE__ */ jsx("input", {
13076
- type: "number",
13077
- name: "maxDepth",
13078
- id: "maxDepth",
13079
- min: "0",
13080
- placeholder: scraperConfig?.maxDepth?.toString() || "3",
13081
- value: maxDepthValue,
13082
- class: "mt-0.5 block w-full max-w-sm px-2 py-1 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
13083
- })] }),
13084
- /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsxs("div", {
13085
- class: "flex items-center",
13086
- children: [/* @__PURE__ */ jsx("label", {
13087
- for: "scope",
13088
- class: "block text-sm font-medium text-gray-700 dark:text-gray-300",
13089
- children: "Scope"
13090
- }), /* @__PURE__ */ jsx(Tooltip, { text: /* @__PURE__ */ jsxs("div", { children: ["Controls which pages are scraped:", /* @__PURE__ */ jsxs("ul", {
13091
- class: "list-disc pl-5",
13092
- children: [
13093
- /* @__PURE__ */ jsx("li", { children: "'Subpages' only scrapes under the given URL path," }),
13094
- /* @__PURE__ */ jsx("li", { children: "'Hostname' scrapes all content on the same host (e.g., all of docs.example.com)," }),
13095
- /* @__PURE__ */ jsx("li", { children: "'Domain' scrapes all content on the domain and its subdomains (e.g., all of example.com)." })
13096
- ]
13097
- })] }) })]
13098
- }), /* @__PURE__ */ jsxs("select", {
13099
- name: "scope",
13100
- id: "scope",
13101
- class: "mt-0.5 block w-full max-w-sm pl-2 pr-10 py-1 text-base border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white",
13102
- children: [
13103
- /* @__PURE__ */ jsx("option", {
13104
- value: "subpages",
13105
- selected: scopeValue === "subpages",
13106
- children: "Subpages (Default)"
13107
- }),
13108
- /* @__PURE__ */ jsx("option", {
13109
- value: "hostname",
13110
- selected: scopeValue === "hostname",
13111
- children: "Hostname"
13112
- }),
13113
- /* @__PURE__ */ jsx("option", {
13114
- value: "domain",
13115
- selected: scopeValue === "domain",
13116
- children: "Domain"
13117
- })
13118
- ]
13119
- })] }),
13120
- /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsxs("div", {
13121
- class: "flex items-center",
13122
- children: [/* @__PURE__ */ jsx("label", {
13123
- for: "includePatterns",
13124
- class: "block text-sm font-medium text-gray-700 dark:text-gray-300",
13125
- children: "Include Patterns"
13126
- }), /* @__PURE__ */ jsx(Tooltip, { text: "Glob or regex patterns for URLs to include. One per line or comma-separated. Regex patterns must be wrapped in slashes, e.g. /pattern/." })]
13127
- }), /* @__PURE__ */ jsx("textarea", {
13128
- name: "includePatterns",
13129
- id: "includePatterns",
13130
- rows: "2",
13131
- placeholder: "e.g. docs/* or /api\\/v1.*/",
13132
- class: "mt-0.5 block w-full max-w-sm px-2 py-1 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white",
13133
- safe: true,
13134
- children: includePatternsValue
13135
- })] }),
13136
- /* @__PURE__ */ jsxs("div", { children: [
13137
- /* @__PURE__ */ jsxs("div", {
13138
- class: "flex items-center",
13139
- children: [/* @__PURE__ */ jsx("label", {
13140
- for: "excludePatterns",
13141
- class: "block text-sm font-medium text-gray-700 dark:text-gray-300",
13142
- children: "Exclude Patterns"
13143
- }), /* @__PURE__ */ jsx(Tooltip, { text: "Glob or regex patterns for URLs to exclude. One per line or comma-separated. Exclude takes precedence over include. Regex patterns must be wrapped in slashes, e.g. /pattern/. Edit or clear this field to customize exclusions." })]
13144
- }),
13145
- /* @__PURE__ */ jsx("textarea", {
13146
- name: "excludePatterns",
13147
- id: "excludePatterns",
13148
- rows: "5",
13149
- safe: true,
13150
- class: "mt-0.5 block w-full max-w-sm px-2 py-1 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white font-mono text-xs",
13151
- children: excludePatternsText
13152
- }),
13153
- /* @__PURE__ */ jsx("p", {
13154
- class: "mt-1 text-xs text-gray-500 dark:text-gray-400",
13155
- children: isAddVersionMode ? "Patterns from previous version. Edit as needed." : "Default patterns are pre-filled. Edit to customize or clear to exclude nothing."
13156
- })
13157
- ] }),
13158
- /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsxs("div", {
13159
- class: "flex items-center",
13160
- children: [/* @__PURE__ */ jsx("label", {
13161
- for: "scrapeMode",
13162
- class: "block text-sm font-medium text-gray-700 dark:text-gray-300",
13163
- children: "Scrape Mode"
13164
- }), /* @__PURE__ */ jsx(Tooltip, { text: /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsxs("ul", {
13165
- class: "list-disc pl-5",
13166
- children: [
13167
- /* @__PURE__ */ jsx("li", { children: "'Auto' automatically selects the best method," }),
13168
- /* @__PURE__ */ jsx("li", { children: "'Fetch' uses simple HTTP requests (faster but may miss dynamic content)," }),
13169
- /* @__PURE__ */ jsx("li", { children: "'Playwright' uses a headless browser (slower but better for JS-heavy sites)." })
13170
- ]
13171
- }) }) })]
13172
- }), /* @__PURE__ */ jsxs("select", {
13173
- name: "scrapeMode",
13174
- id: "scrapeMode",
13175
- class: "mt-0.5 block w-full max-w-sm pl-2 pr-10 py-1 text-base border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white",
13176
- children: [
13177
- /* @__PURE__ */ jsx("option", {
13178
- value: ScrapeMode.Auto,
13179
- selected: scrapeModeValue === ScrapeMode.Auto,
13180
- children: "Auto (Default)"
13181
- }),
13182
- /* @__PURE__ */ jsx("option", {
13183
- value: ScrapeMode.Fetch,
13184
- selected: scrapeModeValue === ScrapeMode.Fetch,
13185
- children: "Fetch"
13186
- }),
13187
- /* @__PURE__ */ jsx("option", {
13188
- value: ScrapeMode.Playwright,
13189
- selected: scrapeModeValue === ScrapeMode.Playwright,
13190
- children: "Playwright"
13191
- })
13192
- ]
13193
- })] }),
13194
- /* @__PURE__ */ jsxs("div", {
13195
- class: "flex items-center",
13196
- children: [
13197
- /* @__PURE__ */ jsx("input", {
13198
- id: "preserveHashes",
13199
- name: "preserveHashes",
13200
- type: "checkbox",
13201
- checked: preserveHashesValue,
13202
- class: "h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700"
13203
- }),
13204
- /* @__PURE__ */ jsx("label", {
13205
- for: "preserveHashes",
13206
- class: "ml-1 block text-sm text-gray-900 dark:text-gray-300",
13207
- children: "Preserve Hash Routes"
13208
- }),
13209
- /* @__PURE__ */ jsx(Tooltip, { text: "Enable this for documentation sites that use hash fragments as client-side routes rather than same-page anchors." })
13210
- ]
13211
- }),
13212
- /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsxs("div", {
13213
- class: "flex items-center mb-1",
13214
- children: [/* @__PURE__ */ jsx("label", {
13215
- class: "block text-sm font-medium text-gray-700 dark:text-gray-300",
13216
- children: "Custom HTTP Headers"
13217
- }), /* @__PURE__ */ jsx(Tooltip, { text: "Add custom HTTP headers (e.g., for authentication). These will be sent with every HTTP request." })]
13218
- }), /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("template", {
13219
- "x-for": "(header, idx) in headers",
13220
- children: /* @__PURE__ */ jsxs("div", {
13221
- class: "flex space-x-2 mb-1",
13222
- children: [
13223
- /* @__PURE__ */ jsx("input", {
13224
- type: "text",
13225
- class: "w-1/3 px-2 py-1 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-xs",
13226
- placeholder: "Header Name",
13227
- "x-model": "header.name",
13228
- required: true
13229
- }),
13230
- /* @__PURE__ */ jsx("span", {
13231
- class: "text-gray-500",
13232
- children: ":"
13233
- }),
13234
- /* @__PURE__ */ jsx("input", {
13235
- type: "text",
13236
- class: "w-1/2 px-2 py-1 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-xs",
13237
- placeholder: "Header Value",
13238
- "x-model": "header.value",
13239
- required: true
13240
- }),
13241
- /* @__PURE__ */ jsx("button", {
13242
- type: "button",
13243
- class: "text-red-500 hover:text-red-700 text-xs",
13244
- "x-on:click": "headers.splice(idx, 1)",
13245
- children: "Remove"
13246
- }),
13247
- /* @__PURE__ */ jsx("input", {
13248
- type: "hidden",
13249
- name: "header[]",
13250
- "x-bind:value": "header.name && header.value ? header.name + ':' + header.value : ''"
13251
- })
13252
- ]
13253
- })
13254
- }), /* @__PURE__ */ jsx("button", {
13255
- type: "button",
13256
- class: "mt-1 px-2 py-0.5 bg-primary-100 dark:bg-primary-900 text-primary-700 dark:text-primary-200 rounded text-xs",
13257
- "x-on:click": "headers.push({ name: '', value: '' })",
13258
- children: "+ Add Header"
13259
- })] })] }),
13260
- /* @__PURE__ */ jsxs("div", {
13261
- class: "flex items-center",
13262
- children: [/* @__PURE__ */ jsx("input", {
13263
- id: "followRedirects",
13264
- name: "followRedirects",
13265
- type: "checkbox",
13266
- checked: followRedirectsValue,
13267
- class: "h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700"
13268
- }), /* @__PURE__ */ jsx("label", {
13269
- for: "followRedirects",
13270
- class: "ml-1 block text-sm text-gray-900 dark:text-gray-300",
13271
- children: "Follow Redirects"
13272
- })]
13273
- }),
13274
- /* @__PURE__ */ jsxs("div", {
13275
- class: "flex items-center",
13276
- children: [/* @__PURE__ */ jsx("input", {
13277
- id: "ignoreErrors",
13278
- name: "ignoreErrors",
13279
- type: "checkbox",
13280
- checked: ignoreErrorsValue,
13281
- class: "h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700"
13282
- }), /* @__PURE__ */ jsx("label", {
13283
- for: "ignoreErrors",
13284
- class: "ml-1 block text-sm text-gray-900 dark:text-gray-300",
13285
- children: "Ignore Errors During Scraping"
13286
- })]
13287
- })
13288
- ]
13289
- })]
13290
- }),
13291
- /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx("button", {
13292
- type: "submit",
13293
- class: "w-full flex justify-center py-1.5 px-3 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary-600 hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500",
13294
- children: "Start Indexing"
13295
- }) })
13296
- ]
13297
- }),
13298
- /* @__PURE__ */ jsx("div", {
13299
- id: "job-response",
13300
- class: "mt-2 text-sm"
13301
- })
13302
- ]
13303
- });
13304
- };
13305
- //#endregion
13306
- //#region src/web/components/ScrapeForm.tsx
13307
- /**
13308
- * Wrapper component for the ScrapeFormContent.
13309
- * Provides a container div, often used as a target for HTMX OOB swaps.
13310
- */
13311
- var ScrapeForm = ({ defaultExcludePatterns, scraperConfig }) => /* @__PURE__ */ jsx("div", {
13312
- id: "scrape-form-container",
13313
- class: "animate-[fadeSlideIn_0.2s_ease-out]",
13314
- children: /* @__PURE__ */ jsx(ScrapeFormContent, {
13315
- defaultExcludePatterns,
13316
- scraperConfig
13317
- })
13318
- });
13319
- //#endregion
13320
- //#region src/web/routes/jobs/new.tsx
13321
- /**
13322
- * Registers the API routes for creating new jobs.
13323
- * @param server - The Fastify instance.
13324
- * @param scrapeTool - The tool instance for scraping documents.
13325
- */
13326
- function registerNewJobRoutes(server, scrapeTool, scraperConfig) {
13327
- server.get("/web/jobs/new", async () => {
13328
- return /* @__PURE__ */ jsx(ScrapeForm, {
13329
- defaultExcludePatterns: DEFAULT_EXCLUSION_PATTERNS,
13330
- scraperConfig
13331
- });
13332
- });
13333
- server.get("/web/jobs/new-button", async () => {
13334
- return /* @__PURE__ */ jsx(AddJobButton, {});
13335
- });
13336
- server.post("/web/jobs/scrape", async (request, reply) => {
13337
- const body = request.body;
13338
- reply.type("text/html");
13339
- try {
13340
- if (!body.url || !body.library) {
13341
- reply.status(400);
13342
- return /* @__PURE__ */ jsx(Alert, {
13343
- type: "error",
13344
- title: "Validation Error:",
13345
- message: "URL and Library Name are required."
13346
- });
13347
- }
13348
- function parsePatterns(input) {
13349
- if (input === void 0) return void 0;
13350
- if (input.trim() === "") return [];
13351
- return input.split(/\n|,/).map((s) => s.trim()).filter((s) => s.length > 0);
13352
- }
13353
- function parseHeaders(input) {
13354
- if (!input) return void 0;
13355
- const arr = Array.isArray(input) ? input : [input];
13356
- const headers = {};
13357
- for (const entry of arr) {
13358
- const idx = entry.indexOf(":");
13359
- if (idx > 0) {
13360
- const name = entry.slice(0, idx).trim();
13361
- const value = entry.slice(idx + 1).trim();
13362
- if (name) headers[name] = value;
13363
- }
13364
- }
13365
- return Object.keys(headers).length > 0 ? headers : void 0;
13366
- }
13367
- const normalizedVersion = !body.version || body.version.trim() === "" || body.version.trim().toLowerCase() === "latest" ? null : body.version.trim();
13368
- const scrapeOptions = {
13369
- url: body.url,
13370
- library: body.library,
13371
- version: normalizedVersion,
13372
- waitForCompletion: false,
13373
- options: {
13374
- maxPages: body.maxPages ? Number.parseInt(body.maxPages, 10) : void 0,
13375
- maxDepth: body.maxDepth ? Number.parseInt(body.maxDepth, 10) : void 0,
13376
- scope: body.scope,
13377
- scrapeMode: body.scrapeMode,
13378
- preserveHashes: body.preserveHashes === "on",
13379
- followRedirects: body.followRedirects === "on",
13380
- ignoreErrors: body.ignoreErrors === "on",
13381
- includePatterns: parsePatterns(body.includePatterns),
13382
- excludePatterns: parsePatterns(body.excludePatterns),
13383
- headers: parseHeaders(body["header[]"])
13384
- }
13385
- };
13386
- if ("jobId" in await scrapeTool.execute(scrapeOptions)) {
13387
- const versionDisplay = normalizedVersion || "latest";
13388
- reply.header("HX-Trigger", JSON.stringify({ toast: {
13389
- message: `Indexing started for ${body.library}@${versionDisplay}`,
13390
- type: "success"
13391
- } }));
13392
- if (body.formMode === "add-version") return /* @__PURE__ */ jsx(AddVersionButton, { libraryName: body.library });
13393
- return /* @__PURE__ */ jsx(AddJobButton, {});
13394
- }
13395
- return /* @__PURE__ */ jsx(Alert, {
13396
- type: "warning",
13397
- message: "Job finished unexpectedly quickly."
13398
- });
13399
- } catch (error) {
13400
- const errorMessage = error instanceof Error ? error.message : "Unknown error";
13401
- logger.error(`❌ Scrape job submission failed: ${error}`);
13402
- if (error instanceof ValidationError) reply.status(400);
13403
- else reply.status(500);
13404
- return /* @__PURE__ */ jsx(Alert, {
13405
- type: "error",
13406
- title: "Error:",
13407
- message: /* @__PURE__ */ jsx("span", {
13408
- safe: true,
13409
- children: errorMessage
13410
- })
13411
- });
13412
- }
13413
- });
13414
- }
13415
- //#endregion
13416
- //#region src/web/components/VersionDetailsRow.tsx
13417
- /**
13418
- * Renders details for a single library version in a row format.
13419
- * Includes version, stats, and optional delete/refresh buttons.
13420
- * @param props - Component props including version, libraryName, showDelete, and showRefresh flags.
13421
- */
13422
- var VersionDetailsRow = ({ version, libraryName, showDelete = true, showRefresh = false }) => {
13423
- const indexedDate = version.indexedAt ? new Date(version.indexedAt).toLocaleDateString() : "N/A";
13424
- const versionLabel = version.ref.version || "Latest";
13425
- const versionParam = version.ref.version || "";
13426
- const preserveHashes = version.preserveHashes ?? false;
13427
- const rowId = `row-${libraryName.replace(/[^a-zA-Z0-9-_]/g, "-")}-${versionParam.replace(/[^a-zA-Z0-9-_]/g, "-")}`;
13428
- return /* @__PURE__ */ jsxs("div", {
13429
- id: rowId,
13430
- class: "flex justify-between items-center py-1 border-b border-gray-200 dark:border-gray-600 last:border-b-0",
13431
- "data-library-name": libraryName,
13432
- "data-version-param": versionParam,
13433
- "data-is-refreshing": isActiveStatus(version.status) ? "true" : "false",
13434
- "x-data": "{ \n library: $el.dataset.libraryName, \n version: $el.dataset.versionParam, \n confirming: $el.dataset.confirming === 'true', \n isDeleting: false,\n isRefreshing: $el.dataset.isRefreshing === 'true',\n setRefreshing(val) {\n this.isRefreshing = !!val;\n this.$el.dataset.isRefreshing = val ? 'true' : 'false';\n },\n init() {\n const rowId = this.$el.id;\n const myLibrary = this.library;\n const myVersion = this.version;\n \n document.body.addEventListener('job-status-change', (e) => {\n const job = e.detail;\n const jobVersion = job.version || '';\n if (job.library === myLibrary && jobVersion === myVersion) {\n const newValue = ['queued', 'running'].includes(job.status);\n const el = document.getElementById(rowId);\n if (el) {\n el.dispatchEvent(new CustomEvent('set-refreshing', { detail: newValue, bubbles: true }));\n }\n }\n });\n }\n }",
13435
- "x-on:set-refreshing": "setRefreshing($event.detail)",
13436
- children: [
13437
- /* @__PURE__ */ jsx("span", {
13438
- class: "text-sm text-gray-900 dark:text-white w-1/4 truncate",
13439
- title: versionLabel,
13440
- children: version.ref.version ? /* @__PURE__ */ jsx(VersionBadge, { version: version.ref.version }) : /* @__PURE__ */ jsx("span", {
13441
- class: "text-gray-600 dark:text-gray-400",
13442
- children: "Latest"
13443
- })
13444
- }),
13445
- /* @__PURE__ */ jsxs("div", {
13446
- class: "flex space-x-2 text-sm text-gray-600 dark:text-gray-400 w-3/4 justify-end items-center",
13447
- children: [
13448
- /* @__PURE__ */ jsxs("span", {
13449
- title: "Number of unique pages indexed",
13450
- children: [
13451
- "Pages:",
13452
- " ",
13453
- /* @__PURE__ */ jsx("span", {
13454
- class: "font-semibold",
13455
- safe: true,
13456
- children: version.counts.uniqueUrls.toLocaleString()
13457
- })
13458
- ]
13459
- }),
13460
- /* @__PURE__ */ jsxs("span", {
13461
- title: "Number of indexed snippets",
13462
- children: [
13463
- "Chunks:",
13464
- " ",
13465
- /* @__PURE__ */ jsx("span", {
13466
- class: "font-semibold",
13467
- safe: true,
13468
- children: version.counts.documents.toLocaleString()
13469
- })
13470
- ]
13471
- }),
13472
- /* @__PURE__ */ jsxs("span", {
13473
- title: "Date last indexed",
13474
- children: [
13475
- "Last Update:",
13476
- " ",
13477
- /* @__PURE__ */ jsx("span", {
13478
- class: "font-semibold",
13479
- safe: true,
13480
- children: indexedDate
13481
- })
13482
- ]
13483
- })
13484
- ]
13485
- }),
13486
- /* @__PURE__ */ jsxs("div", {
13487
- class: "flex items-center ml-2 space-x-1",
13488
- children: [showRefresh && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("template", {
13489
- "x-if": "!isRefreshing",
13490
- children: /* @__PURE__ */ jsxs("button", {
13491
- type: "button",
13492
- class: "font-medium rounded-lg text-sm p-1 w-6 h-6 text-center inline-flex items-center justify-center transition-colors duration-150 ease-in-out text-gray-500 border border-gray-300 hover:bg-gray-100 hover:text-gray-700 focus:ring-4 focus:outline-none focus:ring-gray-200 dark:border-gray-600 dark:text-gray-400 dark:hover:text-white dark:focus:ring-gray-700 dark:hover:bg-gray-600",
13493
- title: "Refresh this version (re-scrape changed pages)",
13494
- "x-on:click": "\n isRefreshing = true;\n $root.dataset.isRefreshing = 'true';\n $el.dispatchEvent(new CustomEvent('trigger-refresh', { bubbles: true }));\n ",
13495
- "hx-post": `/web/libraries/${encodeURIComponent(libraryName)}/versions/${encodeURIComponent(versionParam)}/refresh`,
13496
- "hx-swap": "none",
13497
- "hx-trigger": "trigger-refresh",
13498
- "hx-vals": JSON.stringify({ preserveHashes }),
13499
- children: [/* @__PURE__ */ jsx("svg", {
13500
- class: "w-4 h-4",
13501
- "aria-hidden": "true",
13502
- xmlns: "http://www.w3.org/2000/svg",
13503
- fill: "none",
13504
- viewBox: "0 0 24 24",
13505
- children: /* @__PURE__ */ jsx("path", {
13506
- stroke: "currentColor",
13507
- "stroke-linecap": "round",
13508
- "stroke-linejoin": "round",
13509
- "stroke-width": "2",
13510
- d: "M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
13511
- })
13512
- }), /* @__PURE__ */ jsx("span", {
13513
- class: "sr-only",
13514
- children: "Refresh version"
13515
- })]
13516
- })
13517
- }), /* @__PURE__ */ jsx("template", {
13518
- "x-if": "isRefreshing",
13519
- children: /* @__PURE__ */ jsxs("button", {
13520
- type: "button",
13521
- class: "font-medium rounded-lg text-sm p-1 w-6 h-6 text-center inline-flex items-center justify-center transition-colors duration-150 ease-in-out text-gray-500 border border-gray-300 dark:border-gray-600 dark:text-gray-400",
13522
- title: "Refresh in progress...",
13523
- disabled: true,
13524
- children: [/* @__PURE__ */ jsx(LoadingSpinner, { class: "text-gray-500 dark:text-gray-400" }), /* @__PURE__ */ jsx("span", {
13525
- class: "sr-only",
13526
- children: "Refreshing..."
13527
- })]
13528
- })
13529
- })] }), showDelete && /* @__PURE__ */ jsxs("button", {
13530
- type: "button",
13531
- class: "font-medium rounded-lg text-sm p-1 min-w-6 h-6 text-center inline-flex items-center justify-center transition-colors duration-150 ease-in-out",
13532
- title: "Remove this version",
13533
- "x-bind:class": `confirming ? 'bg-red-600 text-white border-red-600 focus:ring-4 focus:outline-none focus:ring-red-300 dark:bg-red-700 dark:border-red-700 dark:focus:ring-red-800' : 'text-red-700 border border-red-700 hover:bg-red-700 hover:text-white focus:ring-4 focus:outline-none focus:ring-red-300 dark:border-red-500 dark:text-red-500 dark:hover:text-white dark:focus:ring-red-800 dark:hover:bg-red-500'`,
13534
- "x-bind:disabled": "isDeleting",
13535
- "x-on:click": "\n if (confirming) {\n isDeleting = true;\n window.confirmationManager.clear($root.id);\n $el.dispatchEvent(new CustomEvent('confirmed-delete', { bubbles: true }));\n } else {\n confirming = true;\n isDeleting = false;\n window.confirmationManager.start($root.id);\n }\n ",
13536
- "hx-delete": `/web/libraries/${encodeURIComponent(libraryName)}/versions/${encodeURIComponent(versionParam)}`,
13537
- "hx-target": `#${rowId}`,
13538
- "hx-swap": "outerHTML",
13539
- "hx-trigger": "confirmed-delete",
13540
- children: [
13541
- /* @__PURE__ */ jsxs("span", {
13542
- "x-show": "!confirming && !isDeleting",
13543
- children: [/* @__PURE__ */ jsx("svg", {
13544
- class: "w-4 h-4",
13545
- "aria-hidden": "true",
13546
- xmlns: "http://www.w3.org/2000/svg",
13547
- fill: "none",
13548
- viewBox: "0 0 18 20",
13549
- children: /* @__PURE__ */ jsx("path", {
13550
- stroke: "currentColor",
13551
- "stroke-linecap": "round",
13552
- "stroke-linejoin": "round",
13553
- "stroke-width": "2",
13554
- d: "M1 5h16M7 8v8m4-8v8M7 1h4a1 1 0 0 1 1 1v3H6V2a1 1 0 0 1-1-1ZM3 5h12v13a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V5Z"
13555
- })
13556
- }), /* @__PURE__ */ jsx("span", {
13557
- class: "sr-only",
13558
- children: "Remove version"
13559
- })]
13560
- }),
13561
- /* @__PURE__ */ jsxs("span", {
13562
- "x-show": "confirming && !isDeleting",
13563
- class: "mx-1",
13564
- children: ["Confirm?", /* @__PURE__ */ jsx("span", {
13565
- class: "sr-only",
13566
- children: "Confirm delete"
13567
- })]
13568
- }),
13569
- /* @__PURE__ */ jsxs("span", {
13570
- "x-show": "isDeleting",
13571
- children: [/* @__PURE__ */ jsx(LoadingSpinner, {}), /* @__PURE__ */ jsx("span", {
13572
- class: "sr-only",
13573
- children: "Loading..."
13574
- })]
13575
- })
13576
- ]
13577
- })]
13578
- })
13579
- ]
13580
- });
13581
- };
13582
- //#endregion
13583
- //#region src/web/components/LibraryDetailCard.tsx
13584
- /**
13585
- * Renders a card displaying library details and its versions.
13586
- * Includes Delete and Refresh buttons for each version, and an "Add New Version" button.
13587
- * @param props - Component props including the library information.
13588
- */
13589
- var LibraryDetailCard = ({ library }) => {
13590
- const versions = library.versions || [];
13591
- const latestVersion = versions[0];
13592
- return /* @__PURE__ */ jsxs("div", {
13593
- class: "block p-4 bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-300 dark:border-gray-600 mb-4",
13594
- children: [
13595
- /* @__PURE__ */ jsx("div", {
13596
- class: "flex justify-between items-start mb-1",
13597
- children: /* @__PURE__ */ jsxs("div", {
13598
- class: "min-w-0",
13599
- children: [/* @__PURE__ */ jsx("h3", {
13600
- class: "text-lg font-medium text-gray-900 dark:text-white",
13601
- children: /* @__PURE__ */ jsx("span", {
13602
- safe: true,
13603
- children: library.name
13604
- })
13605
- }), latestVersion?.sourceUrl ? /* @__PURE__ */ jsx("div", {
13606
- class: "text-sm text-gray-500 dark:text-gray-400 truncate",
13607
- children: /* @__PURE__ */ jsx("a", {
13608
- href: latestVersion.sourceUrl,
13609
- target: "_blank",
13610
- class: "hover:underline",
13611
- title: latestVersion.sourceUrl,
13612
- safe: true,
13613
- children: latestVersion.sourceUrl
13614
- })
13615
- }) : null]
13616
- })
13617
- }),
13618
- /* @__PURE__ */ jsx("div", {
13619
- class: "mt-2",
13620
- id: "version-list",
13621
- "hx-get": `/web/libraries/${encodeURIComponent(library.name)}/versions-list`,
13622
- "hx-trigger": "library-change from:body",
13623
- "hx-swap": "morph:innerHTML",
13624
- children: versions.length > 0 ? versions.map((v) => {
13625
- const adapted = {
13626
- id: -1,
13627
- ref: {
13628
- library: library.name,
13629
- version: v.version
13630
- },
13631
- status: v.status,
13632
- progress: v.progress,
13633
- counts: {
13634
- documents: v.documentCount,
13635
- uniqueUrls: v.uniqueUrlCount
13636
- },
13637
- indexedAt: v.indexedAt,
13638
- sourceUrl: v.sourceUrl ?? void 0,
13639
- preserveHashes: v.preserveHashes
13640
- };
13641
- return /* @__PURE__ */ jsx(VersionDetailsRow, {
13642
- libraryName: library.name,
13643
- version: adapted,
13644
- showDelete: true,
13645
- showRefresh: true
13646
- });
13647
- }) : /* @__PURE__ */ jsx("p", {
13648
- class: "text-sm text-gray-500 dark:text-gray-400 italic",
13649
- children: "No versions indexed."
13650
- })
13651
- }),
13652
- /* @__PURE__ */ jsx("div", {
13653
- id: "add-version-form-container",
13654
- class: "mt-4",
13655
- children: /* @__PURE__ */ jsx(AddVersionButton, { libraryName: library.name })
13656
- })
13657
- ]
13658
- });
13659
- };
13660
- //#endregion
13661
- //#region src/web/components/LibrarySearchCard.tsx
13662
- /**
13663
- * Renders the search form card for a specific library.
13664
- * Includes a version dropdown and query input.
13665
- * @param props - Component props including the library information.
13666
- */
13667
- var LibrarySearchCard = ({ library }) => {
13668
- return /* @__PURE__ */ jsxs("div", {
13669
- class: "block p-4 bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-300 dark:border-gray-600 mb-4",
13670
- children: [/* @__PURE__ */ jsxs("h2", {
13671
- class: "text-xl font-semibold mb-2 text-gray-900 dark:text-white",
13672
- safe: true,
13673
- children: [
13674
- "Search ",
13675
- library.name,
13676
- " Documentation"
13677
- ]
13678
- }), /* @__PURE__ */ jsxs("form", {
13679
- "hx-get": `/web/libraries/${encodeURIComponent(library.name)}/search`,
13680
- "hx-target": "#searchResultsContainer .search-results",
13681
- "hx-swap": "innerHTML",
13682
- "hx-indicator": "#searchResultsContainer",
13683
- class: "flex space-x-2",
13684
- children: [
13685
- /* @__PURE__ */ jsxs("select", {
13686
- name: "version",
13687
- class: "w-40 bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500",
13688
- children: [
13689
- /* @__PURE__ */ jsx("option", {
13690
- value: "",
13691
- children: "Latest"
13692
- }),
13693
- " ",
13694
- library.versions.map((version) => /* @__PURE__ */ jsx("option", {
13695
- value: version.version || "latest",
13696
- safe: true,
13697
- children: version.version || "Latest"
13698
- }))
13699
- ]
13700
- }),
13701
- /* @__PURE__ */ jsx("input", {
13702
- type: "text",
13703
- name: "query",
13704
- placeholder: "Search query...",
13705
- required: true,
13706
- class: "flex-grow bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
13707
- }),
13708
- /* @__PURE__ */ jsxs("button", {
13709
- type: "submit",
13710
- class: "text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800 relative",
13711
- children: [/* @__PURE__ */ jsx("span", {
13712
- class: "search-text",
13713
- children: "Search"
13714
- }), /* @__PURE__ */ jsx("span", {
13715
- class: "spinner absolute inset-0 flex items-center justify-center",
13716
- children: /* @__PURE__ */ jsx(LoadingSpinner, {})
13717
- })]
13718
- })
13719
- ]
13720
- })]
13721
- });
13722
- };
13723
- //#endregion
13724
- //#region src/web/components/SearchResultItem.tsx
13725
- /**
13726
- * Renders a single search result item.
13727
- * Converts markdown content to HTML using unified for markdown MIME types.
13728
- * For other content types, renders as preformatted text.
13729
- * @param props - Component props including the search result data.
13730
- */
13731
- var SearchResultItem = async ({ result }) => {
13732
- const isMarkdown = result.mimeType ? MimeTypeUtils.isMarkdown(result.mimeType) || MimeTypeUtils.isSupportedDocument(result.mimeType) : true;
13733
- const purifier = DOMPurify(createJSDOM("").window);
13734
- let contentElement;
13735
- if (isMarkdown) {
13736
- const file = await unified().use(remarkParse).use(remarkGfm).use(remarkHtml).process(result.content);
13737
- const rawHtml = String(file);
13738
- contentElement = /* @__PURE__ */ jsx("div", {
13739
- class: "format dark:format-invert max-w-none",
13740
- children: purifier.sanitize(rawHtml)
13741
- });
13742
- } else contentElement = /* @__PURE__ */ jsx("div", {
13743
- class: "format dark:format-invert max-w-none",
13744
- children: /* @__PURE__ */ jsx("pre", { children: /* @__PURE__ */ jsx("code", { children: escapeHtml(result.content) }) })
13745
- });
13746
- return /* @__PURE__ */ jsxs("div", {
13747
- class: "block px-4 py-2 bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-300 dark:border-gray-600 mb-2",
13748
- children: [/* @__PURE__ */ jsxs("div", {
13749
- class: "text-sm text-gray-600 dark:text-gray-400 mb-1 flex items-center gap-2 min-w-0",
13750
- children: [/* @__PURE__ */ jsx("a", {
13751
- href: result.url,
13752
- target: "_blank",
13753
- rel: "noopener noreferrer",
13754
- class: "underline underline-offset-4 flex-1 truncate",
13755
- title: result.url,
13756
- safe: true,
13757
- children: result.url
13758
- }), result.sourceMimeType || result.mimeType ? /* @__PURE__ */ jsx("span", {
13759
- class: "text-xs opacity-75 font-mono",
13760
- safe: true,
13761
- children: result.sourceMimeType || result.mimeType
13762
- }) : null]
13763
- }), contentElement]
13764
- });
13765
- };
13766
- //#endregion
13767
- //#region src/web/components/SearchResultList.tsx
13768
- /**
13769
- * Renders the list of search results using SearchResultItem.
13770
- * Displays a message if no results are found.
13771
- * @param props - Component props including the array of search results.
13772
- */
13773
- var SearchResultList = ({ results }) => {
13774
- if (results.length === 0) return /* @__PURE__ */ jsx("p", {
13775
- class: "text-gray-500 dark:text-gray-400 italic",
13776
- children: "No results found."
13777
- });
13778
- return /* @__PURE__ */ jsx("div", {
13779
- class: "space-y-2",
13780
- children: results.map((result) => /* @__PURE__ */ jsx(SearchResultItem, { result }))
13781
- });
13782
- };
13783
- //#endregion
13784
- //#region src/web/components/SearchResultSkeletonItem.tsx
13785
- /**
13786
- * Renders a skeleton placeholder for a search result item.
13787
- * Used to indicate loading state while search results are being fetched.
13788
- */
13789
- var SearchResultSkeletonItem = () => /* @__PURE__ */ jsxs("div", {
13790
- class: "block px-4 py-2 bg-white dark:bg-gray-800 rounded-lg shadow-sm mb-2 animate-pulse",
13791
- children: [
13792
- /* @__PURE__ */ jsx("div", { class: "h-[0.8em] bg-gray-200 dark:bg-gray-700 rounded w-3/4 mb-2" }),
13793
- /* @__PURE__ */ jsx("div", { class: "h-[0.8em] bg-gray-200 dark:bg-gray-700 rounded w-full mb-2" }),
13794
- /* @__PURE__ */ jsx("div", { class: "h-[0.8em] bg-gray-200 dark:bg-gray-700 rounded w-5/6" })
13795
- ]
13796
- });
13797
- //#endregion
13798
- //#region src/web/routes/libraries/detail.tsx
13799
- /**
13800
- * Registers the route for displaying library details.
13801
- * @param server - The Fastify instance.
13802
- * @param listLibrariesTool - The tool instance for listing libraries.
13803
- * @param searchTool - The tool instance for searching documentation.
13804
- * @param scrapeTool - The tool instance for scraping documentation.
13805
- * @param docService - The document management service for getting scraper options.
13806
- */
13807
- function registerLibraryDetailRoutes(server, listLibrariesTool, searchTool, scrapeTool, docService) {
13808
- server.get("/libraries/:libraryName", async (request, reply) => {
13809
- const { libraryName } = request.params;
13810
- try {
13811
- const libraryInfo = (await listLibrariesTool.execute()).libraries.find((lib) => lib.name.toLowerCase() === libraryName.toLowerCase());
13812
- if (!libraryInfo) {
13813
- reply.status(404).send("Library not found");
13814
- return;
13815
- }
13816
- reply.type("text/html; charset=utf-8");
13817
- return "<!DOCTYPE html>" + /* @__PURE__ */ jsxs(Layout, {
13818
- title: `MCP Docs - ${libraryInfo.name}`,
13819
- children: [
13820
- /* @__PURE__ */ jsx(LibraryDetailCard, { library: libraryInfo }),
13821
- /* @__PURE__ */ jsx(LibrarySearchCard, { library: libraryInfo }),
13822
- /* @__PURE__ */ jsxs("div", {
13823
- id: "searchResultsContainer",
13824
- children: [/* @__PURE__ */ jsxs("div", {
13825
- class: "search-skeleton space-y-2",
13826
- children: [
13827
- /* @__PURE__ */ jsx(SearchResultSkeletonItem, {}),
13828
- /* @__PURE__ */ jsx(SearchResultSkeletonItem, {}),
13829
- /* @__PURE__ */ jsx(SearchResultSkeletonItem, {})
13830
- ]
13831
- }), /* @__PURE__ */ jsx("div", { class: "search-results" })]
13832
- })
13833
- ]
13834
- });
13835
- } catch (error) {
13836
- server.log.error(error, `Failed to load library details for ${libraryName}`);
13837
- reply.status(500).send("Internal Server Error");
13838
- }
13839
- });
13840
- server.get("/web/libraries/:libraryName/search", async (request, reply) => {
13841
- const { libraryName } = request.params;
13842
- const { query, version } = request.query;
13843
- if (!query) {
13844
- reply.status(400).send("Search query is required.");
13845
- return;
13846
- }
13847
- const versionParam = version === "latest" ? void 0 : version;
13848
- try {
13849
- const searchResult = await searchTool.execute({
13850
- library: libraryName,
13851
- query,
13852
- version: versionParam,
13853
- limit: 10
13854
- });
13855
- reply.type("text/html; charset=utf-8");
13856
- return /* @__PURE__ */ jsx(SearchResultList, { results: searchResult.results });
13857
- } catch (error) {
13858
- server.log.error(error, `Failed to search library ${libraryName}`);
13859
- reply.type("text/html; charset=utf-8");
13860
- return /* @__PURE__ */ jsx(Alert, {
13861
- type: "error",
13862
- message: error instanceof Error ? error.message : "An unexpected error occurred during the search."
13863
- });
13864
- }
13865
- });
13866
- server.get("/web/libraries/:libraryName/versions-list", async (request, reply) => {
13867
- const { libraryName } = request.params;
13868
- try {
13869
- const libraryInfo = (await listLibrariesTool.execute()).libraries.find((lib) => lib.name.toLowerCase() === libraryName.toLowerCase());
13870
- if (!libraryInfo) {
13871
- reply.status(404).send("Library not found");
13872
- return;
13873
- }
13874
- const versions = libraryInfo.versions || [];
13875
- reply.type("text/html; charset=utf-8");
13876
- if (versions.length === 0) return /* @__PURE__ */ jsx("p", {
13877
- class: "text-sm text-gray-500 dark:text-gray-400 italic",
13878
- children: "No versions indexed."
13879
- });
13880
- return /* @__PURE__ */ jsx(Fragment, { children: versions.map((v) => {
13881
- const adapted = {
13882
- id: -1,
13883
- ref: {
13884
- library: libraryInfo.name,
13885
- version: v.version
13886
- },
13887
- status: v.status,
13888
- progress: v.progress,
13889
- counts: {
13890
- documents: v.documentCount,
13891
- uniqueUrls: v.uniqueUrlCount
13892
- },
13893
- indexedAt: v.indexedAt,
13894
- sourceUrl: v.sourceUrl ?? void 0,
13895
- preserveHashes: v.preserveHashes
13896
- };
13897
- return /* @__PURE__ */ jsx(VersionDetailsRow, {
13898
- libraryName: libraryInfo.name,
13899
- version: adapted,
13900
- showDelete: true,
13901
- showRefresh: true
13902
- });
13903
- }) });
13904
- } catch (error) {
13905
- logger.error(`Failed to fetch versions for ${libraryName}: ${error}`);
13906
- reply.status(500).send("Internal Server Error");
13907
- }
13908
- });
13909
- server.get("/web/libraries/:libraryName/add-version-button", async (request, reply) => {
13910
- const { libraryName } = request.params;
13911
- reply.type("text/html; charset=utf-8");
13912
- return /* @__PURE__ */ jsx(AddVersionButton, { libraryName });
13913
- });
13914
- server.get("/web/libraries/:libraryName/add-version-form", async (request, reply) => {
13915
- const { libraryName } = request.params;
13916
- try {
13917
- const libraryInfo = (await listLibrariesTool.execute()).libraries.find((lib) => lib.name.toLowerCase() === libraryName.toLowerCase());
13918
- if (!libraryInfo) {
13919
- reply.status(404).send("Library not found");
13920
- return;
13921
- }
13922
- const latestVersion = (libraryInfo.versions || [])[0];
13923
- let initialValues = { library: libraryName };
13924
- if (latestVersion) {
13925
- const libSummary = (await docService.listLibraries()).find((s) => s.library.toLowerCase() === libraryName.toLowerCase());
13926
- if (libSummary) {
13927
- const versionSummary = libSummary.versions.find((v) => v.ref.version === (latestVersion.version || "") || !latestVersion.version && v.ref.version === "");
13928
- if (versionSummary) {
13929
- const scraperConfig = await docService.getScraperOptions(versionSummary.id);
13930
- if (scraperConfig) {
13931
- const opts = scraperConfig.options;
13932
- initialValues = {
13933
- library: libraryName,
13934
- url: scraperConfig.sourceUrl,
13935
- maxPages: opts.maxPages,
13936
- maxDepth: opts.maxDepth,
13937
- scope: opts.scope,
13938
- includePatterns: opts.includePatterns?.join("\n"),
13939
- excludePatterns: opts.excludePatterns?.join("\n"),
13940
- scrapeMode: opts.scrapeMode,
13941
- headers: opts.headers ? Object.entries(opts.headers).map(([name, value]) => ({
13942
- name,
13943
- value
13944
- })) : void 0,
13945
- followRedirects: opts.followRedirects,
13946
- ignoreErrors: opts.ignoreErrors,
13947
- preserveHashes: opts.preserveHashes
13948
- };
13949
- }
13950
- }
13951
- }
13952
- }
13953
- reply.type("text/html; charset=utf-8");
13954
- return /* @__PURE__ */ jsx(ScrapeFormContent, {
13955
- initialValues,
13956
- mode: "add-version"
13957
- });
13958
- } catch (error) {
13959
- logger.error(`Failed to load add-version form for ${libraryName}: ${error}`);
13960
- reply.type("text/html; charset=utf-8");
13961
- return /* @__PURE__ */ jsx(Alert, {
13962
- type: "error",
13963
- message: "Failed to load the add version form."
13964
- });
13965
- }
13966
- });
13967
- }
13968
- //#endregion
13969
- //#region src/web/components/LibraryItem.tsx
13970
- /**
13971
- * Renders a card for a single library, listing its versions with details.
13972
- * Uses VersionDetailsRow to display each version.
13973
- * @param props - Component props including the library information.
13974
- */
13975
- var LibraryItem = ({ library }) => {
13976
- const versions = library.versions || [];
13977
- const latestVersion = versions[0];
13978
- return /* @__PURE__ */ jsxs("div", {
13979
- id: `library-item-${library.name}`,
13980
- class: "block px-4 py-2 bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-300 dark:border-gray-600",
13981
- children: [
13982
- /* @__PURE__ */ jsx("h3", {
13983
- class: "text-lg font-medium text-gray-900 dark:text-white",
13984
- children: /* @__PURE__ */ jsx("a", {
13985
- href: `/libraries/${encodeURIComponent(library.name)}`,
13986
- class: "hover:underline",
13987
- children: /* @__PURE__ */ jsx("span", {
13988
- safe: true,
13989
- children: library.name
13990
- })
13991
- })
13992
- }),
13993
- latestVersion?.sourceUrl ? /* @__PURE__ */ jsx("div", {
13994
- class: "text-sm text-gray-500 dark:text-gray-400 overflow-hidden h-5 @container",
13995
- children: /* @__PURE__ */ jsx("a", {
13996
- href: latestVersion.sourceUrl,
13997
- target: "_blank",
13998
- class: "inline-block whitespace-nowrap hover:underline hover:animate-[scrollText_2s_ease-in-out_forwards]",
13999
- title: latestVersion.sourceUrl,
14000
- safe: true,
14001
- children: latestVersion.sourceUrl
14002
- })
14003
- }) : null,
14004
- /* @__PURE__ */ jsx("div", {
14005
- class: "mt-2",
14006
- children: versions.length > 0 ? versions.map((v) => {
14007
- const adapted = {
14008
- id: -1,
14009
- ref: {
14010
- library: library.name,
14011
- version: v.version
14012
- },
14013
- status: v.status,
14014
- progress: v.progress,
14015
- counts: {
14016
- documents: v.documentCount,
14017
- uniqueUrls: v.uniqueUrlCount
14018
- },
14019
- indexedAt: v.indexedAt,
14020
- sourceUrl: v.sourceUrl ?? void 0
14021
- };
14022
- return /* @__PURE__ */ jsx(VersionDetailsRow, {
14023
- libraryName: library.name,
14024
- version: adapted
14025
- });
14026
- }) : /* @__PURE__ */ jsx("p", {
14027
- class: "text-sm text-gray-500 dark:text-gray-400 italic",
14028
- children: "No versions indexed."
14029
- })
14030
- })
14031
- ]
14032
- });
14033
- };
14034
- //#endregion
14035
- //#region src/web/components/LibraryList.tsx
14036
- /**
14037
- * Renders a list of LibraryItem components.
14038
- * @param props - Component props including the array of libraries.
14039
- */
14040
- var LibraryList = ({ libraries }) => {
14041
- if (libraries.length === 0) return /* @__PURE__ */ jsx(Alert, {
14042
- type: "info",
14043
- title: "Welcome!",
14044
- message: /* @__PURE__ */ jsxs(Fragment, { children: [
14045
- "To get started, click",
14046
- " ",
14047
- /* @__PURE__ */ jsx("span", {
14048
- class: "font-semibold",
14049
- children: "Add New Documentation"
14050
- }),
14051
- " above and enter the URL of a documentation site to index. For more information, check the",
14052
- " ",
14053
- /* @__PURE__ */ jsx("a", {
14054
- href: "https://grounded.tools",
14055
- target: "_blank",
14056
- rel: "noopener noreferrer",
14057
- class: "font-medium underline hover:no-underline",
14058
- children: "official website"
14059
- }),
14060
- "."
14061
- ] })
14062
- });
14063
- return /* @__PURE__ */ jsx("div", {
14064
- id: "library-list",
14065
- class: "space-y-2 animate-[fadeSlideIn_0.2s_ease-out]",
14066
- children: libraries.map((library) => /* @__PURE__ */ jsx(LibraryItem, { library }))
14067
- });
14068
- };
14069
- //#endregion
14070
- //#region src/web/routes/libraries/list.tsx
14071
- /**
14072
- * Registers the API routes for library management.
14073
- * @param server - The Fastify instance.
14074
- * @param listLibrariesTool - The tool instance for listing libraries.
14075
- * @param removeTool - The tool instance for removing library versions.
14076
- * @param refreshVersionTool - The tool instance for refreshing library versions.
14077
- */
14078
- function registerLibrariesRoutes(server, listLibrariesTool, removeTool, refreshVersionTool) {
14079
- server.get("/web/libraries", async (_request, reply) => {
14080
- try {
14081
- const result = await listLibrariesTool.execute();
14082
- reply.type("text/html; charset=utf-8");
14083
- return /* @__PURE__ */ jsx(LibraryList, { libraries: result.libraries });
14084
- } catch (error) {
14085
- logger.error(`Failed to list libraries: ${error}`);
14086
- reply.status(500).send("Internal Server Error");
14087
- }
14088
- });
14089
- server.delete("/web/libraries/:libraryName/versions/:versionParam", async (request, reply) => {
14090
- const { libraryName, versionParam } = request.params;
14091
- const version = versionParam === "latest" ? void 0 : versionParam;
14092
- try {
14093
- await removeTool.execute({
14094
- library: libraryName,
14095
- version
14096
- });
14097
- if (!(await listLibrariesTool.execute()).libraries.some((lib) => lib.name.toLowerCase() === libraryName.toLowerCase())) reply.header("HX-Redirect", "/");
14098
- reply.status(204).send();
14099
- } catch (error) {
14100
- logger.error(`Failed to remove ${libraryName}@${versionParam}: ${error}`);
14101
- reply.status(500).send({ message: error.message || "Failed to remove version." });
14102
- }
14103
- });
14104
- server.post("/web/libraries/:libraryName/versions/:versionParam/refresh", async (request, reply) => {
14105
- const { libraryName, versionParam } = request.params;
14106
- const version = versionParam === "latest" || versionParam === "" ? void 0 : versionParam;
14107
- const preserveHashes = request.body?.preserveHashes === true || request.body?.preserveHashes === "true" ? true : request.body?.preserveHashes === false || request.body?.preserveHashes === "false" ? false : void 0;
14108
- try {
14109
- await refreshVersionTool.execute({
14110
- library: libraryName,
14111
- version,
14112
- preserveHashes,
14113
- waitForCompletion: false
14114
- });
14115
- const versionDisplay = version || "latest";
14116
- reply.header("HX-Trigger", JSON.stringify({ toast: {
14117
- message: `Refresh started for ${libraryName}@${versionDisplay}`,
14118
- type: "success"
14119
- } }));
14120
- reply.status(204).send();
14121
- } catch (error) {
14122
- logger.error(`Failed to refresh ${libraryName}@${versionParam}: ${error}`);
14123
- const errorMessage = error instanceof Error ? error.message : "Failed to refresh version.";
14124
- reply.header("HX-Trigger", JSON.stringify({ toast: {
14125
- message: errorMessage,
14126
- type: "error"
14127
- } }));
14128
- reply.status(500).send();
14129
- }
14130
- });
14131
- }
14132
- //#endregion
14133
- //#region src/web/components/AnalyticsCards.tsx
14134
- /**
14135
- * Formats a number for display, using K, M, B suffixes for large numbers.
14136
- */
14137
- function formatNumber(num) {
14138
- if (num >= 1e9) return `${(num / 1e9).toFixed(1)}B`;
14139
- if (num >= 1e6) return `${(num / 1e6).toFixed(1)}M`;
14140
- if (num >= 1e3) return `${(num / 1e3).toFixed(1)}K`;
14141
- return num.toString();
14142
- }
14143
- /**
14144
- * Displays three analytics cards: Total Chunks, Active Libraries, and Indexed Pages.
14145
- */
14146
- var AnalyticsCards = ({ totalChunks, activeLibraries, activeVersions, indexedPages }) => /* @__PURE__ */ jsxs("div", {
14147
- class: "grid grid-cols-1 sm:grid-cols-3 gap-4 mb-4 animate-[fadeSlideIn_0.2s_ease-out]",
14148
- children: [
14149
- /* @__PURE__ */ jsx("div", {
14150
- class: "p-4 bg-white rounded-lg shadow dark:bg-gray-800 border border-gray-300 dark:border-gray-600",
14151
- children: /* @__PURE__ */ jsx("div", {
14152
- class: "flex items-center",
14153
- children: /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("p", {
14154
- class: "text-sm font-medium text-gray-500 dark:text-gray-400",
14155
- children: "Total Knowledge Base"
14156
- }), /* @__PURE__ */ jsxs("p", {
14157
- class: "text-xl font-semibold text-gray-900 dark:text-white",
14158
- safe: true,
14159
- children: [formatNumber(totalChunks), " Chunks"]
14160
- })] })
14161
- })
14162
- }),
14163
- /* @__PURE__ */ jsx("div", {
14164
- class: "p-4 bg-white rounded-lg shadow dark:bg-gray-800 border border-gray-300 dark:border-gray-600",
14165
- children: /* @__PURE__ */ jsx("div", {
14166
- class: "flex items-center",
14167
- children: /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("p", {
14168
- class: "text-sm font-medium text-gray-500 dark:text-gray-400",
14169
- children: "Libraries / Versions"
14170
- }), /* @__PURE__ */ jsxs("p", {
14171
- class: "text-xl font-semibold text-gray-900 dark:text-white",
14172
- children: [
14173
- activeLibraries,
14174
- " / ",
14175
- activeVersions
14176
- ]
14177
- })] })
14178
- })
14179
- }),
14180
- /* @__PURE__ */ jsx("div", {
14181
- class: "p-4 bg-white rounded-lg shadow dark:bg-gray-800 border border-gray-300 dark:border-gray-600",
14182
- children: /* @__PURE__ */ jsx("div", {
14183
- class: "flex items-center",
14184
- children: /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("p", {
14185
- class: "text-sm font-medium text-gray-500 dark:text-gray-400",
14186
- children: "Indexed Pages"
14187
- }), /* @__PURE__ */ jsx("p", {
14188
- class: "text-xl font-semibold text-gray-900 dark:text-white",
14189
- safe: true,
14190
- children: formatNumber(indexedPages)
14191
- })] })
14192
- })
14193
- })
14194
- ]
14195
- });
14196
- //#endregion
14197
- //#region src/web/routes/stats.tsx
14198
- /**
14199
- * Registers the API route for analytics stats.
14200
- * @param server - The Fastify instance.
14201
- * @param docService - The document management service for querying library data.
14202
- */
14203
- function registerStatsRoute(server, docService) {
14204
- server.get("/web/stats", async (_request, reply) => {
14205
- try {
14206
- const libraries = await docService.listLibraries();
14207
- let totalChunks = 0;
14208
- let indexedPages = 0;
14209
- let activeVersions = 0;
14210
- for (const lib of libraries) {
14211
- activeVersions += lib.versions.length;
14212
- for (const version of lib.versions) {
14213
- totalChunks += version.counts.documents;
14214
- indexedPages += version.counts.uniqueUrls;
14215
- }
14216
- }
14217
- const activeLibraries = libraries.length;
14218
- reply.type("text/html; charset=utf-8");
14219
- return /* @__PURE__ */ jsx(AnalyticsCards, {
14220
- totalChunks,
14221
- activeLibraries,
14222
- activeVersions,
14223
- indexedPages
14224
- });
14225
- } catch (error) {
14226
- logger.error(`Failed to fetch stats: ${error}`);
14227
- reply.status(500).send("Internal Server Error");
14228
- }
14229
- });
14230
- }
14231
- //#endregion
14232
- //#region src/services/webService.ts
14233
- /**
14234
- * Register web interface routes on a Fastify server instance.
14235
- * This includes all human-facing UI routes.
14236
- * Note: Static file serving and form body parsing are handled by AppServer.
14237
- */
14238
- async function registerWebService(server, docService, pipeline, eventBus, appConfig, externalWorkerUrl) {
14239
- const listLibrariesTool = new ListLibrariesTool(docService);
14240
- const listJobsTool = new ListJobsTool(pipeline);
14241
- const scrapeTool = new ScrapeTool(pipeline, appConfig.scraper);
14242
- const removeTool = new RemoveTool(docService, pipeline);
14243
- const refreshVersionTool = new RefreshVersionTool(pipeline);
14244
- const searchTool = new SearchTool(docService);
14245
- const cancelJobTool = new CancelJobTool(pipeline);
14246
- const clearCompletedJobsTool = new ClearCompletedJobsTool(pipeline);
14247
- registerIndexRoute(server, externalWorkerUrl);
14248
- registerLibrariesRoutes(server, listLibrariesTool, removeTool, refreshVersionTool);
14249
- registerLibraryDetailRoutes(server, listLibrariesTool, searchTool, scrapeTool, docService);
14250
- registerJobListRoutes(server, listJobsTool);
14251
- registerNewJobRoutes(server, scrapeTool, appConfig.scraper);
14252
- registerCancelJobRoute(server, cancelJobTool);
14253
- registerClearCompletedJobsRoute(server, clearCompletedJobsTool);
14254
- registerEventsRoute(server, eventBus);
14255
- registerStatsRoute(server, docService);
14256
- }
14257
- //#endregion
14258
- //#region src/services/workerService.ts
14259
- /**
14260
- * Register worker service to enable embedded pipeline processing.
14261
- * This starts the pipeline and configures callbacks for job processing.
14262
- *
14263
- * Note: This function is now deprecated in favor of configuring callbacks
14264
- * in AppServer.setupPipelineEventBridge(). Keeping telemetry/logging here
14265
- * would overwrite the event bus callbacks, breaking SSE notifications.
14266
- * Telemetry and logging should be integrated into the event bus listeners instead.
14267
- */
14268
- async function registerWorkerService(pipeline) {
14269
- await pipeline.start();
14270
- logger.debug("Worker service started");
14271
- }
14272
- /**
14273
- * Stop the worker service and cleanup resources.
14274
- */
14275
- async function stopWorkerService(pipeline) {
14276
- await pipeline.stop();
14277
- logger.debug("Worker service stopped");
12306
+ async function stopWorkerService(pipeline) {
12307
+ await pipeline.stop();
12308
+ logger.debug("Worker service stopped");
14278
12309
  }
14279
12310
  //#endregion
14280
12311
  //#region src/utils/banner.ts
@@ -14310,6 +12341,7 @@ var AppServer = class AppServer {
14310
12341
  authManager = null;
14311
12342
  serverConfig;
14312
12343
  appConfig;
12344
+ systemInfo;
14313
12345
  remoteEventProxy = null;
14314
12346
  wss = null;
14315
12347
  constructor(docService, pipeline, eventBus, serverConfig, appConfig) {
@@ -14318,9 +12350,19 @@ var AppServer = class AppServer {
14318
12350
  this.eventBus = eventBus;
14319
12351
  this.serverConfig = serverConfig;
14320
12352
  this.appConfig = appConfig;
12353
+ this.systemInfo = buildSystemInfo(serverConfig, appConfig);
14321
12354
  this.server = Fastify({ logger: false });
14322
12355
  }
14323
12356
  /**
12357
+ * Builds a cheap, synchronous connectivity check for the remote worker.
12358
+ * Returns `undefined` when the worker is embedded (the field is only
12359
+ * meaningful — and only ever populated — in remote worker mode).
12360
+ */
12361
+ buildIsWorkerConnected() {
12362
+ if (!this.serverConfig.externalWorkerUrl) return;
12363
+ return () => this.remoteEventProxy?.isActive() ?? false;
12364
+ }
12365
+ /**
14324
12366
  * Validate the server configuration for invalid service combinations.
14325
12367
  */
14326
12368
  validateConfig() {
@@ -14340,7 +12382,7 @@ var AppServer = class AppServer {
14340
12382
  if (this.appConfig.app.telemetryEnabled && shouldEnableTelemetry()) try {
14341
12383
  if (telemetry.isEnabled()) {
14342
12384
  telemetry.setGlobalContext({
14343
- appVersion: "2.4.5",
12385
+ appVersion: "3.0.0",
14344
12386
  appPlatform: process.platform,
14345
12387
  appNodeVersion: process.version,
14346
12388
  appServicesEnabled: this.getActiveServicesList(),
@@ -14483,7 +12525,6 @@ var AppServer = class AppServer {
14483
12525
  if (request.url.includes("/oauth") || request.url.includes("/auth") || request.url.includes("/register")) logger.debug(`${request.method} ${request.url} - Headers: ${JSON.stringify(request.headers)}`);
14484
12526
  });
14485
12527
  if (this.appConfig.auth.enabled && this.authManager) await this.setupAuthMetadataEndpoint();
14486
- if (this.serverConfig.enableWebInterface) await this.enableWebInterface();
14487
12528
  if (this.serverConfig.enableMcpServer) await this.enableMcpServer();
14488
12529
  if (this.serverConfig.enableApiServer) await this.enableTrpcApi();
14489
12530
  if (this.serverConfig.enableWorker) await this.enableWorker();
@@ -14500,13 +12541,6 @@ var AppServer = class AppServer {
14500
12541
  }
14501
12542
  }
14502
12543
  /**
14503
- * Enable web interface service.
14504
- */
14505
- async enableWebInterface() {
14506
- await registerWebService(this.server, this.docService, this.pipeline, this.eventBus, this.appConfig, this.serverConfig.externalWorkerUrl);
14507
- logger.debug("Web interface service enabled");
14508
- }
14509
- /**
14510
12544
  * Enable MCP server service.
14511
12545
  */
14512
12546
  async enableMcpServer() {
@@ -14517,7 +12551,7 @@ var AppServer = class AppServer {
14517
12551
  * Enable Pipeline RPC (tRPC) service.
14518
12552
  */
14519
12553
  async enableTrpcApi() {
14520
- await registerTrpcService(this.server, this.pipeline, this.docService, this.eventBus);
12554
+ await registerTrpcService(this.server, this.pipeline, this.docService, this.eventBus, this.systemInfo, this.buildIsWorkerConnected());
14521
12555
  logger.debug("API server (tRPC) enabled");
14522
12556
  }
14523
12557
  /**
@@ -14532,7 +12566,7 @@ var AppServer = class AppServer {
14532
12566
  this.wss?.emit("connection", ws, request);
14533
12567
  });
14534
12568
  });
14535
- applyTrpcWebSocketHandler(this.wss, this.pipeline, this.docService, this.eventBus);
12569
+ applyTrpcWebSocketHandler(this.wss, this.pipeline, this.docService, this.eventBus, this.systemInfo, this.buildIsWorkerConnected());
14536
12570
  logger.debug("WebSocket server initialized for tRPC subscriptions");
14537
12571
  }
14538
12572
  /**
@@ -14543,14 +12577,43 @@ var AppServer = class AppServer {
14543
12577
  logger.debug("Worker service enabled");
14544
12578
  }
14545
12579
  /**
14546
- * Setup static file serving with root prefix as fallback.
12580
+ * Setup static file serving with root prefix as fallback, plus a SPA
12581
+ * fallback so client-side routing works for the React admin dashboard.
14547
12582
  */
14548
12583
  async setupStaticFiles() {
12584
+ const publicRoot = path.join(getProjectRoot(), "public");
12585
+ const indexHtmlPath = path.join(publicRoot, "index.html");
12586
+ const serveSpaShell = this.createSpaShellHandler(indexHtmlPath);
14549
12587
  await this.server.register(fastifyStatic, {
14550
- root: path.join(getProjectRoot(), "public"),
12588
+ root: publicRoot,
14551
12589
  prefix: "/",
14552
12590
  index: false
14553
12591
  });
12592
+ this.server.get("/", serveSpaShell);
12593
+ this.server.setNotFoundHandler(async (request, reply) => {
12594
+ if (request.method !== "GET" || request.url.startsWith("/api")) {
12595
+ reply.code(404).send({ error: "Not Found" });
12596
+ return;
12597
+ }
12598
+ await serveSpaShell(request, reply);
12599
+ });
12600
+ }
12601
+ /**
12602
+ * Creates a request handler that responds with the built SPA's
12603
+ * `index.html`, falling back to a 404 if the file cannot be read (e.g. the
12604
+ * frontend has not been built yet).
12605
+ */
12606
+ createSpaShellHandler(indexHtmlPath) {
12607
+ let cachedHtml = null;
12608
+ return async (_request, reply) => {
12609
+ try {
12610
+ if (cachedHtml === null) cachedHtml = await readFile(indexHtmlPath, "utf-8");
12611
+ reply.type("text/html").send(cachedHtml);
12612
+ } catch (error) {
12613
+ logger.error(`❌ Failed to serve SPA shell from ${indexHtmlPath}: ${error}`);
12614
+ reply.code(404).send({ error: "Not Found" });
12615
+ }
12616
+ };
14554
12617
  }
14555
12618
  /**
14556
12619
  * Initialize OAuth2/OIDC authentication manager.
@@ -14588,7 +12651,7 @@ var AppServer = class AppServer {
14588
12651
  const isWorkerOnly = this.serverConfig.enableWorker && !this.serverConfig.enableWebInterface && !this.serverConfig.enableMcpServer;
14589
12652
  const isWebOnly = this.serverConfig.enableWebInterface && !this.serverConfig.enableWorker && !this.serverConfig.enableMcpServer;
14590
12653
  const isMcpOnly = this.serverConfig.enableMcpServer && !this.serverConfig.enableWebInterface && !this.serverConfig.enableWorker;
14591
- if (isWorkerOnly) logger.info(`🚀 Worker available at ${address}`);
12654
+ if (isWorkerOnly) logger.info(`🚀 Worker available at ${address}/api`);
14592
12655
  else if (isWebOnly) logger.info(`🚀 Web interface available at ${address}`);
14593
12656
  else if (isMcpOnly) logger.info(`🚀 MCP server available at ${address}`);
14594
12657
  else logger.info(`🚀 Grounded Docs available at ${address}`);
@@ -18356,7 +16419,7 @@ function createWebCommand(cli) {
18356
16419
  }) : await PipelineFactory.createPipeline(docService, eventBus, pipelineOptions), eventBus, createAppServerConfig({
18357
16420
  enableWebInterface: true,
18358
16421
  enableMcpServer: false,
18359
- enableApiServer: false,
16422
+ enableApiServer: true,
18360
16423
  enableWorker: !serverUrl,
18361
16424
  port: appConfig.server.ports.web,
18362
16425
  externalWorkerUrl: serverUrl,
@@ -18453,7 +16516,7 @@ function createCli(argv) {
18453
16516
  let globalEventBus = null;
18454
16517
  let globalTelemetryService = null;
18455
16518
  const commandStartTimes = /* @__PURE__ */ new Map();
18456
- const cli = registerGlobalOutputOptions(yargs(hideBin(argv))).scriptName("docs-mcp-server").strict().usage("Usage: $0 <command> [options]").version("2.4.5").option("verbose", {
16519
+ const cli = registerGlobalOutputOptions(yargs(hideBin(argv))).scriptName("docs-mcp-server").strict().usage("Usage: $0 <command> [options]").version("3.0.0").option("verbose", {
18457
16520
  type: "boolean",
18458
16521
  description: "Enable verbose (debug) logging",
18459
16522
  default: false
@@ -18503,7 +16566,7 @@ function createCli(argv) {
18503
16566
  if (shouldEnableTelemetry() && telemetry.isEnabled()) {
18504
16567
  const commandName = argv._[0]?.toString() || "default";
18505
16568
  telemetry.setGlobalContext({
18506
- appVersion: "2.4.5",
16569
+ appVersion: "3.0.0",
18507
16570
  appPlatform: process.platform,
18508
16571
  appNodeVersion: process.version,
18509
16572
  appInterface: "cli",
@@ -18643,4 +16706,4 @@ async function runCli() {
18643
16706
  //#endregion
18644
16707
  export { cleanupCliCommand, runCli };
18645
16708
 
18646
- //# sourceMappingURL=main-D89k01Wy.js.map
16709
+ //# sourceMappingURL=main-qq21CGPf.js.map