@arabold/docs-mcp-server 3.4.1 → 3.5.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.
@@ -26,7 +26,7 @@ import { lookup } from "node:dns/promises";
26
26
  import fs$1, { readFile } from "node:fs/promises";
27
27
  import net, { BlockList, isIP } from "node:net";
28
28
  import os from "node:os";
29
- import { Minimatch, minimatch } from "minimatch";
29
+ import { Minimatch } from "minimatch";
30
30
  import { HeaderGenerator } from "header-generator";
31
31
  import { chromium } from "playwright";
32
32
  import https from "node:https";
@@ -53,8 +53,8 @@ import * as tar from "tar";
53
53
  import yauzl from "yauzl";
54
54
  import Fuse from "fuse.js";
55
55
  import semver from "semver";
56
- import Database from "better-sqlite3";
57
56
  import * as sqliteVec from "sqlite-vec";
57
+ import Database from "better-sqlite3";
58
58
  import { createTRPCClient, createWSClient, httpBatchLink, splitLink, wsLink } from "@trpc/client";
59
59
  import superjson from "superjson";
60
60
  import { encode } from "@toon-format/toon";
@@ -270,6 +270,19 @@ var LibraryNotFoundInStoreError = class extends StoreError {
270
270
  }
271
271
  };
272
272
  /**
273
+ * Error thrown when a rename targets a library with an indexing job in flight.
274
+ * The rename is refused rather than letting the job keep writing under the old name.
275
+ */
276
+ var LibraryBusyError = class extends StoreError {
277
+ library;
278
+ activeStatuses;
279
+ constructor(library, activeStatuses) {
280
+ super(`Library ${escapeControlCharacters(library)} has an indexing job in flight (${activeStatuses.join(", ")}); retry the rename when it finishes. If no server or scrape command is indexing it anymore, the job was interrupted: starting the server resumes or fails it.`);
281
+ this.library = library;
282
+ this.activeStatuses = activeStatuses;
283
+ }
284
+ };
285
+ /**
273
286
  * Error thrown when a specific version of a library cannot be found in the store.
274
287
  * Includes the list of available versions for better context.
275
288
  */
@@ -380,6 +393,47 @@ var DimensionError = class extends StoreError {
380
393
  */
381
394
  var ConnectionError = class extends StoreError {};
382
395
  /**
396
+ * Error thrown when better-sqlite3's compiled binary cannot load. The package
397
+ * ships Node-API binaries for Windows, macOS and Linux (glibc and musl) on x64
398
+ * and arm64, which load under every supported Node.js version and under Bun.
399
+ * On another platform or architecture no binary exists, and on a damaged
400
+ * install the system cannot load it, so the package has to be reinstalled or
401
+ * built from source.
402
+ */
403
+ var NativeModuleUnavailableError = class extends StoreError {
404
+ constructor() {
405
+ super(`The SQLite native module (better-sqlite3) could not load on ${process.platform}-${process.arch}, so the database cannot open. better-sqlite3 ships prebuilt binaries for Windows, macOS and Linux on x64 and arm64. On one of those, reinstall the package. On another platform, build it from source with node-gyp: https://github.com/WiseLibs/better-sqlite3/blob/master/docs/compilation.md`);
406
+ }
407
+ };
408
+ /**
409
+ * Error thrown when the runtime provides an older Node-API version than
410
+ * better-sqlite3's binaries need. Node.js 22.0 to 22.13 provide Node-API 9,
411
+ * and loading the binary there crashes the process instead of throwing.
412
+ */
413
+ var NodeApiUnsupportedError = class extends StoreError {
414
+ available;
415
+ required;
416
+ constructor(available, required) {
417
+ super(`The SQLite native module (better-sqlite3) needs Node-API ${required}, but this runtime provides Node-API ${escapeControlCharacters(available)}, so the database cannot open. Update Node.js to 22.14 or later.`);
418
+ this.available = available;
419
+ this.required = required;
420
+ }
421
+ };
422
+ /**
423
+ * Tells whether an error means better-sqlite3's compiled binary failed to
424
+ * load: no binary exists for the platform, or the system could not load it.
425
+ * Node.js and Bun both report the path of the binary, which is either a
426
+ * compiled `build/Release/better_sqlite3.node` or a prebuilt
427
+ * `prebuilds/<platform>-<arch>.node` inside the package.
428
+ *
429
+ * @param error - The error thrown while opening the database
430
+ * @returns True when the error is about the binary
431
+ */
432
+ function isNativeModuleError(error) {
433
+ if (!(error instanceof Error) || !("code" in error)) return false;
434
+ return (error.code === "MODULE_NOT_FOUND" || error.code === "ERR_DLOPEN_FAILED") && /better-sqlite3[\\/](?:build|prebuilds)[\\/][^'"\s]*\.node/.test(error.message);
435
+ }
436
+ /**
383
437
  * Error thrown when the embedding provider fails to embed a page's chunks.
384
438
  * Nothing of the page is written when this is thrown.
385
439
  */
@@ -3566,16 +3620,22 @@ function isRegexPattern(pattern) {
3566
3620
  return pattern.length > 2 && pattern.startsWith("/") && pattern.endsWith("/");
3567
3621
  }
3568
3622
  /**
3569
- * Converts a pattern string to a RegExp instance (auto-detects glob/regex).
3570
- * For globs, uses minimatch's internal conversion.
3623
+ * Converts a regex pattern string (wrapped in `/.../`) to a RegExp instance.
3624
+ *
3625
+ * Glob patterns cannot be converted: minimatch v11 removed `makeRe`, and no
3626
+ * RegExp equivalent exists. Use {@link matchesAnyPattern} or
3627
+ * {@link matchesAnyHostPattern} for glob matching instead; this function is
3628
+ * only for the `/.../` regex form (its internal callers branch on
3629
+ * {@link isRegexPattern} first, so they never hit the glob branch).
3630
+ *
3631
+ * @param pattern The pattern to convert; must be a `/.../` regex pattern.
3632
+ * @returns A compiled RegExp for the pattern.
3571
3633
  */
3572
3634
  function patternToRegExp(pattern) {
3573
3635
  const cached = regExpCache.get(pattern);
3574
3636
  if (cached) return cached;
3575
- let re;
3576
- if (isRegexPattern(pattern)) re = new RegExp(pattern.slice(1, -1));
3577
- else re = minimatch.makeRe(pattern, { dot: true });
3578
- if (!re) throw new Error(`Invalid glob pattern: ${pattern}`);
3637
+ if (!isRegexPattern(pattern)) throw new Error(`Invalid regex pattern: ${pattern}. Glob patterns cannot be converted to RegExp (minimatch v11 removed makeRe); use matchesAnyPattern for glob matching.`);
3638
+ const re = new RegExp(pattern.slice(1, -1));
3579
3639
  regExpCache.set(pattern, re);
3580
3640
  return re;
3581
3641
  }
@@ -5334,18 +5394,41 @@ function unwrapPlainTextPre(content) {
5334
5394
  return pre.text();
5335
5395
  }
5336
5396
  /**
5337
- * Returns true when a URL points to an llms.txt meta-file.
5397
+ * Returns the lower-cased last segment of a URL's path.
5338
5398
  * @param url The URL to inspect.
5339
- * @returns Whether the URL path basename is exactly llms.txt.
5399
+ * @returns The basename, or undefined for an unparsable URL or an empty path.
5340
5400
  */
5341
- function isLlmsTxtUrl(url) {
5401
+ function pathBasename(url) {
5342
5402
  try {
5343
- return new URL(url).pathname.split("/").filter(Boolean).at(-1)?.toLowerCase() === "llms.txt";
5403
+ return new URL(url).pathname.split("/").filter(Boolean).at(-1)?.toLowerCase();
5344
5404
  } catch {
5345
- return false;
5405
+ return;
5346
5406
  }
5347
5407
  }
5348
5408
  /**
5409
+ * Returns true when a URL points to an llms.txt meta-file.
5410
+ * @param url The URL to inspect.
5411
+ * @returns Whether the URL path basename is exactly llms.txt.
5412
+ */
5413
+ function isLlmsTxtUrl(url) {
5414
+ return pathBasename(url) === "llms.txt";
5415
+ }
5416
+ /**
5417
+ * Returns true when a URL points to a companion of llms.txt, such as
5418
+ * `llms-full.txt`, `llms-small.txt`, `llms-medium.txt` or `llms-ctx.txt`.
5419
+ *
5420
+ * The llms.txt proposal defines none of these. They are conventions that
5421
+ * documentation generators follow: the site's docs, complete, abridged or
5422
+ * expanded from the index, joined into one Markdown document whatever content
5423
+ * type the server sends.
5424
+ *
5425
+ * @param url The URL to inspect.
5426
+ * @returns Whether the URL path basename is `llms-<anything>.txt`.
5427
+ */
5428
+ function isLlmsTxtCompanionUrl(url) {
5429
+ return /^llms-.+\.txt$/.test(pathBasename(url) ?? "");
5430
+ }
5431
+ /**
5349
5432
  * Parses llms.txt Markdown into project metadata and curated links.
5350
5433
  * @param content The llms.txt Markdown content.
5351
5434
  * @returns Parsed llms.txt metadata and links, or an empty result for invalid content.
@@ -5629,7 +5712,7 @@ var BaseScraperStrategy = class BaseScraperStrategy {
5629
5712
  * crawl queue entirely.
5630
5713
  */
5631
5714
  shouldProcessUrl(url, options, context = {}) {
5632
- if (isLlmsTxtUrl(url)) return false;
5715
+ if (isLlmsTxtUrl(url) || isLlmsTxtCompanionUrl(url)) return false;
5633
5716
  if (!(url.startsWith("file://") && isFileUrlInsideRoots(url, context.internalAllowedFileRoots))) {
5634
5717
  const scope = options.scope ?? "subpages";
5635
5718
  try {
@@ -6156,140 +6239,105 @@ var MinimumChunkSizeError = class extends SplitterError {
6156
6239
  * Generic error for content splitting failures
6157
6240
  */
6158
6241
  var ContentSplitterError = class extends SplitterError {};
6159
- // src/splitter/splitters/CodeContentSplitter.ts
6242
+ // src/splitter/splitters/fenceState.ts
6160
6243
  /**
6161
- * Splits code content while preserving language information and formatting.
6162
- * Uses line boundaries for splitting and ensures each chunk is properly
6163
- * wrapped with language-specific code block markers.
6244
+ * Tracks whether a markdown string ends inside an open fenced code block. Used
6245
+ * by content splitters to avoid cutting chunks in the middle of a fence, which
6246
+ * would leave one chunk with an unmatched opener and the next chunk with an
6247
+ * unmatched closer.
6248
+ *
6249
+ * Follows CommonMark fence semantics for the cases that matter to us: a fence
6250
+ * is a line whose only leading non-whitespace content is three or more
6251
+ * identical backticks or three or more identical tildes. The closing fence
6252
+ * must use the same character and at least as many of them as the opener.
6253
+ * Backticks and tildes do not pair across types.
6164
6254
  */
6165
- var CodeContentSplitter = class {
6166
- options;
6167
- constructor(options) {
6168
- this.options = options;
6169
- }
6170
- async split(content) {
6171
- const infoString = (content.match(/^```([^\n]*)\n/)?.[1] ?? "").trimEnd();
6172
- const lines = content.replace(/^```[^\n]*\n/, "").replace(/```\s*$/, "").split("\n");
6173
- const chunks = [];
6174
- let currentChunkLines = [];
6175
- for (const line of lines) {
6176
- const singleLineSize = this.wrap(line, infoString).length;
6177
- if (singleLineSize > this.options.chunkSize) throw new MinimumChunkSizeError(singleLineSize, this.options.chunkSize);
6178
- currentChunkLines.push(line);
6179
- if (this.wrap(currentChunkLines.join("\n"), infoString).length > this.options.chunkSize && currentChunkLines.length > 1) {
6180
- const lastLine = currentChunkLines.pop();
6181
- chunks.push(this.wrap(currentChunkLines.join("\n"), infoString));
6182
- currentChunkLines = [lastLine];
6183
- }
6184
- }
6185
- if (currentChunkLines.length > 0) chunks.push(this.wrap(currentChunkLines.join("\n"), infoString));
6186
- return chunks;
6187
- }
6188
- wrap(content, infoString) {
6189
- return `\`\`\`${infoString || ""}\n${content.replace(/\n+$/, "")}\n\`\`\``;
6190
- }
6191
- };
6192
- // src/splitter/splitters/fenceState.ts
6193
6255
  var FENCE_PREFIX = "[ \\t]*(?:>[ \\t]*)*";
6194
- var FENCE_OPENER = new RegExp(`^${FENCE_PREFIX}(\`{3,}|~{3,})`);
6195
- function splitLinesWithOffsets(text) {
6196
- const lines = [];
6197
- let offset = 0;
6198
- while (offset <= text.length) {
6199
- const nlIndex = text.indexOf("\n", offset);
6200
- if (nlIndex === -1) {
6201
- if (offset < text.length) lines.push({
6202
- content: text.slice(offset),
6203
- offset,
6204
- newlineLength: 0
6205
- });
6206
- return lines;
6207
- }
6208
- lines.push({
6209
- content: text.slice(offset, nlIndex),
6210
- offset,
6211
- newlineLength: 1
6212
- });
6213
- offset = nlIndex + 1;
6214
- }
6215
- return lines;
6216
- }
6217
- function isClosingFence(line, delimiter, openerCount) {
6218
- return new RegExp(`^${FENCE_PREFIX}\\${delimiter}{${openerCount},}[ \\t]*$`).test(line);
6219
- }
6256
+ var FENCE_OPENER = new RegExp(`^(${FENCE_PREFIX})(\`{3,}|~{3,})`);
6220
6257
  /**
6221
- * Scan the input and return non-overlapping fence regions. Each region covers
6222
- * the line containing the opener through the line containing the matching
6223
- * closer (inclusive of trailing newlines). Unclosed openers produce a region
6224
- * extending to the end of input.
6258
+ * Reads a fence opener from one line.
6259
+ *
6260
+ * @param line A single line, without its newline.
6261
+ * @returns The opener's parts, or null when the line does not open a fence.
6225
6262
  */
6226
- function findFenceRegions(text) {
6227
- const regions = [];
6228
- const lines = splitLinesWithOffsets(text);
6229
- let i = 0;
6230
- while (i < lines.length) {
6231
- const opener = FENCE_OPENER.exec(lines[i].content);
6232
- if (!opener) {
6233
- i += 1;
6234
- continue;
6235
- }
6236
- const delimiter = opener[1][0];
6237
- const count = opener[1].length;
6238
- const startOffset = lines[i].offset;
6239
- let closerLineIndex = -1;
6240
- for (let j = i + 1; j < lines.length; j++) if (isClosingFence(lines[j].content, delimiter, count)) {
6241
- closerLineIndex = j;
6242
- break;
6243
- }
6244
- if (closerLineIndex === -1) {
6245
- regions.push({
6246
- startOffset,
6247
- endOffset: text.length
6248
- });
6249
- break;
6250
- }
6251
- const closerLine = lines[closerLineIndex];
6252
- const endOffset = closerLine.offset + closerLine.content.length + closerLine.newlineLength;
6253
- regions.push({
6254
- startOffset,
6255
- endOffset
6256
- });
6257
- i = closerLineIndex + 1;
6258
- }
6259
- return regions;
6263
+ function parseFenceOpener(line) {
6264
+ const match = FENCE_OPENER.exec(line);
6265
+ if (!match) return null;
6266
+ return {
6267
+ prefix: match[1],
6268
+ delimiter: match[2][0],
6269
+ length: match[2].length
6270
+ };
6260
6271
  }
6261
6272
  /**
6262
- * Returns true if `chunk` ends while inside an open fence — i.e. its triple-
6263
- * backtick/tilde count is odd in a way that leaves a dangling opener.
6273
+ * Builds the pattern for the line that closes a fence: the same character, at
6274
+ * least as many of them, and as permissive about the prefix as the opener.
6264
6275
  */
6265
- function hasOpenFenceAtEnd(chunk) {
6266
- const regions = findFenceRegions(chunk);
6267
- if (regions.length === 0) return false;
6268
- const last = regions[regions.length - 1];
6269
- if (last.endOffset !== chunk.length) return false;
6270
- const lines = splitLinesWithOffsets(chunk.slice(last.startOffset));
6271
- if (lines.length < 2) return true;
6272
- const opener = FENCE_OPENER.exec(lines[0].content);
6273
- if (!opener) return false;
6274
- return !isClosingFence(lines[lines.length - 1].content, opener[1][0], opener[1].length);
6276
+ function closingFencePattern(opener) {
6277
+ return new RegExp(`^${FENCE_PREFIX}\\${opener.delimiter}{${opener.length},}[ \\t]*$`);
6275
6278
  }
6279
+ /**
6280
+ * Follows fence state across consecutive pieces of one text.
6281
+ *
6282
+ * Callers that join pieces in order can ask whether the text so far ends
6283
+ * inside a fence without rescanning it, which keeps a document with a long or
6284
+ * unclosed fence linear instead of quadratic.
6285
+ */
6286
+ var FenceTracker = class {
6287
+ /** Matches the line that closes the open fence, or null while none is open. */
6288
+ closer = null;
6289
+ partialLine = "";
6290
+ /**
6291
+ * Adds the next piece of the text.
6292
+ *
6293
+ * @param text The piece, joined directly after the previous one.
6294
+ */
6295
+ feed(text) {
6296
+ const lines = `${this.partialLine}${text}`.split("\n");
6297
+ this.partialLine = lines.pop() ?? "";
6298
+ for (const line of lines) this.closer = this.next(this.closer, line);
6299
+ }
6300
+ /**
6301
+ * Reports whether the text fed so far ends inside an open fence. A trailing
6302
+ * line without its newline counts as a whole line.
6303
+ *
6304
+ * @returns True when a fence is open at the end of the text.
6305
+ */
6306
+ isOpen() {
6307
+ return (this.partialLine ? this.next(this.closer, this.partialLine) : this.closer) !== null;
6308
+ }
6309
+ next(closer, line) {
6310
+ if (closer === null) {
6311
+ const opener = parseFenceOpener(line);
6312
+ return opener ? closingFencePattern(opener) : null;
6313
+ }
6314
+ return closer.test(line) ? null : closer;
6315
+ }
6316
+ };
6276
6317
  // src/splitter/splitters/TextContentSplitter.ts
6277
6318
  /**
6278
6319
  * Splits text content using a hierarchical approach:
6279
6320
  * 1. Try splitting by paragraphs (double newlines)
6280
- * 2. If chunks still too large, split by single newlines
6281
- * 3. Finally, use word boundaries via LangChain's splitter
6321
+ * 2. If chunks still too large, split by single newlines and merge them back
6322
+ * up to the chunk size
6323
+ * 3. Split only the lines that are still too large, at word boundaries
6282
6324
  *
6283
- * Across all strategies the splitter preserves fenced code block balance: if
6284
- * splitting would leave a chunk ending inside an open ``` or ~~~ fence, that
6285
- * chunk is merged with the following chunk until the fence closes. When this
6286
- * merging forces a chunk past `chunkSize`, the splitter accepts the oversize
6287
- * chunk and emits a warning rather than break the fence.
6325
+ * Text is split to stay within `chunkSize`. Across all strategies the splitter
6326
+ * also preserves fenced code block balance: a chunk never ends inside an open
6327
+ * ``` or ~~~ fence. A fenced block stays whole up to `maxChunkSize`, even when
6328
+ * that is larger than `chunkSize`. A block larger than `maxChunkSize` is cut at
6329
+ * line boundaries. With `rewrapFences`, each piece is closed and reopened with
6330
+ * the block's own opener line, the same way the Markdown code splitter re-wraps
6331
+ * a long code block; without it, nothing is added and the chunks join back to
6332
+ * the input. No chunk exceeds `maxChunkSize`, because an oversized chunk cannot
6333
+ * be embedded.
6288
6334
  */
6289
6335
  var TextContentSplitter = class {
6290
6336
  options;
6337
+ maxChunkSize;
6291
6338
  constructor(options) {
6292
6339
  this.options = options;
6340
+ this.maxChunkSize = Math.max(options.maxChunkSize ?? 0, options.chunkSize);
6293
6341
  }
6294
6342
  /**
6295
6343
  * Splits text content into chunks while trying to preserve semantic boundaries.
@@ -6298,28 +6346,38 @@ var TextContentSplitter = class {
6298
6346
  */
6299
6347
  async split(content) {
6300
6348
  if (content.length <= this.options.chunkSize) return [content];
6301
- const longestWord = content.split(/\s+/).reduce((max, word) => word.length > max.length ? word : max);
6302
- if (longestWord.length > this.options.chunkSize) throw new MinimumChunkSizeError(longestWord.length, this.options.chunkSize);
6303
- const paragraphChunks = this.mergeForFenceBalance(this.splitByParagraphs(content), "");
6349
+ const paragraphChunks = this.mergeForFenceBalance(this.splitByParagraphs(content));
6304
6350
  if (this.areChunksValid(paragraphChunks)) return paragraphChunks;
6305
- const lineChunks = this.mergeForFenceBalance(this.splitByLines(content), "");
6306
- if (this.areChunksValid(lineChunks)) return this.mergeChunks(lineChunks, "");
6307
- const wordChunks = this.mergeForFenceBalance(await this.splitByWords(content), " ");
6308
- const merged = this.mergeChunks(wordChunks, " ");
6309
- this.warnOversize(merged);
6310
- return merged;
6351
+ const units = this.mergeForFenceBalance(this.splitByLines(content)).flatMap((unit) => this.fitUnit(unit));
6352
+ return this.mergeChunks(units);
6353
+ }
6354
+ /**
6355
+ * Returns a line unit whole when it fits, or the pieces it is cut into. A
6356
+ * unit is either one fenced block, which may use up to `maxChunkSize`, or
6357
+ * one line with no fence in it, which is held to `chunkSize`.
6358
+ */
6359
+ fitUnit(unit) {
6360
+ if (unit.length <= this.options.chunkSize) return [unit];
6361
+ const firstLineEnd = unit.indexOf("\n");
6362
+ const opener = firstLineEnd === -1 ? null : parseFenceOpener(unit.slice(0, firstLineEnd));
6363
+ if (opener === null) return splitLongLine(unit, this.options.chunkSize, this.maxChunkSize);
6364
+ if (unit.length <= this.maxChunkSize) return [unit];
6365
+ return this.splitFencedBlock(unit, unit.slice(0, firstLineEnd + 1), opener);
6311
6366
  }
6312
6367
  /**
6313
6368
  * Walks `chunks` left to right and merges adjacent chunks whenever the running
6314
6369
  * buffer ends inside an open fenced code block. Guarantees that every emitted
6315
- * chunk has balanced fences (i.e. `hasOpenFenceAtEnd` returns false).
6370
+ * chunk has balanced fences, except a trailing fence the input never closes.
6371
+ * The chunks must be consecutive pieces of one text, joined without a separator.
6316
6372
  */
6317
- mergeForFenceBalance(chunks, separator) {
6373
+ mergeForFenceBalance(chunks) {
6318
6374
  const result = [];
6375
+ const fences = new FenceTracker();
6319
6376
  let buffer = "";
6320
6377
  for (const chunk of chunks) {
6321
- buffer = buffer ? `${buffer}${separator}${chunk}` : chunk;
6322
- if (!hasOpenFenceAtEnd(buffer)) {
6378
+ buffer += chunk;
6379
+ fences.feed(chunk);
6380
+ if (!fences.isOpen()) {
6323
6381
  result.push(buffer);
6324
6382
  buffer = "";
6325
6383
  }
@@ -6327,8 +6385,29 @@ var TextContentSplitter = class {
6327
6385
  if (buffer) result.push(buffer);
6328
6386
  return result;
6329
6387
  }
6330
- warnOversize(chunks) {
6331
- for (const chunk of chunks) if (chunk.length > this.options.chunkSize) logger.warn(`⚠ TextContentSplitter emitted oversize chunk to preserve fence balance: ${chunk.length} > ${this.options.chunkSize}`);
6388
+ /**
6389
+ * Cuts a fenced block larger than `maxChunkSize` into pieces within it. With
6390
+ * `rewrapFences` each piece is wrapped in the block's own fences; otherwise
6391
+ * the pieces are plain cuts that join back to the block.
6392
+ */
6393
+ splitFencedBlock(unit, openerLine, opener) {
6394
+ const closerLine = `${opener.prefix}${opener.delimiter.repeat(opener.length)}\n`;
6395
+ const room = this.maxChunkSize - openerLine.length - closerLine.length - 1;
6396
+ if (!this.options.rewrapFences || room <= 0) return this.packLines(unit, this.maxChunkSize);
6397
+ const pieces = this.packLines(unit.slice(openerLine.length), room);
6398
+ logger.debug(`Split a ${unit.length}-char fenced block into ${pieces.length} chunks of at most ${this.maxChunkSize} chars`);
6399
+ return pieces.map((piece, index) => {
6400
+ if (index === pieces.length - 1) return `${openerLine}${piece}`;
6401
+ return `${openerLine}${piece}${piece.endsWith("\n") ? closerLine : `\n${closerLine}`}`;
6402
+ });
6403
+ }
6404
+ /**
6405
+ * Cuts text at line boundaries into pieces of at most `limit` characters,
6406
+ * cutting a longer line with `splitLongLine`. The pieces join back to the text.
6407
+ */
6408
+ packLines(text, limit) {
6409
+ const lines = this.splitByLines(text).flatMap((line) => line.length <= limit ? [line] : splitLongLine(line, limit));
6410
+ return this.mergeChunks(lines, limit);
6332
6411
  }
6333
6412
  /**
6334
6413
  * Checks if all chunks are within the maximum size limit
@@ -6374,19 +6453,11 @@ var TextContentSplitter = class {
6374
6453
  return chunks;
6375
6454
  }
6376
6455
  /**
6377
- * Uses LangChain's recursive splitter for word-based splitting as a last resort
6378
- */
6379
- async splitByWords(text) {
6380
- return await new RecursiveCharacterTextSplitter({
6381
- chunkSize: this.options.chunkSize,
6382
- chunkOverlap: 0
6383
- }).splitText(text);
6384
- }
6385
- /**
6386
6456
  * Attempts to merge small chunks with previous chunks to minimize fragmentation.
6387
- * Only merges if combined size is within maxChunkSize.
6457
+ * Only merges if the combined size is within `limit`, which defaults to `chunkSize`.
6458
+ * The chunks are joined as they are, since each keeps its own newlines.
6388
6459
  */
6389
- mergeChunks(chunks, separator) {
6460
+ mergeChunks(chunks, limit = this.options.chunkSize) {
6390
6461
  const mergedChunks = [];
6391
6462
  let currentChunk = null;
6392
6463
  for (const chunk of chunks) {
@@ -6394,7 +6465,7 @@ var TextContentSplitter = class {
6394
6465
  currentChunk = chunk;
6395
6466
  continue;
6396
6467
  }
6397
- if (this.getChunkSize(currentChunk) + this.getChunkSize(chunk) + separator.length <= this.options.chunkSize) currentChunk = `${currentChunk}${separator}${chunk}`;
6468
+ if (this.getChunkSize(currentChunk) + this.getChunkSize(chunk) <= limit) currentChunk = `${currentChunk}${chunk}`;
6398
6469
  else {
6399
6470
  mergedChunks.push(currentChunk);
6400
6471
  currentChunk = chunk;
@@ -6410,13 +6481,82 @@ var TextContentSplitter = class {
6410
6481
  return content;
6411
6482
  }
6412
6483
  };
6484
+ /**
6485
+ * Cuts a line that is too long into pieces that join back to it.
6486
+ *
6487
+ * Each piece ends after the last space or tab within `limit`. When there is no
6488
+ * space to cut at, the line starts with one long token: it stays whole up to
6489
+ * `hardLimit`, and is cut inside only when it is longer still. A cut inside a
6490
+ * token is the last resort, used only when nothing else stays within the limit.
6491
+ *
6492
+ * @param line The line to cut.
6493
+ * @param limit The size each piece should stay within.
6494
+ * @param hardLimit The size no piece may exceed; defaults to `limit`.
6495
+ * @returns The pieces, in order.
6496
+ */
6497
+ function splitLongLine(line, limit, hardLimit = limit) {
6498
+ const hard = Math.max(hardLimit, limit);
6499
+ const pieces = [];
6500
+ let start = 0;
6501
+ while (line.length - start > limit) {
6502
+ const window = line.slice(start, start + limit);
6503
+ const lastSpace = Math.max(window.lastIndexOf(" "), window.lastIndexOf(" "));
6504
+ let cut;
6505
+ if (lastSpace > 0) cut = lastSpace + 1;
6506
+ else {
6507
+ const spaceAfter = line.slice(start + limit, start + hard).search(/[ \t]/);
6508
+ cut = spaceAfter === -1 ? Math.min(hard, line.length - start) : limit + spaceAfter + 1;
6509
+ }
6510
+ pieces.push(line.slice(start, start + cut));
6511
+ start += cut;
6512
+ }
6513
+ if (start < line.length) pieces.push(line.slice(start));
6514
+ return pieces;
6515
+ }
6516
+ // src/splitter/splitters/CodeContentSplitter.ts
6517
+ /**
6518
+ * Splits code content while preserving language information and formatting.
6519
+ * Uses line boundaries for splitting and ensures each chunk is properly
6520
+ * wrapped with language-specific code block markers.
6521
+ */
6522
+ var CodeContentSplitter = class {
6523
+ options;
6524
+ constructor(options) {
6525
+ this.options = options;
6526
+ }
6527
+ async split(content) {
6528
+ const infoString = (content.match(/^```([^\n]*)\n/)?.[1] ?? "").trimEnd();
6529
+ const strippedContent = content.replace(/^```[^\n]*\n/, "").replace(/```\s*$/, "");
6530
+ const room = this.options.chunkSize - this.wrap("", infoString).length;
6531
+ if (room <= 0) throw new MinimumChunkSizeError(this.wrap("", infoString).length, this.options.chunkSize);
6532
+ const lines = strippedContent.split("\n").flatMap((line) => line.length <= room ? [line] : splitLongLine(line, room));
6533
+ const chunks = [];
6534
+ let currentChunkLines = [];
6535
+ for (const line of lines) {
6536
+ currentChunkLines.push(line);
6537
+ if (this.wrap(currentChunkLines.join("\n"), infoString).length > this.options.chunkSize && currentChunkLines.length > 1) {
6538
+ const lastLine = currentChunkLines.pop();
6539
+ chunks.push(this.wrap(currentChunkLines.join("\n"), infoString));
6540
+ currentChunkLines = [lastLine];
6541
+ }
6542
+ }
6543
+ if (currentChunkLines.length > 0) chunks.push(this.wrap(currentChunkLines.join("\n"), infoString));
6544
+ return chunks;
6545
+ }
6546
+ wrap(content, infoString) {
6547
+ return `\`\`\`${infoString || ""}\n${content.replace(/\n+$/, "")}\n\`\`\``;
6548
+ }
6549
+ };
6413
6550
  // src/splitter/splitters/ListContentSplitter.ts
6414
6551
  var ListContentSplitter = class {
6415
6552
  options;
6416
6553
  textSplitter;
6417
6554
  constructor(options) {
6418
6555
  this.options = options;
6419
- this.textSplitter = new TextContentSplitter(options);
6556
+ this.textSplitter = new TextContentSplitter({
6557
+ rewrapFences: true,
6558
+ ...options
6559
+ });
6420
6560
  }
6421
6561
  async split(content) {
6422
6562
  if (content.length <= this.options.chunkSize) return [content];
@@ -6595,10 +6735,17 @@ var SemanticMarkdownSplitter = class SemanticMarkdownSplitter {
6595
6735
  return markdown;
6596
6736
  }
6597
6737
  });
6598
- this.textSplitter = new TextContentSplitter({ chunkSize: this.preferredChunkSize });
6738
+ this.textSplitter = new TextContentSplitter({
6739
+ chunkSize: this.preferredChunkSize,
6740
+ maxChunkSize: this.maxChunkSize,
6741
+ rewrapFences: true
6742
+ });
6599
6743
  this.codeSplitter = new CodeContentSplitter({ chunkSize: this.maxChunkSize });
6600
6744
  this.tableSplitter = new TableContentSplitter({ chunkSize: this.maxChunkSize });
6601
- this.listSplitter = new ListContentSplitter({ chunkSize: this.preferredChunkSize });
6745
+ this.listSplitter = new ListContentSplitter({
6746
+ chunkSize: this.preferredChunkSize,
6747
+ maxChunkSize: this.maxChunkSize
6748
+ });
6602
6749
  }
6603
6750
  /**
6604
6751
  * Main entry point for splitting markdown content
@@ -6705,7 +6852,7 @@ var SemanticMarkdownSplitter = class SemanticMarkdownSplitter {
6705
6852
  let currentSection = this.createRootSection();
6706
6853
  const sections = [];
6707
6854
  const stack = [currentSection];
6708
- for (const element of Array.from(body.children)) {
6855
+ for (let element = body.firstElementChild; element !== null; element = element.nextElementSibling) {
6709
6856
  const headingMatch = element.tagName.match(/H([1-6])/);
6710
6857
  if (headingMatch) {
6711
6858
  const level = Number.parseInt(headingMatch[1], 10);
@@ -9184,7 +9331,7 @@ var TextDocumentSplitter = class {
9184
9331
  }
9185
9332
  }));
9186
9333
  } catch (error) {
9187
- if (!(error instanceof MinimumChunkSizeError) && error instanceof Error) console.warn(`Unexpected text splitting error: ${error.message}. Forcing character-based split.`);
9334
+ console.warn(`Unexpected text splitting error: ${error instanceof Error ? error.message : String(error)}. Forcing character-based split.`);
9188
9335
  const chunks = [];
9189
9336
  let offset = 0;
9190
9337
  while (offset < content.length) {
@@ -9545,29 +9692,29 @@ var MarkdownLinkExtractorMiddleware = class {
9545
9692
  */
9546
9693
  async process(context, next) {
9547
9694
  if (!Array.isArray(context.links)) context.links = [];
9548
- for (const link of extractMarkdownLinks(context.content)) if (!context.links.includes(link)) context.links.push(link);
9695
+ const seen = new Set(context.links);
9696
+ for (const link of extractMarkdownLinks(context.content)) if (!seen.has(link)) {
9697
+ seen.add(link);
9698
+ context.links.push(link);
9699
+ }
9549
9700
  await next();
9550
9701
  }
9551
9702
  };
9552
9703
  function extractMarkdownLinks(content) {
9553
- const links = [];
9704
+ const links = /* @__PURE__ */ new Set();
9554
9705
  const referenceDefinitions = /* @__PURE__ */ new Map();
9555
9706
  for (const match of content.matchAll(referenceDefinitionPattern)) {
9556
9707
  const label = normalizeReferenceLabel(match[1]);
9557
9708
  const target = cleanReferenceTarget(match[2]);
9558
9709
  if (label && target && !referenceDefinitions.has(label)) referenceDefinitions.set(label, target);
9559
9710
  }
9560
- for (const match of content.matchAll(inlineLinkPattern)) addUniqueLink(links, match[2]);
9711
+ for (const match of content.matchAll(inlineLinkPattern)) if (match[2]) links.add(match[2]);
9561
9712
  for (const match of content.matchAll(referenceLinkPattern)) {
9562
9713
  const target = referenceDefinitions.get(normalizeReferenceLabel(match[2]));
9563
- if (target) addUniqueLink(links, target);
9714
+ if (target) links.add(target);
9564
9715
  }
9565
9716
  return links;
9566
9717
  }
9567
- function addUniqueLink(links, target) {
9568
- if (!target || links.includes(target)) return;
9569
- links.push(target);
9570
- }
9571
9718
  function normalizeReferenceLabel(label) {
9572
9719
  return label?.trim().replace(/\s+/g, " ").toLowerCase() ?? "";
9573
9720
  }
@@ -11919,9 +12066,15 @@ var WebScraperStrategy = class extends BaseScraperStrategy {
11919
12066
  * of them, while react.dev — the `text/plain` host — returns a real 404.
11920
12067
  * It cost the published Markdown of every such site and bought nothing.
11921
12068
  * Soft-error detection needs to read the body, and belongs elsewhere.
12069
+ *
12070
+ * The llms.txt companions (`llms-full.txt`, `llms-small.txt`, ...) are
12071
+ * Markdown by convention despite their extension, and servers send them as
12072
+ * `text/plain`. They are restated the same way but keep their own identity:
12073
+ * each is a document of its own, not a variant of another page. Other `.txt`
12074
+ * files stay plain text.
11922
12075
  */
11923
12076
  asMarkdownRepresentation(url, rawContent) {
11924
- if (!this.isMarkdownUrl(url) || !this.isAcceptableMarkdownVariant(rawContent)) return rawContent;
12077
+ if (!(this.isMarkdownUrl(url) || isLlmsTxtCompanionUrl(url)) || !this.isAcceptableMarkdownVariant(rawContent)) return rawContent;
11925
12078
  return MimeTypeUtils.isMarkdown(rawContent.mimeType) ? rawContent : {
11926
12079
  ...rawContent,
11927
12080
  mimeType: "text/markdown"
@@ -12606,6 +12759,8 @@ var PipelineManager = class {
12606
12759
  }
12607
12760
  /**
12608
12761
  * Converts internal job representation to public job interface.
12762
+ * The processed page content (`progress.result`) stays on the internal job: it
12763
+ * can weigh hundreds of kilobytes per job and no consumer of the public job reads it.
12609
12764
  */
12610
12765
  toPublicJob(job) {
12611
12766
  return {
@@ -12613,7 +12768,10 @@ var PipelineManager = class {
12613
12768
  library: job.library,
12614
12769
  version: job.version || null,
12615
12770
  status: job.status,
12616
- progress: job.progress,
12771
+ progress: job.progress ? {
12772
+ ...job.progress,
12773
+ result: null
12774
+ } : null,
12617
12775
  error: job.error ? { message: job.error.message } : null,
12618
12776
  createdAt: job.createdAt,
12619
12777
  startedAt: job.startedAt,
@@ -12828,50 +12986,57 @@ var PipelineManager = class {
12828
12986
  async registerScrapeJob(library, normalizedVersion, options, enqueue) {
12829
12987
  const requested = enqueue.onExisting ?? "reject-version";
12830
12988
  const policy = options.clean === false && requested === "reject-version" ? "replace" : requested;
12831
- const claimed = await this.store.claimVersion(library, normalizedVersion, policy);
12832
- await this.stopJobsFor(library, normalizedVersion);
12833
- const label = formatVersionLabel(claimed.library, normalizedVersion);
12834
- const normalizedOptions = this.normalizeScraperOptions(options);
12835
- const jobId = v4();
12836
- const abortController = new AbortController();
12837
- let resolveCompletion;
12838
- let rejectCompletion;
12839
- const completionPromise = new Promise((resolve, reject) => {
12840
- resolveCompletion = resolve;
12841
- rejectCompletion = reject;
12842
- });
12843
- completionPromise.catch(() => {});
12844
- const job = {
12845
- id: jobId,
12846
- library: claimed.library,
12847
- version: normalizedVersion,
12848
- versionId: claimed.versionId,
12849
- status: PipelineJobStatus.QUEUED,
12850
- progress: null,
12851
- error: null,
12852
- createdAt: /* @__PURE__ */ new Date(),
12853
- startedAt: null,
12854
- finishedAt: null,
12855
- abortController,
12856
- completionPromise,
12857
- resolveCompletion,
12858
- rejectCompletion,
12859
- progressPages: 0,
12860
- progressPagesIndexed: 0,
12861
- progressMaxPages: 0,
12862
- errorMessage: null,
12863
- updatedAt: /* @__PURE__ */ new Date(),
12864
- sourceUrl: normalizedOptions.url,
12865
- scraperOptions: normalizedOptions
12866
- };
12867
- this.jobMap.set(jobId, job);
12868
- this.jobQueue.push(jobId);
12869
- logger.info(`📝 Job enqueued: ${jobId} for ${label}`);
12870
- await this.updateJobStatus(job, PipelineJobStatus.QUEUED);
12871
- if (this.isRunning) this._processQueue().catch((error) => {
12872
- logger.error(`❌ Error in processQueue during enqueue: ${error}`);
12873
- });
12874
- return jobId;
12989
+ const claimed = await this.store.claimVersion(library, normalizedVersion, policy, { markQueued: true });
12990
+ let registered = false;
12991
+ try {
12992
+ await this.stopJobsFor(library, normalizedVersion);
12993
+ const label = formatVersionLabel(claimed.library, normalizedVersion);
12994
+ const normalizedOptions = this.normalizeScraperOptions(options);
12995
+ const jobId = v4();
12996
+ const abortController = new AbortController();
12997
+ let resolveCompletion;
12998
+ let rejectCompletion;
12999
+ const completionPromise = new Promise((resolve, reject) => {
13000
+ resolveCompletion = resolve;
13001
+ rejectCompletion = reject;
13002
+ });
13003
+ completionPromise.catch(() => {});
13004
+ const job = {
13005
+ id: jobId,
13006
+ library: claimed.library,
13007
+ version: normalizedVersion,
13008
+ versionId: claimed.versionId,
13009
+ status: PipelineJobStatus.QUEUED,
13010
+ progress: null,
13011
+ error: null,
13012
+ createdAt: /* @__PURE__ */ new Date(),
13013
+ startedAt: null,
13014
+ finishedAt: null,
13015
+ abortController,
13016
+ completionPromise,
13017
+ resolveCompletion,
13018
+ rejectCompletion,
13019
+ progressPages: 0,
13020
+ progressPagesIndexed: 0,
13021
+ progressMaxPages: 0,
13022
+ errorMessage: null,
13023
+ updatedAt: /* @__PURE__ */ new Date(),
13024
+ sourceUrl: normalizedOptions.url,
13025
+ scraperOptions: normalizedOptions
13026
+ };
13027
+ this.jobMap.set(jobId, job);
13028
+ this.jobQueue.push(jobId);
13029
+ registered = true;
13030
+ logger.info(`📝 Job enqueued: ${jobId} for ${label}`);
13031
+ await this.updateJobStatus(job, PipelineJobStatus.QUEUED);
13032
+ if (this.isRunning) this._processQueue().catch((error) => {
13033
+ logger.error(`❌ Error in processQueue during enqueue: ${error}`);
13034
+ });
13035
+ return jobId;
13036
+ } catch (error) {
13037
+ if (!registered && claimed.previousStatus) await this.store.restoreVersionStatusIfQueued(claimed.versionId, claimed.previousStatus).catch(() => {});
13038
+ throw error;
13039
+ }
12875
13040
  }
12876
13041
  /**
12877
13042
  * Enqueues a refresh job for an existing library version by re-scraping all pages
@@ -13173,7 +13338,10 @@ var PipelineManager = class {
13173
13338
  const publicJob = this.toPublicJob(job);
13174
13339
  this.eventBus.emit(EventType.JOB_PROGRESS, {
13175
13340
  job: publicJob,
13176
- progress
13341
+ progress: {
13342
+ ...progress,
13343
+ result: null
13344
+ }
13177
13345
  });
13178
13346
  logger.debug(`Job ${job.id} progress: ${progress.pagesScraped}/${progress.totalPages} processed, ${progress.pagesIndexed} indexed`);
13179
13347
  }
@@ -13245,6 +13413,12 @@ var DocumentManagementClient = class {
13245
13413
  async compact(options) {
13246
13414
  return this.client.compact.mutate(options ?? {});
13247
13415
  }
13416
+ async renameLibrary(library, newName) {
13417
+ return this.client.renameLibrary.mutate({
13418
+ library,
13419
+ newName
13420
+ });
13421
+ }
13248
13422
  async getVersionsByStatus(statuses) {
13249
13423
  return this.client.getVersionsByStatus.query({ statuses });
13250
13424
  }
@@ -14029,7 +14203,6 @@ async function applyMigrations(db, options) {
14029
14203
  db.pragma("synchronous = NORMAL");
14030
14204
  db.pragma("mmap_size = 268435456");
14031
14205
  db.pragma("cache_size = -64000");
14032
- db.pragma("temp_store = MEMORY");
14033
14206
  logger.debug("Applied safe migration pragmas");
14034
14207
  } catch (_error) {
14035
14208
  logger.warn("⚠️ Could not apply all migration pragmas");
@@ -14094,6 +14267,37 @@ async function applyMigrations(db, options) {
14094
14267
  logger.warn("⚠️ Could not apply all production database settings");
14095
14268
  }
14096
14269
  }
14270
+ // src/store/openDatabase.ts
14271
+ /**
14272
+ * Opens the SQLite database with better-sqlite3. The package ships Node-API
14273
+ * binaries for Windows, macOS and Linux (glibc and musl) on x64 and arm64, so
14274
+ * the binary loads under every Node.js version from 22.14 up and under Bun,
14275
+ * without an install script or a download.
14276
+ */
14277
+ /** The Node-API version better-sqlite3's binaries are built for. */
14278
+ var REQUIRED_NODE_API = 10;
14279
+ /**
14280
+ * Opens a better-sqlite3 database. Open databases only through this function,
14281
+ * so a binary that cannot load ends in one actionable error instead of a raw
14282
+ * module resolution failure or a crash.
14283
+ *
14284
+ * @param dbPath - Path of the database file, or `:memory:`
14285
+ * @param options - better-sqlite3 options, such as `readonly`
14286
+ * @returns The open database
14287
+ * @throws NodeApiUnsupportedError when the runtime provides an older Node-API version than the binary needs
14288
+ * @throws NativeModuleUnavailableError when no better-sqlite3 binary loads on this platform
14289
+ */
14290
+ function openDatabase(dbPath, options = {}) {
14291
+ const nodeApi = process.versions.napi;
14292
+ if (nodeApi !== void 0 && Number(nodeApi) < REQUIRED_NODE_API) throw new NodeApiUnsupportedError(nodeApi, REQUIRED_NODE_API);
14293
+ try {
14294
+ return new Database(dbPath, options);
14295
+ } catch (error) {
14296
+ if (!isNativeModuleError(error)) throw error;
14297
+ logger.debug(`Failed to load better-sqlite3: ${error}`);
14298
+ throw new NativeModuleUnavailableError();
14299
+ }
14300
+ }
14097
14301
  // src/store/DocumentStore.ts
14098
14302
  /**
14099
14303
  * How many full-text candidates are sorted by score alone before the
@@ -14104,6 +14308,13 @@ async function applyMigrations(db, options) {
14104
14308
  */
14105
14309
  var FTS_TIE_WINDOW_FACTOR = 2;
14106
14310
  /**
14311
+ * The shortest beginning of a text worth halving again when the provider keeps
14312
+ * rejecting it as too large. A provider that still refuses this little has a
14313
+ * limit far below any chunk size, which is a configuration fault to report
14314
+ * rather than retry.
14315
+ */
14316
+ var MIN_TRUNCATED_EMBEDDING_CHARS = 256;
14317
+ /**
14107
14318
  * Orders search results that score the same: by page URL, then by position on
14108
14319
  * the page. Without it, ties fall to storage order, which depends on when and
14109
14320
  * how fast each page was indexed.
@@ -14245,7 +14456,7 @@ var DocumentStore = class {
14245
14456
  this.embeddingBatchSize = this.config.embeddings.batchSize;
14246
14457
  this.embeddingBatchChars = this.config.embeddings.batchChars;
14247
14458
  this.embeddingInitTimeoutMs = this.config.embeddings.initTimeoutMs;
14248
- this.db = new Database(dbPath);
14459
+ this.db = openDatabase(dbPath);
14249
14460
  this.embeddingConfig = this.resolveEmbeddingConfig(appConfig.app.embeddingModel);
14250
14461
  }
14251
14462
  resolveEmbeddingConfig(modelSpec) {
@@ -14277,8 +14488,11 @@ var DocumentStore = class {
14277
14488
  getPageId: this.db.prepare("SELECT id, source_content_type FROM pages WHERE version_id = ? AND url = ?"),
14278
14489
  insertLibrary: this.db.prepare("INSERT INTO libraries (name, display_name) VALUES (?, ?)"),
14279
14490
  getLibraryIdByName: this.db.prepare("SELECT id, display_name FROM libraries WHERE name = ?"),
14491
+ renameLibrary: this.db.prepare("UPDATE libraries SET name = ?, display_name = ? WHERE id = ?"),
14492
+ getActiveVersionStatusesByLibraryId: this.db.prepare("SELECT DISTINCT status FROM versions WHERE library_id = ? AND status IN ('queued', 'running', 'updating')"),
14280
14493
  getLibraryById: this.db.prepare("SELECT * FROM libraries WHERE id = ?"),
14281
14494
  insertVersion: this.db.prepare("INSERT INTO versions (library_id, name, status) VALUES (?, ?, 'not_indexed') ON CONFLICT(library_id, name) DO NOTHING"),
14495
+ markVersionQueued: this.db.prepare("UPDATE versions SET status = 'queued' WHERE id = ?"),
14282
14496
  resolveVersionId: this.db.prepare("SELECT id FROM versions WHERE library_id = ? AND name = ?"),
14283
14497
  getVersionById: this.db.prepare("SELECT * FROM versions WHERE id = ?"),
14284
14498
  queryVersionsByLibraryId: this.db.prepare("SELECT * FROM versions WHERE library_id = ? ORDER BY name"),
@@ -14333,12 +14547,14 @@ var DocumentStore = class {
14333
14547
  -- the *first*-index time and never moves on refresh. Fall back to the
14334
14548
  -- oldest page for versions that predate status tracking.
14335
14549
  COALESCE(v.updated_at, MIN(p.created_at)) as indexedAt,
14336
- COUNT(d.id) as documentCount,
14337
- COUNT(DISTINCT p.url) as uniqueUrlCount
14550
+ -- Counts kept per page by migration 020's triggers, so the listing
14551
+ -- never reads the documents table. UNIQUE(version_id, url) makes
14552
+ -- each page of a version a distinct URL.
14553
+ COALESCE(SUM(p.chunk_count), 0) as documentCount,
14554
+ COUNT(p.id) as uniqueUrlCount
14338
14555
  FROM versions v
14339
14556
  JOIN libraries l ON v.library_id = l.id
14340
14557
  LEFT JOIN pages p ON p.version_id = v.id
14341
- LEFT JOIN documents d ON d.page_id = p.id
14342
14558
  GROUP BY v.id
14343
14559
  ORDER BY l.name, version`),
14344
14560
  getChildChunks: this.db.prepare(`
@@ -14923,7 +15139,7 @@ var DocumentStore = class {
14923
15139
  * @throws {VersionAlreadyExistsError} Policy `reject-version` and the version exists.
14924
15140
  * @throws {InvalidLibraryNameError} The library is new and its name fails validation.
14925
15141
  */
14926
- async claimVersion(library, version, policy) {
15142
+ async claimVersion(library, version, policy, options) {
14927
15143
  const label = normalizeVersionLabel(version);
14928
15144
  const storedVersion = denormalizeVersionName(label);
14929
15145
  return this.db.transaction(() => {
@@ -14931,6 +15147,15 @@ var DocumentStore = class {
14931
15147
  if (this.statements.insertVersion.run(libraryRow.id, storedVersion).changes === 0 && policy === "reject-version") throw new VersionAlreadyExistsError(libraryRow.displayName, label);
14932
15148
  const versionIdRow = this.statements.resolveVersionId.get(libraryRow.id, storedVersion);
14933
15149
  if (!versionIdRow) throw new StoreError(`Failed to resolve version_id for library: ${quoteName(library)}, version: ${quoteName(version)}`);
15150
+ if (options?.markQueued) {
15151
+ const current = this.statements.getVersionById.get(versionIdRow.id);
15152
+ this.statements.markVersionQueued.run(versionIdRow.id);
15153
+ return {
15154
+ versionId: versionIdRow.id,
15155
+ library: libraryRow.displayName,
15156
+ previousStatus: current.status
15157
+ };
15158
+ }
14934
15159
  return {
14935
15160
  versionId: versionIdRow.id,
14936
15161
  library: libraryRow.displayName
@@ -15004,6 +15229,18 @@ var DocumentStore = class {
15004
15229
  }
15005
15230
  }
15006
15231
  /**
15232
+ * Puts a version's status back, but only while it is still `queued`.
15233
+ * Used to undo the reservation a claim made when the enqueue fails before a
15234
+ * job is registered, without overwriting a status a job wrote in the meantime.
15235
+ */
15236
+ async restoreVersionStatusIfQueued(versionId, status) {
15237
+ try {
15238
+ this.db.prepare("UPDATE versions SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND status = ?").run(status, versionId, VersionStatus.QUEUED);
15239
+ } catch (error) {
15240
+ throw new StoreError(`Failed to restore version status: ${error}`);
15241
+ }
15242
+ }
15243
+ /**
15007
15244
  * Updates the progress counters for a version being indexed.
15008
15245
  * @param versionId The version ID to update
15009
15246
  * @param pages Current number of pages processed
@@ -15105,6 +15342,43 @@ var DocumentStore = class {
15105
15342
  }
15106
15343
  }
15107
15344
  /**
15345
+ * Renames a library in place: one transaction updates the lookup key and the
15346
+ * display name, leaving versions, pages, chunks and embeddings untouched.
15347
+ *
15348
+ * Runs as one IMMEDIATE transaction with no `await` inside, mirroring
15349
+ * {@link claimVersion}: the database decides a race, and a rename cannot
15350
+ * interleave with a concurrent claim or another rename.
15351
+ *
15352
+ * @param library Current library name, in any casing or padding.
15353
+ * @param newName New name as entered; the trimmed form becomes the display name.
15354
+ * @returns The previous and new display names, or `null` when the library does not exist.
15355
+ * @throws {InvalidLibraryNameError} The new name fails validation.
15356
+ * @throws {LibraryAlreadyExistsError} A different library already uses the new name.
15357
+ * @throws {LibraryBusyError} The library has an indexing job in flight.
15358
+ */
15359
+ async renameLibrary(library, newName) {
15360
+ const displayName = normalizeLibraryDisplayName(newName);
15361
+ const problem = describeLibraryNameProblem(displayName);
15362
+ if (problem) throw new InvalidLibraryNameError(displayName, problem);
15363
+ const oldKey = normalizeLibraryName(library);
15364
+ const newKey = normalizeLibraryName(newName);
15365
+ return this.db.transaction(() => {
15366
+ const row = this.statements.getLibraryIdByName.get(oldKey);
15367
+ if (!row) return null;
15368
+ const active = this.statements.getActiveVersionStatusesByLibraryId.all(row.id);
15369
+ if (active.length > 0) throw new LibraryBusyError(row.display_name, active.map((a) => a.status));
15370
+ if (newKey !== oldKey) {
15371
+ const conflict = this.statements.getLibraryIdByName.get(newKey);
15372
+ if (conflict) throw new LibraryAlreadyExistsError(conflict.display_name);
15373
+ }
15374
+ this.statements.renameLibrary.run(newKey, displayName, row.id);
15375
+ return {
15376
+ oldName: row.display_name,
15377
+ newName: displayName
15378
+ };
15379
+ }).immediate();
15380
+ }
15381
+ /**
15108
15382
  * Deletes a library by its ID.
15109
15383
  * This should only be called when the library has no remaining versions.
15110
15384
  * @param libraryId The library ID to delete
@@ -15236,18 +15510,19 @@ var DocumentStore = class {
15236
15510
  * Creates embeddings for an array of texts with automatic retry logic for size-related errors.
15237
15511
  * If a batch fails due to size limits:
15238
15512
  * - Batches with multiple texts are split in half and retried recursively
15239
- * - Single texts that are too large are truncated and retried once
15513
+ * - A single text that is too large is cut to its first half, again and
15514
+ * again, until the provider accepts it. The stored chunk keeps its full
15515
+ * text; only its vector is computed from the beginning.
15240
15516
  *
15241
15517
  * @param texts Array of texts to embed
15242
15518
  * @param isRetry Internal flag to prevent duplicate warning logs
15243
- * @param hasTruncatedSingleText Whether a single text has already been truncated once
15244
15519
  * @returns Array of embedding vectors
15245
15520
  */
15246
- async embedDocumentsWithRetry(texts, isRetry = false, hasTruncatedSingleText = false) {
15521
+ async embedDocumentsWithRetry(texts, isRetry = false) {
15247
15522
  if (texts.length === 0) return [];
15523
+ const embeddings = this.embeddings;
15524
+ if (embeddings === null) throw new StoreError("Embeddings are not initialized");
15248
15525
  try {
15249
- const embeddings = this.embeddings;
15250
- if (embeddings === null) throw new StoreError("Embeddings are not initialized");
15251
15526
  return await embeddings.embedDocuments(texts);
15252
15527
  } catch (error) {
15253
15528
  if (this.isInputSizeError(error)) {
@@ -15256,26 +15531,44 @@ var DocumentStore = class {
15256
15531
  const firstHalf = texts.slice(0, midpoint);
15257
15532
  const secondHalf = texts.slice(midpoint);
15258
15533
  if (!isRetry) logger.warn(`⚠️ Batch of ${texts.length} texts exceeded size limit, splitting into ${firstHalf.length} + ${secondHalf.length}`);
15259
- const [firstEmbeddings, secondEmbeddings] = await Promise.all([this.embedDocumentsWithRetry(firstHalf, true, false), this.embedDocumentsWithRetry(secondHalf, true, false)]);
15534
+ const [firstEmbeddings, secondEmbeddings] = await Promise.all([this.embedDocumentsWithRetry(firstHalf, true), this.embedDocumentsWithRetry(secondHalf, true)]);
15260
15535
  return [...firstEmbeddings, ...secondEmbeddings];
15261
- } else {
15262
- if (hasTruncatedSingleText) throw error;
15263
- const text = texts[0];
15264
- const midpoint = Math.floor(text.length / 2);
15265
- const firstHalf = text.substring(0, midpoint);
15266
- if (!isRetry) logger.warn(`⚠️ Single text exceeded embedding size limit (${text.length} chars).`);
15267
- try {
15268
- return await this.embedDocumentsWithRetry([firstHalf], true, true);
15269
- } catch (retryError) {
15270
- logger.error(`❌ Failed to embed even after splitting. Original length: ${text.length}`);
15271
- throw retryError;
15272
- }
15273
15536
  }
15537
+ return await this.embedBeginningOf(embeddings, texts[0]);
15274
15538
  }
15275
15539
  throw error;
15276
15540
  }
15277
15541
  }
15278
15542
  /**
15543
+ * Embeds the beginning of a single text the provider rejected as too large.
15544
+ *
15545
+ * The text is halved until the provider accepts it, since one halving is not
15546
+ * enough when a text is several times over the limit. The first halving
15547
+ * always runs; later ones stop below `MIN_TRUNCATED_EMBEDDING_CHARS`. The
15548
+ * beginning holds the title, URL and path header and typically the most
15549
+ * important context.
15550
+ *
15551
+ * @param embeddings The embedding model that rejected the text.
15552
+ * @param text The rejected text.
15553
+ * @returns The embedding of the longest beginning the provider accepted.
15554
+ */
15555
+ async embedBeginningOf(embeddings, text) {
15556
+ logger.warn(`⚠️ Single text exceeded embedding size limit (${text.length} chars), embedding its beginning only.`);
15557
+ let beginning = text.substring(0, Math.floor(text.length / 2));
15558
+ let lastError;
15559
+ do {
15560
+ try {
15561
+ return await embeddings.embedDocuments([beginning]);
15562
+ } catch (error) {
15563
+ lastError = error;
15564
+ if (!this.isInputSizeError(error)) break;
15565
+ }
15566
+ beginning = beginning.substring(0, Math.floor(beginning.length / 2));
15567
+ } while (beginning.length >= MIN_TRUNCATED_EMBEDDING_CHARS);
15568
+ logger.error(`❌ Failed to embed even after truncating. Original length: ${text.length}`);
15569
+ throw lastError;
15570
+ }
15571
+ /**
15279
15572
  * Removes the row a refreshed page was read from, when it is not the row now
15280
15573
  * being written.
15281
15574
  *
@@ -16185,6 +16478,14 @@ var DocumentManagementService = class DocumentManagementService {
16185
16478
  return this.store.claimInterruptedVersion(versionId, updatedAt);
16186
16479
  }
16187
16480
  /**
16481
+ * Puts a version's status back, but only while it is still `queued`, and tells
16482
+ * views the library list changed.
16483
+ */
16484
+ async restoreVersionStatusIfQueued(versionId, status) {
16485
+ await this.store.restoreVersionStatusIfQueued(versionId, status);
16486
+ this.eventBus.emit(EventType.LIBRARY_CHANGE, void 0);
16487
+ }
16488
+ /**
16188
16489
  * Updates the status of a version, and tells views the library list changed.
16189
16490
  */
16190
16491
  async updateVersionStatus(versionId, status, errorMessage) {
@@ -16223,8 +16524,8 @@ var DocumentManagementService = class DocumentManagementService {
16223
16524
  * Creates or verifies the library and version an indexing job writes into, atomically.
16224
16525
  * See {@link DocumentStore.claimVersion} for the policy semantics and errors.
16225
16526
  */
16226
- async claimVersion(library, version, policy) {
16227
- return this.store.claimVersion(library, version, policy);
16527
+ async claimVersion(library, version, policy, options) {
16528
+ return this.store.claimVersion(library, version, policy, options);
16228
16529
  }
16229
16530
  /**
16230
16531
  * Looks up a version that must already exist, without creating anything.
@@ -16324,6 +16625,22 @@ var DocumentManagementService = class DocumentManagementService {
16324
16625
  return new LibraryNotFoundInStoreError(library, suggestions);
16325
16626
  }
16326
16627
  /**
16628
+ * Renames a library in place, keeping its versions and indexed content.
16629
+ *
16630
+ * @param library Current library name.
16631
+ * @param newName New name as entered; its trimmed form becomes the display name.
16632
+ * @returns The previous and new display names.
16633
+ * @throws {LibraryNotFoundInStoreError} If the library does not exist.
16634
+ */
16635
+ async renameLibrary(library, newName) {
16636
+ logger.info(`✏️ Renaming library: ${library} -> ${newName}`);
16637
+ const renamed = await this.store.renameLibrary(library, newName);
16638
+ if (!renamed) throw await this.libraryNotFound(library);
16639
+ this.eventBus.emit(EventType.LIBRARY_CHANGE, void 0);
16640
+ logger.info(`✅ Renamed '${renamed.oldName}' to '${renamed.newName}'.`);
16641
+ return renamed;
16642
+ }
16643
+ /**
16327
16644
  * Returns every label stored for a library — semantic versions and opaque tags
16328
16645
  * alike — in canonical display order.
16329
16646
  *
@@ -17907,7 +18224,7 @@ function createMcpServerInstance(tools, config, instructions, schemas) {
17907
18224
  const server = new McpServer({
17908
18225
  name,
17909
18226
  ...title !== void 0 ? { title } : {},
17910
- version: "3.4.1"
18227
+ version: "3.5.0"
17911
18228
  }, {
17912
18229
  capabilities: {
17913
18230
  tools: {},
@@ -19016,7 +19333,7 @@ function buildSystemInfo(serverConfig, appConfig, mcpEndpointUrl, workerUrl) {
19016
19333
  const mcpEnabled = Boolean(serverConfig.enableMcpServer);
19017
19334
  const authEnabled = Boolean(appConfig.auth.enabled);
19018
19335
  return {
19019
- version: "3.4.1",
19336
+ version: "3.5.0",
19020
19337
  readOnly: Boolean(appConfig.app.readOnly),
19021
19338
  telemetryEnabled: Boolean(appConfig.app.telemetryEnabled),
19022
19339
  services: {
@@ -19180,6 +19497,18 @@ createPipelineRouter(t$3);
19180
19497
  * tRPC router exposing document data store operations via the worker API.
19181
19498
  * Only procedures actually used externally are included to keep surface minimal.
19182
19499
  */
19500
+ /**
19501
+ * Maps a rename failure a caller can act on to its tRPC code, mirroring the
19502
+ * pipeline router's enqueue mapping. Anything else passes through unchanged.
19503
+ */
19504
+ function toRenameError(error) {
19505
+ const code = error instanceof LibraryAlreadyExistsError || error instanceof LibraryBusyError ? "CONFLICT" : error instanceof InvalidLibraryNameError ? "BAD_REQUEST" : error instanceof LibraryNotFoundInStoreError ? "NOT_FOUND" : null;
19506
+ return code && error instanceof Error ? new TRPCError({
19507
+ code,
19508
+ message: error.message,
19509
+ cause: error
19510
+ }) : error;
19511
+ }
19183
19512
  var t$2 = initTRPC.context().create({ transformer: superjson });
19184
19513
  /** A required name, trimmed. */
19185
19514
  var nonEmpty = z.string().trim().min(1);
@@ -19241,6 +19570,16 @@ function createDataRouter(trpc) {
19241
19570
  }).optional()).mutation(async ({ ctx, input }) => {
19242
19571
  return await ctx.docService.compact(input);
19243
19572
  }),
19573
+ renameLibrary: tt.procedure.input(z.object({
19574
+ library: nonEmpty,
19575
+ newName: nonEmpty
19576
+ })).mutation(async ({ ctx, input }) => {
19577
+ try {
19578
+ return await ctx.docService.renameLibrary(input.library, input.newName);
19579
+ } catch (error) {
19580
+ throw toRenameError(error);
19581
+ }
19582
+ }),
19244
19583
  getVersionsByStatus: tt.procedure.input(z.object({ statuses: z.array(z.string()) })).query(async ({ ctx, input }) => {
19245
19584
  const statuses = input.statuses;
19246
19585
  return await ctx.docService.getVersionsByStatus(statuses);
@@ -19688,7 +20027,7 @@ var AppServer = class AppServer {
19688
20027
  if (this.appConfig.app.telemetryEnabled && shouldEnableTelemetry()) try {
19689
20028
  if (telemetry.isEnabled()) {
19690
20029
  telemetry.setGlobalContext({
19691
- appVersion: "3.4.1",
20030
+ appVersion: "3.5.0",
19692
20031
  appPlatform: process.platform,
19693
20032
  appNodeVersion: process.version,
19694
20033
  appServicesEnabled: this.getActiveServicesList(),
@@ -20621,6 +20960,88 @@ function createRemoveCommand(cli) {
20621
20960
  }
20622
20961
  });
20623
20962
  }
20963
+ // src/tools/RenameTool.ts
20964
+ /**
20965
+ * Tool to rename a library in place, keeping its versions and indexed content.
20966
+ * Shared by the CLI; the store refuses the rename while a job writes into the library.
20967
+ */
20968
+ var RenameTool = class {
20969
+ documentManagementService;
20970
+ /**
20971
+ * @param documentManagementService Renames the library, locally or against a worker.
20972
+ */
20973
+ constructor(documentManagementService) {
20974
+ this.documentManagementService = documentManagementService;
20975
+ }
20976
+ /**
20977
+ * Executes the rename of the specified library.
20978
+ * Names are compared case-insensitively, so a case-only change updates the display name.
20979
+ */
20980
+ async execute(args) {
20981
+ const { library, newName } = args;
20982
+ if (!library || typeof library !== "string" || library.trim() === "") throw new ValidationError("Library name is required and must be a non-empty string.", this.constructor.name);
20983
+ if (!newName || typeof newName !== "string" || newName.trim() === "") throw new ValidationError("The new name is required and must be a non-empty string.", this.constructor.name);
20984
+ logger.info(`✏️ Renaming library: ${library} -> ${newName}`);
20985
+ try {
20986
+ await this.documentManagementService.validateLibraryExists(library);
20987
+ const { oldName, newName: renamed } = await this.documentManagementService.renameLibrary(library, newName);
20988
+ const message = `Successfully renamed ${oldName} to ${renamed}.`;
20989
+ logger.info(`✅ ${message}`);
20990
+ return { message };
20991
+ } catch (error) {
20992
+ if (error instanceof ToolError) throw error;
20993
+ const errorMessage = `Failed to rename ${library} to ${newName}: ${error instanceof Error ? error.message : String(error)}`;
20994
+ logger.error(`❌ Error renaming library: ${errorMessage}`);
20995
+ throw new ToolError(errorMessage, this.constructor.name);
20996
+ }
20997
+ }
20998
+ };
20999
+ // src/cli/commands/rename.ts
21000
+ function createRenameCommand(cli) {
21001
+ cli.command("rename <library> <new-name>", "Rename a library in place, keeping its versions and indexed content", (yargs) => {
21002
+ return yargs.version(false).positional("library", {
21003
+ type: "string",
21004
+ description: "Current library name",
21005
+ demandOption: true
21006
+ }).positional("new-name", {
21007
+ type: "string",
21008
+ description: "New library name",
21009
+ demandOption: true
21010
+ }).option("server-url", {
21011
+ type: "string",
21012
+ description: "URL of external pipeline worker RPC (e.g., http://localhost:8080/api)",
21013
+ alias: "serverUrl"
21014
+ });
21015
+ }, async (argv) => {
21016
+ await telemetry.track(TelemetryEvent.CLI_COMMAND, {
21017
+ command: "rename",
21018
+ library: argv.library,
21019
+ newName: argv.newName,
21020
+ useServerUrl: !!argv.serverUrl
21021
+ });
21022
+ const library = argv.library;
21023
+ const newName = argv.newName;
21024
+ const serverUrl = argv.serverUrl;
21025
+ const appConfig = loadConfig(argv, {
21026
+ configPath: argv.config,
21027
+ searchDir: argv.storePath
21028
+ });
21029
+ const backend = await openBackend({
21030
+ serverUrl,
21031
+ eventBus: getEventBus(argv),
21032
+ appConfig
21033
+ });
21034
+ try {
21035
+ const { message } = await new RenameTool(backend.docService).execute({
21036
+ library,
21037
+ newName
21038
+ });
21039
+ renderTextOutput(message);
21040
+ } finally {
21041
+ await backend.close();
21042
+ }
21043
+ });
21044
+ }
20624
21045
  // src/cli/commands/scrape.ts
20625
21046
  function createScrapeCommand(cli) {
20626
21047
  cli.command("scrape <library> <url>", "Download and index documentation from a URL or local directory", (yargs) => {
@@ -21002,6 +21423,7 @@ var COMMAND_FACTORIES = [
21002
21423
  createMcpCommand,
21003
21424
  createRefreshCommand,
21004
21425
  createRemoveCommand,
21426
+ createRenameCommand,
21005
21427
  createScrapeCommand,
21006
21428
  createSearchCommand,
21007
21429
  createWebCommand,
@@ -21046,7 +21468,7 @@ function registerGlobalOptions(cli) {
21046
21468
  function createCli(argv) {
21047
21469
  let globalEventBus = null;
21048
21470
  const commandStartTimes = /* @__PURE__ */ new Map();
21049
- const cli = registerGlobalOptions(yargs(hideBin(argv))).scriptName("docs-mcp-server").strict().usage("Usage: $0 <command> [options]").version("3.4.1").middleware(async (argv) => {
21471
+ const cli = registerGlobalOptions(yargs(hideBin(argv))).scriptName("docs-mcp-server").strict().usage("Usage: $0 <command> [options]").version("3.5.0").middleware(async (argv) => {
21050
21472
  if (argv.verbose && argv.quiet) throw new Error("Arguments verbose and quiet are mutually exclusive");
21051
21473
  applyGlobalCliOutputMode({
21052
21474
  verbose: argv.verbose,
@@ -21068,7 +21490,7 @@ function createCli(argv) {
21068
21490
  if (shouldEnableTelemetry() && telemetry.isEnabled()) {
21069
21491
  const commandName = argv._[0]?.toString() || "default";
21070
21492
  telemetry.setGlobalContext({
21071
- appVersion: "3.4.1",
21493
+ appVersion: "3.5.0",
21072
21494
  appPlatform: process.platform,
21073
21495
  appNodeVersion: process.version,
21074
21496
  appInterface: "cli",
@@ -21128,6 +21550,13 @@ var sigintHandler = async () => {
21128
21550
  }
21129
21551
  };
21130
21552
  /**
21553
+ * Waits until stdout and stderr have written everything queued so far. Writes
21554
+ * to a pipe are asynchronous, so exiting right away can cut off the output.
21555
+ */
21556
+ async function flushOutput() {
21557
+ await Promise.all([process.stdout, process.stderr].map((stream) => new Promise((resolve) => stream.write("", () => resolve()))));
21558
+ }
21559
+ /**
21131
21560
  * Performs cleanup for CLI commands that don't start long-running services.
21132
21561
  * This ensures proper analytics shutdown and process exit to prevent hanging.
21133
21562
  */
@@ -21136,6 +21565,7 @@ async function cleanupCliCommand() {
21136
21565
  logger.debug("CLI command executed. Cleaning up...");
21137
21566
  process.removeListener("SIGINT", sigintHandler);
21138
21567
  await telemetry.shutdown();
21568
+ await flushOutput();
21139
21569
  process.exit();
21140
21570
  }
21141
21571
  }
@@ -21172,6 +21602,7 @@ async function runCli() {
21172
21602
  await Promise.allSettled(shutdownPromises);
21173
21603
  await closeActiveBackend().catch((e) => logger.error(`❌ Error closing backend: ${e}`));
21174
21604
  }
21605
+ await flushOutput();
21175
21606
  process.exit(1);
21176
21607
  }
21177
21608
  const appServer = getActiveAppServer();
@@ -21179,4 +21610,4 @@ async function runCli() {
21179
21610
  }
21180
21611
  export { runCli };
21181
21612
 
21182
- //# sourceMappingURL=main-Cb6JaTXM.js.map
21613
+ //# sourceMappingURL=main-D3_JhsO7.js.map