@acanthis-dec/cli 0.2.3 → 0.3.1

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.
package/dist/index.mjs CHANGED
@@ -5,11 +5,13 @@ import fs from "node:fs/promises";
5
5
  import os from "node:os";
6
6
  import path from "node:path";
7
7
  import z from "zod";
8
- import { S_BAR, S_STEP_CANCEL, S_STEP_ERROR, S_STEP_SUBMIT, cancel, confirm, intro, isCI, isCancel, log, multiselect, note, outro, password, select, spinner, text, unicode, unicodeOr } from "@clack/prompts";
8
+ import { S_BAR, S_BAR_END, S_STEP_CANCEL, S_STEP_ERROR, S_STEP_SUBMIT, cancel, confirm, intro, isCI, isCancel, log, multiselect, note, outro, password, select, spinner, symbol, symbolBar, text, unicode, unicodeOr } from "@clack/prompts";
9
9
  import { createRequire } from "module";
10
10
  import { stripVTControlCharacters } from "node:util";
11
+ import fs$1 from "node:fs";
12
+ import readline from "node:readline";
11
13
  // package.json
12
- var version = "0.2.3";
14
+ var version = "0.3.1";
13
15
  // src/client.ts
14
16
  var ApiClientError = class extends Error {
15
17
  status;
@@ -576,6 +578,25 @@ async function withConcurrencyLimit(items, concurrency, worker) {
576
578
  await Promise.all(Array.from({ length: workerCount }, () => runWorker()));
577
579
  return results;
578
580
  }
581
+ /**
582
+ * Resolves a base output directory path, expanding `~` / `~/` / `~\` to the user's home directory
583
+ * and resolving relative paths against the current working directory.
584
+ */
585
+ function resolveOutputBaseDir(rawDir) {
586
+ const trimmed = rawDir.trim();
587
+ if (!trimmed) return path.resolve(".");
588
+ if (trimmed === "~") return os.homedir();
589
+ if (trimmed.startsWith("~/") || trimmed.startsWith("~\\")) return path.resolve(os.homedir(), trimmed.slice(2));
590
+ return path.resolve(trimmed);
591
+ }
592
+ /**
593
+ * Resolves the final export directory, appending a sanitized novel title subdirectory by default.
594
+ */
595
+ function resolveExportTargetDir(baseDir, novelTitle, subdir = true) {
596
+ const resolvedBase = resolveOutputBaseDir(baseDir);
597
+ if (!subdir) return resolvedBase;
598
+ return path.join(resolvedBase, sanitizeFilename(novelTitle));
599
+ }
579
600
  // src/commands/shared.ts
580
601
  const serverTokenArgs = {
581
602
  server: {
@@ -4199,6 +4220,14 @@ const HEADING_TAG_NAMES = /* @__PURE__ */ new Set([
4199
4220
  "h2",
4200
4221
  "h3"
4201
4222
  ]);
4223
+ const ALL_HEADING_TAG_NAMES = /* @__PURE__ */ new Set([
4224
+ "h1",
4225
+ "h2",
4226
+ "h3",
4227
+ "h4",
4228
+ "h5",
4229
+ "h6"
4230
+ ]);
4202
4231
  const URI_ATTRIBUTE_NAMES = /* @__PURE__ */ new Set([
4203
4232
  "href",
4204
4233
  "src",
@@ -4425,18 +4454,122 @@ function escapeNodesForXmlSerialization(nodes) {
4425
4454
  }
4426
4455
  }
4427
4456
  }
4428
- function sanitizeChapterHtmlToXhtml(options) {
4429
- const normalizedChildren = normalizeLeadingHeading(sanitizeNodeList(parseDocument(options.chapter.html, { decodeEntities: true }).children, options.imageHrefBySourceUrl), options.chapter.title);
4457
+ function hasSingleImageChild(element) {
4458
+ let foundImg = false;
4459
+ for (const child of element.children) {
4460
+ if (isText$1(child)) {
4461
+ if (child.data.trim().length > 0) return false;
4462
+ continue;
4463
+ }
4464
+ if (isTag$1(child)) {
4465
+ if (child.name.toLowerCase() === "img" && !foundImg) {
4466
+ foundImg = true;
4467
+ continue;
4468
+ }
4469
+ return false;
4470
+ }
4471
+ if (!isComment$1(child)) return false;
4472
+ }
4473
+ return foundImg;
4474
+ }
4475
+ function annotateChapterBlocks(nodes) {
4476
+ const result = [];
4477
+ let blockIndex = 0;
4478
+ for (const node of nodes) {
4479
+ if (isText$1(node)) {
4480
+ const trimmed = node.data.trim();
4481
+ if (!trimmed) {
4482
+ result.push(node);
4483
+ continue;
4484
+ }
4485
+ const wrapped = new Element$1("p", { id: `b${blockIndex}` }, [new Text$1(trimmed)]);
4486
+ wrapped.parent = node.parent;
4487
+ result.push(wrapped);
4488
+ blockIndex += 1;
4489
+ continue;
4490
+ }
4491
+ if (!isTag$1(node)) {
4492
+ result.push(node);
4493
+ continue;
4494
+ }
4495
+ const tag = node.name.toLowerCase();
4496
+ if (tag === "img") {
4497
+ node.attribs = {
4498
+ ...node.attribs,
4499
+ id: `b${blockIndex}`
4500
+ };
4501
+ result.push(node);
4502
+ blockIndex += 1;
4503
+ continue;
4504
+ }
4505
+ if (tag === "p") {
4506
+ if (hasSingleImageChild(node)) {
4507
+ node.attribs = {
4508
+ ...node.attribs,
4509
+ id: `b${blockIndex}`
4510
+ };
4511
+ result.push(node);
4512
+ blockIndex += 1;
4513
+ continue;
4514
+ }
4515
+ const hasText = collectTextContent(node).trim().length > 0;
4516
+ const hasElementChild = node.children.some((child) => isTag$1(child));
4517
+ if (!hasText && !hasElementChild) {
4518
+ result.push(node);
4519
+ continue;
4520
+ }
4521
+ node.attribs = {
4522
+ ...node.attribs,
4523
+ id: `b${blockIndex}`
4524
+ };
4525
+ result.push(node);
4526
+ blockIndex += 1;
4527
+ continue;
4528
+ }
4529
+ if (ALL_HEADING_TAG_NAMES.has(tag)) {
4530
+ node.attribs = {
4531
+ ...node.attribs,
4532
+ id: `b${blockIndex}`
4533
+ };
4534
+ result.push(node);
4535
+ blockIndex += 1;
4536
+ continue;
4537
+ }
4538
+ node.attribs = {
4539
+ ...node.attribs,
4540
+ id: `b${blockIndex}`
4541
+ };
4542
+ result.push(node);
4543
+ blockIndex += 1;
4544
+ }
4545
+ return {
4546
+ nodes: result,
4547
+ totalParagraphs: blockIndex
4548
+ };
4549
+ }
4550
+ function sanitizeChapterHtmlToXhtmlWithStats(options) {
4551
+ const sanitizedChildren = sanitizeNodeList(parseDocument(options.chapter.html, { decodeEntities: true }).children, options.imageHrefBySourceUrl);
4552
+ let childrenForHeading = sanitizedChildren;
4553
+ let totalParagraphs = 0;
4554
+ if (options.enableBlockAnchors) {
4555
+ const annotated = annotateChapterBlocks(sanitizedChildren);
4556
+ childrenForHeading = annotated.nodes;
4557
+ totalParagraphs = annotated.totalParagraphs;
4558
+ }
4559
+ const normalizedChildren = normalizeLeadingHeading(childrenForHeading, options.chapter.title);
4430
4560
  escapeNodesForXmlSerialization(normalizedChildren);
4431
4561
  const bodyHtml = render(normalizedChildren, {
4432
4562
  xmlMode: true,
4433
4563
  encodeEntities: false
4434
4564
  });
4435
- return wrapXhtmlDocument({
4436
- title: options.chapter.title,
4437
- language: options.language,
4438
- bodyHtml
4439
- });
4565
+ return {
4566
+ xhtml: wrapXhtmlDocument({
4567
+ title: options.chapter.title,
4568
+ language: options.language,
4569
+ bodyHtml
4570
+ }),
4571
+ totalParagraphs
4572
+ };
4440
4573
  }
4441
4574
  // ../../packages/epub/src/nav.ts
4442
4575
  function renderNavList(entries, indentLevel) {
@@ -4841,10 +4974,11 @@ function appendChapterEntry(options) {
4841
4974
  const manifestId = `ch-${paddedIndex}`;
4842
4975
  const manifestHref = `text/ch-${paddedIndex}.xhtml`;
4843
4976
  const zipPath = `OEBPS/${manifestHref}`;
4844
- const xhtml = sanitizeChapterHtmlToXhtml({
4977
+ const { xhtml, totalParagraphs } = sanitizeChapterHtmlToXhtmlWithStats({
4845
4978
  chapter: options.chapter,
4846
4979
  imageHrefBySourceUrl: options.imageHrefBySourceUrl,
4847
- language: options.language
4980
+ language: options.language,
4981
+ enableBlockAnchors: options.enableBlockAnchors
4848
4982
  });
4849
4983
  options.manifest.push({
4850
4984
  id: manifestId,
@@ -4857,8 +4991,11 @@ function appendChapterEntry(options) {
4857
4991
  content: xhtml
4858
4992
  });
4859
4993
  return {
4860
- title: options.chapter.title,
4861
- href: manifestHref
4994
+ navEntry: {
4995
+ title: options.chapter.title,
4996
+ href: manifestHref
4997
+ },
4998
+ totalParagraphs
4862
4999
  };
4863
5000
  }
4864
5001
  function buildVolumeEpub(input) {
@@ -4881,19 +5018,46 @@ function buildVolumeEpub(input) {
4881
5018
  binaryEntries
4882
5019
  }).coverImageId;
4883
5020
  const { imageHrefBySourceUrl, registeredImages } = registerIllustrations(input.illustrations);
5021
+ const enableBlockAnchors = input.syncMetadata !== void 0;
5022
+ const manifestChapters = [];
4884
5023
  let chapterCounter = 0;
4885
5024
  for (const chapter of input.chapters) {
4886
5025
  chapterCounter += 1;
4887
- const navEntry = appendChapterEntry({
5026
+ const { navEntry, totalParagraphs } = appendChapterEntry({
4888
5027
  chapter,
4889
5028
  chapterIndex: chapterCounter,
4890
5029
  language,
4891
5030
  imageHrefBySourceUrl,
4892
5031
  manifest,
4893
5032
  spine,
4894
- textEntries
5033
+ textEntries,
5034
+ enableBlockAnchors
4895
5035
  });
4896
5036
  navEntries.push(navEntry);
5037
+ if (enableBlockAnchors) manifestChapters.push({
5038
+ index: chapterCounter,
5039
+ href: navEntry.href,
5040
+ chapterId: chapter.id,
5041
+ title: chapter.title,
5042
+ totalParagraphs
5043
+ });
5044
+ }
5045
+ if (input.syncMetadata) {
5046
+ const acanthisManifest = {
5047
+ schemaVersion: 1,
5048
+ platform: input.syncMetadata.platform,
5049
+ novelId: input.syncMetadata.novelId,
5050
+ volumeId: input.syncMetadata.volumeId,
5051
+ volumeTitle: input.volumeTitle,
5052
+ profile: input.syncMetadata.profile,
5053
+ contentFingerprint: input.syncMetadata.contentFingerprint,
5054
+ generatedAt: modifiedAt.toISOString(),
5055
+ chapters: manifestChapters
5056
+ };
5057
+ textEntries.push({
5058
+ zipPath: "OEBPS/acanthis-manifest.json",
5059
+ content: `${JSON.stringify(acanthisManifest, null, 2)}\n`
5060
+ });
4897
5061
  }
4898
5062
  for (const image of registeredImages) {
4899
5063
  manifest.push({
@@ -4992,7 +5156,7 @@ function buildNovelEpub(input) {
4992
5156
  const volumeNavChildren = [];
4993
5157
  for (const chapter of volume.chapters) {
4994
5158
  chapterCounter += 1;
4995
- const chapterNavEntry = appendChapterEntry({
5159
+ const { navEntry: chapterNavEntry } = appendChapterEntry({
4996
5160
  chapter,
4997
5161
  chapterIndex: chapterCounter,
4998
5162
  language,
@@ -5299,7 +5463,8 @@ async function runExport(client, options, callbacks) {
5299
5463
  const novelCover = novel.coverUrl?.trim() ? assetByRawUrl.get(novel.coverUrl.trim()) : void 0;
5300
5464
  const summaryText = novel.summary.trim() ? novel.summary : void 0;
5301
5465
  const genresList = novel.genres.length > 0 ? novel.genres : void 0;
5302
- await fs.mkdir(options.outputDir, { recursive: true });
5466
+ const targetDir = resolveExportTargetDir(options.outputDir, novel.title, options.subdir !== false);
5467
+ await fs.mkdir(targetDir, { recursive: true });
5303
5468
  const files = [];
5304
5469
  if (options.mode === "split") {
5305
5470
  const totalSteps = selectedVolumes.length;
@@ -5309,7 +5474,7 @@ async function runExport(client, options, callbacks) {
5309
5474
  const volumeIllustUrls = illustrationUrlsPerVolume[vIdx];
5310
5475
  if (!volume || !chapters || !volumeIllustUrls) continue;
5311
5476
  const baseName = sanitizeFilename(`[${novel.author}] ${novel.title} - ${volume.title}`);
5312
- const targetPath = path.join(options.outputDir, `${baseName}.epub`);
5477
+ const targetPath = path.join(targetDir, `${baseName}.epub`);
5313
5478
  const displayTitle = `${novel.title} - ${volume.title}`;
5314
5479
  if (!options.overwrite && await fileExists(targetPath)) {
5315
5480
  emitWarning(`Skipped existing file: ${targetPath}`);
@@ -5385,7 +5550,7 @@ async function runExport(client, options, callbacks) {
5385
5550
  } else {
5386
5551
  const baseName = sanitizeFilename(`[${novel.author}] ${novel.title}`);
5387
5552
  const suffix = selectedAllVolumes ? "" : " (选集)";
5388
- const targetPath = path.join(options.outputDir, `${baseName}${suffix}.epub`);
5553
+ const targetPath = path.join(targetDir, `${baseName}${suffix}.epub`);
5389
5554
  const totalChapterCount = fetchedChaptersPerVolume.reduce((sum, list) => sum + list.length, 0);
5390
5555
  if (!options.overwrite && await fileExists(targetPath)) {
5391
5556
  emitWarning(`Skipped existing file: ${targetPath}`);
@@ -5445,7 +5610,7 @@ async function runExport(client, options, callbacks) {
5445
5610
  phase: "write",
5446
5611
  current: 1,
5447
5612
  total: 1,
5448
- message: `Writing ${targetPath}`
5613
+ message: `Writing ${path.basename(targetPath)}`
5449
5614
  });
5450
5615
  await fs.writeFile(targetPath, epubBytes);
5451
5616
  files.push({
@@ -5461,14 +5626,15 @@ async function runExport(client, options, callbacks) {
5461
5626
  novelTitle: novel.title,
5462
5627
  source: options.source,
5463
5628
  mode: options.mode,
5629
+ outputDir: targetDir,
5464
5630
  files,
5465
5631
  warnings
5466
5632
  };
5467
5633
  }
5468
5634
  // src/progress.ts
5469
5635
  const ESC_CODE = 27;
5470
- const CURSOR_HIDE = "\x1B[?25l";
5471
- const CURSOR_SHOW = "\x1B[?25h";
5636
+ const CURSOR_HIDE$1 = "\x1B[?25l";
5637
+ const CURSOR_SHOW$1 = "\x1B[?25h";
5472
5638
  const RESET_STYLE = "\x1B[0m";
5473
5639
  const SPINNER_FRAMES = unicode ? [
5474
5640
  "◒",
@@ -5485,9 +5651,9 @@ const SPINNER_DELAY_MS = unicode ? 80 : 120;
5485
5651
  const RENDER_THROTTLE_MS = 50;
5486
5652
  const BAR_FILLED = unicodeOr("█", "#");
5487
5653
  const BAR_EMPTY = unicodeOr("░", "-");
5488
- const ELLIPSIS = unicodeOr("…", "...");
5654
+ const ELLIPSIS$1 = unicodeOr("…", "...");
5489
5655
  const TRUNCATE_ELLIPSIS = unicodeOr("…", ".");
5490
- const CHEVRON = unicodeOr("›", ">");
5656
+ const CHEVRON$1 = unicodeOr("›", ">");
5491
5657
  const ICON_PENDING = unicodeOr("○", "o");
5492
5658
  const ICON_DONE = unicodeOr("✓", "+");
5493
5659
  const ICON_SKIPPED = unicodeOr("–", "-");
@@ -5717,7 +5883,7 @@ function createExportProgressRenderer(options) {
5717
5883
  };
5718
5884
  const formatActiveLine = (budget) => {
5719
5885
  if (activeVolumeTitle && activeDetail) {
5720
- const sepWidth = getDisplayWidth(` ${CHEVRON} `);
5886
+ const sepWidth = getDisplayWidth(` ${CHEVRON$1} `);
5721
5887
  const innerBudget = Math.max(4, budget - sepWidth);
5722
5888
  const volRaw = getDisplayWidth(activeVolumeTitle);
5723
5889
  const detailRaw = getDisplayWidth(activeDetail);
@@ -5742,7 +5908,7 @@ function createExportProgressRenderer(options) {
5742
5908
  }
5743
5909
  const volPart = truncatePlain(activeVolumeTitle, volLimit);
5744
5910
  const detailPart = truncatePlain(activeDetail, detailLimit);
5745
- return `${pc.cyan(volPart)} ${pc.dim(CHEVRON)} ${detailPart}`;
5911
+ return `${pc.cyan(volPart)} ${pc.dim(CHEVRON$1)} ${detailPart}`;
5746
5912
  }
5747
5913
  if (activeVolumeTitle) return pc.cyan(truncatePlain(activeVolumeTitle, budget));
5748
5914
  if (activeDetail) return truncatePlain(activeDetail, budget);
@@ -5870,14 +6036,14 @@ function createExportProgressRenderer(options) {
5870
6036
  const vol = volumes[i];
5871
6037
  if (vol && isVolumeCompleteInPhase(vol)) doneBefore += 1;
5872
6038
  }
5873
- lines.push(`${guidePrefix}${pc.dim(`${ELLIPSIS} ${start} earlier volume(s) (${doneBefore}/${start} done)`)}`);
6039
+ lines.push(`${guidePrefix}${pc.dim(`${ELLIPSIS$1} ${start} earlier volume(s) (${doneBefore}/${start} done)`)}`);
5874
6040
  }
5875
6041
  for (let i = start; i < end; i += 1) {
5876
6042
  const vol = volumes[i];
5877
6043
  if (!vol) continue;
5878
6044
  lines.push(buildVolumeRow(vol, spinnerFrame, columns, contentBudget));
5879
6045
  }
5880
- if (end < totalVolumes) lines.push(`${guidePrefix}${pc.dim(`${ELLIPSIS} ${totalVolumes - end} more volume(s)`)}`);
6046
+ if (end < totalVolumes) lines.push(`${guidePrefix}${pc.dim(`${ELLIPSIS$1} ${totalVolumes - end} more volume(s)`)}`);
5881
6047
  return lines.map((line) => truncateAnsi(line, maxLineWidth));
5882
6048
  };
5883
6049
  const renderFrame = () => {
@@ -5899,7 +6065,7 @@ function createExportProgressRenderer(options) {
5899
6065
  };
5900
6066
  const restoreCursorIfHidden = () => {
5901
6067
  if (cursorHidden) {
5902
- output.write(CURSOR_SHOW);
6068
+ output.write(CURSOR_SHOW$1);
5903
6069
  cursorHidden = false;
5904
6070
  }
5905
6071
  };
@@ -5962,7 +6128,7 @@ function createExportProgressRenderer(options) {
5962
6128
  return;
5963
6129
  }
5964
6130
  if (withGuide) output.write(`${pc.gray(S_BAR)}\n`);
5965
- output.write(CURSOR_HIDE);
6131
+ output.write(CURSOR_HIDE$1);
5966
6132
  cursorHidden = true;
5967
6133
  onResize = () => {
5968
6134
  renderFrame();
@@ -6110,9 +6276,15 @@ const exportCommand = defineCommand({
6110
6276
  output: {
6111
6277
  type: "string",
6112
6278
  alias: "o",
6113
- description: "Output directory for EPUB files",
6279
+ description: "Base output directory (supports relative paths and ~; defaults to current directory)",
6114
6280
  valueHint: "dir"
6115
6281
  },
6282
+ subdir: {
6283
+ type: "boolean",
6284
+ default: true,
6285
+ description: "Create a subdirectory named after the novel title inside the base output directory",
6286
+ negativeDescription: "Write EPUB file(s) directly into the base output directory without a novel subdirectory"
6287
+ },
6116
6288
  mode: {
6117
6289
  type: "string",
6118
6290
  alias: "m",
@@ -6185,6 +6357,7 @@ const exportCommand = defineCommand({
6185
6357
  source: config.defaultSource,
6186
6358
  token: config.token,
6187
6359
  outputDir: config.outputDir,
6360
+ subdir: args.subdir !== false,
6188
6361
  mode: effectiveMode,
6189
6362
  volumes: volumesSpec,
6190
6363
  illustrations: args.illustrations !== false,
@@ -6381,6 +6554,550 @@ const sourcesCommand = defineCommand({
6381
6554
  }
6382
6555
  }
6383
6556
  });
6557
+ // src/dir-prompt.ts
6558
+ const CURSOR_HIDE = "\x1B[?25l";
6559
+ const CURSOR_SHOW = "\x1B[?25h";
6560
+ const CHEVRON = unicodeOr("▸", ">");
6561
+ const ARROW_RIGHT = unicodeOr("→", "->");
6562
+ const ELLIPSIS = unicodeOr("…", "...");
6563
+ const DIR_PROMPT_CANCEL = Symbol("acanthis:dir-prompt-cancel");
6564
+ /**
6565
+ * Checks whether a value returned from `promptDirectory` indicates cancellation.
6566
+ */
6567
+ function isDirectoryPromptCancel(value) {
6568
+ return value === DIR_PROMPT_CANCEL;
6569
+ }
6570
+ function resolveBaseWithContext(rawDir, cwd, homeDir) {
6571
+ const trimmed = rawDir.trim();
6572
+ if (!trimmed) return path.resolve(cwd);
6573
+ if (trimmed === "~") return homeDir;
6574
+ if (trimmed.startsWith("~/") || trimmed.startsWith("~\\")) return path.resolve(homeDir, trimmed.slice(2));
6575
+ return path.resolve(cwd, trimmed);
6576
+ }
6577
+ function detectSeparator(rawInput, platform) {
6578
+ if (rawInput.includes("/")) return "/";
6579
+ if (rawInput.includes("\\")) return "\\";
6580
+ return platform === "win32" ? "\\" : "/";
6581
+ }
6582
+ function listSubdirectories(dirPath, cache) {
6583
+ const cached = cache?.get(dirPath);
6584
+ if (cached !== void 0) return cached;
6585
+ let entries;
6586
+ try {
6587
+ entries = fs$1.readdirSync(dirPath, { withFileTypes: true });
6588
+ } catch {
6589
+ return [];
6590
+ }
6591
+ const dirs = [];
6592
+ for (const entry of entries) {
6593
+ if (entry.isDirectory()) {
6594
+ dirs.push(entry.name);
6595
+ continue;
6596
+ }
6597
+ if (entry.isSymbolicLink()) try {
6598
+ if (fs$1.statSync(path.join(dirPath, entry.name)).isDirectory()) dirs.push(entry.name);
6599
+ } catch {}
6600
+ }
6601
+ dirs.sort((a, b) => a.localeCompare(b, "en", {
6602
+ sensitivity: "base",
6603
+ numeric: true
6604
+ }));
6605
+ cache?.set(dirPath, dirs);
6606
+ return dirs;
6607
+ }
6608
+ function computeLongestCommonPrefix(values) {
6609
+ if (values.length === 0) return "";
6610
+ const firstValue = values[0];
6611
+ if (firstValue === void 0) return "";
6612
+ if (values.length === 1) return firstValue;
6613
+ const splitValues = values.map((v) => [...v]);
6614
+ const firstChars = splitValues[0] ?? [];
6615
+ let prefix = "";
6616
+ for (let i = 0; i < firstChars.length; i += 1) {
6617
+ const targetChar = firstChars[i];
6618
+ if (targetChar === void 0) break;
6619
+ const targetLower = targetChar.toLowerCase();
6620
+ let allMatch = true;
6621
+ for (let j = 1; j < splitValues.length; j += 1) {
6622
+ const candidateChar = splitValues[j]?.[i];
6623
+ if (candidateChar === void 0 || candidateChar.toLowerCase() !== targetLower) {
6624
+ allMatch = false;
6625
+ break;
6626
+ }
6627
+ }
6628
+ if (!allMatch) break;
6629
+ prefix += targetChar;
6630
+ }
6631
+ return prefix;
6632
+ }
6633
+ /**
6634
+ * Computes the remaining suffix to render as inline ghost text for a candidate path.
6635
+ */
6636
+ function computeGhostSuffix(rawInput, candidate) {
6637
+ if (!candidate) return "";
6638
+ if (candidate.length > rawInput.length && candidate.toLowerCase().startsWith(rawInput.toLowerCase())) return candidate.slice(rawInput.length);
6639
+ return "";
6640
+ }
6641
+ /**
6642
+ * Computes matching subdirectory completions for a partially typed path.
6643
+ */
6644
+ function getDirectoryCompletions(rawInput, options) {
6645
+ const cwd = options?.cwd ?? process.cwd();
6646
+ const homeDir = options?.homeDir ?? os.homedir();
6647
+ const platform = options?.platform ?? process.platform;
6648
+ const sep = detectSeparator(rawInput, platform);
6649
+ let dirPrefixDisplay = "";
6650
+ let searchDirFs = cwd;
6651
+ let namePrefix = "";
6652
+ if (rawInput === "") {
6653
+ dirPrefixDisplay = "";
6654
+ searchDirFs = cwd;
6655
+ namePrefix = "";
6656
+ } else if (rawInput === ".") {
6657
+ dirPrefixDisplay = `.${sep}`;
6658
+ searchDirFs = cwd;
6659
+ namePrefix = "";
6660
+ } else if (rawInput === "..") {
6661
+ dirPrefixDisplay = `..${sep}`;
6662
+ searchDirFs = path.resolve(cwd, "..");
6663
+ namePrefix = "";
6664
+ } else if (rawInput === "~") {
6665
+ dirPrefixDisplay = `~${sep}`;
6666
+ searchDirFs = homeDir;
6667
+ namePrefix = "";
6668
+ } else if (rawInput.endsWith("/") || rawInput.endsWith("\\")) {
6669
+ dirPrefixDisplay = rawInput;
6670
+ searchDirFs = resolveBaseWithContext(rawInput, cwd, homeDir);
6671
+ namePrefix = "";
6672
+ } else {
6673
+ const lastSepIdx = Math.max(rawInput.lastIndexOf("/"), rawInput.lastIndexOf("\\"));
6674
+ if (lastSepIdx >= 0) {
6675
+ dirPrefixDisplay = rawInput.slice(0, lastSepIdx + 1);
6676
+ namePrefix = rawInput.slice(lastSepIdx + 1);
6677
+ searchDirFs = resolveBaseWithContext(dirPrefixDisplay, cwd, homeDir);
6678
+ } else {
6679
+ dirPrefixDisplay = "";
6680
+ namePrefix = rawInput;
6681
+ searchDirFs = cwd;
6682
+ }
6683
+ }
6684
+ const allDirs = listSubdirectories(searchDirFs, options?.cache);
6685
+ const includeHidden = namePrefix.startsWith(".");
6686
+ const namePrefixLower = namePrefix.toLowerCase();
6687
+ const filtered = allDirs.filter((name) => {
6688
+ if (!includeHidden && name.startsWith(".")) return false;
6689
+ if (namePrefix.length === 0) return true;
6690
+ return name.toLowerCase().startsWith(namePrefixLower);
6691
+ });
6692
+ if (namePrefix.length > 0 && platform !== "win32") filtered.sort((a, b) => {
6693
+ const aExact = a.startsWith(namePrefix) ? 0 : 1;
6694
+ const bExact = b.startsWith(namePrefix) ? 0 : 1;
6695
+ if (aExact !== bExact) return aExact - bExact;
6696
+ return a.localeCompare(b, "en", {
6697
+ sensitivity: "base",
6698
+ numeric: true
6699
+ });
6700
+ });
6701
+ const matches = filtered.map((name) => `${dirPrefixDisplay}${name}${sep}`);
6702
+ return {
6703
+ matches,
6704
+ labels: filtered.map((name) => `${name}${sep}`),
6705
+ commonPrefix: computeLongestCommonPrefix(matches),
6706
+ ghostSuffix: computeGhostSuffix(rawInput, matches[0]),
6707
+ resolvedParentDir: searchDirFs
6708
+ };
6709
+ }
6710
+ function stripNonPrintable(str) {
6711
+ let cleaned = "";
6712
+ for (const ch of str) {
6713
+ const cp = ch.codePointAt(0);
6714
+ if (cp !== void 0 && cp >= 32 && cp !== 127) cleaned += ch;
6715
+ }
6716
+ return cleaned;
6717
+ }
6718
+ function deleteLastPathSegment(beforeCursor) {
6719
+ if (!beforeCursor) return "";
6720
+ const chars = [...beforeCursor];
6721
+ while (chars.length > 0) {
6722
+ const last = chars[chars.length - 1];
6723
+ if (last === "/" || last === "\\") chars.pop();
6724
+ else break;
6725
+ }
6726
+ while (chars.length > 0) {
6727
+ const last = chars[chars.length - 1];
6728
+ if (last === "/" || last === "\\") break;
6729
+ chars.pop();
6730
+ }
6731
+ return chars.join("");
6732
+ }
6733
+ /**
6734
+ * Prompts the user for a directory path with zsh-autosuggestions / PSReadLine-style
6735
+ * inline ghost suggestions, Tab/Shift+Tab cycling, arrow selection, and path preview.
6736
+ */
6737
+ async function promptDirectory(options) {
6738
+ const input = options.input ?? process.stdin;
6739
+ const output = options.output ?? process.stdout;
6740
+ if (!input.isTTY || !output.isTTY) {
6741
+ const validateFn = options.validate;
6742
+ const fallbackOpts = {
6743
+ message: options.message,
6744
+ ...options.initialValue !== void 0 ? {
6745
+ initialValue: options.initialValue,
6746
+ defaultValue: options.initialValue
6747
+ } : {},
6748
+ ...options.placeholder !== void 0 ? { placeholder: options.placeholder } : {},
6749
+ ...validateFn !== void 0 ? { validate: (val) => validateFn(val ?? "") } : {}
6750
+ };
6751
+ const result = await text(fallbackOpts);
6752
+ return isCancel(result) ? DIR_PROMPT_CANCEL : result;
6753
+ }
6754
+ return await new Promise((resolve) => {
6755
+ let buffer = options.initialValue ?? ".";
6756
+ let cursor = [...buffer].length;
6757
+ let errorMessage = "";
6758
+ let selectedIndex = 0;
6759
+ let lastRenderedLines = 0;
6760
+ let settled = false;
6761
+ let tabCycle;
6762
+ const dirCache = /* @__PURE__ */ new Map();
6763
+ let completions = getDirectoryCompletions(buffer, { cache: dirCache });
6764
+ const refreshSuggestions = (resetSelection = true) => {
6765
+ tabCycle = void 0;
6766
+ completions = getDirectoryCompletions(buffer, { cache: dirCache });
6767
+ if (completions.matches.length === 0) selectedIndex = 0;
6768
+ else if (resetSelection) selectedIndex = 0;
6769
+ else if (selectedIndex >= completions.matches.length) selectedIndex = completions.matches.length - 1;
6770
+ };
6771
+ const buildActiveInputDisplay = () => {
6772
+ const chars = [...buffer];
6773
+ const before = chars.slice(0, cursor).join("");
6774
+ if (cursor < chars.length) {
6775
+ const atCursor = chars[cursor] ?? " ";
6776
+ const after = chars.slice(cursor + 1).join("");
6777
+ return `${before}${pc.inverse(atCursor)}${after}`;
6778
+ }
6779
+ if (tabCycle) return `${buffer}${pc.inverse(" ")}`;
6780
+ const activeCandidate = completions.matches[selectedIndex];
6781
+ const ghostSuffix = computeGhostSuffix(buffer, activeCandidate);
6782
+ if (ghostSuffix.length > 0) {
6783
+ const ghostChars = [...ghostSuffix];
6784
+ const firstGhost = ghostChars[0] ?? " ";
6785
+ const restGhost = ghostChars.slice(1).join("");
6786
+ return `${buffer}${pc.inverse(firstGhost)}${pc.dim(restGhost)}`;
6787
+ }
6788
+ if (buffer.length === 0 && options.placeholder) {
6789
+ const placeholderChars = [...options.placeholder];
6790
+ const firstPh = placeholderChars[0] ?? " ";
6791
+ const restPh = placeholderChars.slice(1).join("");
6792
+ return `${pc.inverse(firstPh)}${pc.dim(restPh)}`;
6793
+ }
6794
+ return `${buffer}${pc.inverse(" ")}`;
6795
+ };
6796
+ const renderState = (state) => {
6797
+ const columns = Math.max(20, output.columns || 80);
6798
+ const rows = Math.max(8, output.rows || 24);
6799
+ const maxLineWidth = Math.max(19, columns - 1);
6800
+ const lines = [];
6801
+ lines.push(`${symbol(state)} ${options.message}`);
6802
+ if (state === "submit") lines.push(`${pc.gray(S_BAR)} ${pc.dim(buffer)}`);
6803
+ else if (state === "cancel") {
6804
+ if (buffer.length > 0) lines.push(`${pc.gray(S_BAR)} ${pc.strikethrough(pc.dim(buffer))}`);
6805
+ lines.push(pc.gray(S_BAR));
6806
+ } else {
6807
+ const bar = `${symbolBar(state)} `;
6808
+ const barEnd = state === "error" ? pc.yellow(S_BAR_END) : pc.cyan(S_BAR_END);
6809
+ lines.push(`${bar}${buildActiveInputDisplay()}`);
6810
+ const activeLabels = tabCycle ? tabCycle.labels : completions.labels;
6811
+ const activeHighlight = tabCycle ? tabCycle.index : selectedIndex;
6812
+ const reservedRows = options.preview !== void 0 ? 6 : 5;
6813
+ const maxVisible = Math.max(2, Math.min(5, rows - reservedRows));
6814
+ if (activeLabels.length > 0) {
6815
+ let start = 0;
6816
+ let end = activeLabels.length;
6817
+ if (activeLabels.length > maxVisible) {
6818
+ const half = Math.floor(maxVisible / 2);
6819
+ start = Math.max(0, activeHighlight - half);
6820
+ if (start + maxVisible > activeLabels.length) start = Math.max(0, activeLabels.length - maxVisible);
6821
+ end = Math.min(activeLabels.length, start + maxVisible);
6822
+ }
6823
+ const labelBudget = Math.max(10, maxLineWidth - 6);
6824
+ for (let i = start; i < end; i += 1) {
6825
+ const shownLabel = truncatePlain(activeLabels[i] ?? "", labelBudget);
6826
+ if (i === activeHighlight) lines.push(`${bar} ${pc.cyan(CHEVRON)} ${pc.cyan(shownLabel)}`);
6827
+ else lines.push(`${bar} ${pc.dim(shownLabel)}`);
6828
+ }
6829
+ const hiddenCount = activeLabels.length - (end - start);
6830
+ if (hiddenCount > 0) lines.push(`${bar} ${pc.dim(`${ELLIPSIS} +${hiddenCount} more`)}`);
6831
+ }
6832
+ if (options.preview) {
6833
+ const previewText = options.preview(buffer);
6834
+ if (previewText) {
6835
+ const shownPreview = truncatePlain(previewText, Math.max(10, maxLineWidth - 6));
6836
+ lines.push(`${bar}${pc.dim(`${ARROW_RIGHT} ${shownPreview}`)}`);
6837
+ }
6838
+ }
6839
+ if (state === "error" && errorMessage) lines.push(`${barEnd} ${pc.yellow(errorMessage)}`);
6840
+ else {
6841
+ const hintText = "Tab: complete • →: accept • ↑/↓: pick • Enter: confirm";
6842
+ const hintBudget = Math.max(10, maxLineWidth - 3);
6843
+ const shownHint = getDisplayWidth(hintText) <= hintBudget ? hintText : "Tab • → • ↑/↓ • Enter";
6844
+ lines.push(`${barEnd} ${pc.dim(shownHint)}`);
6845
+ }
6846
+ }
6847
+ const clampedLines = lines.map((line) => truncateAnsi(line, maxLineWidth));
6848
+ let frame = "";
6849
+ if (lastRenderedLines > 1) frame += `\x1b[${lastRenderedLines - 1}A`;
6850
+ if (lastRenderedLines > 0) frame += "\r\x1B[0J";
6851
+ frame += clampedLines.join("\n");
6852
+ if (state === "submit" || state === "cancel") frame += "\n";
6853
+ output.write(frame);
6854
+ lastRenderedLines = clampedLines.length;
6855
+ };
6856
+ const rl = readline.createInterface({
6857
+ input,
6858
+ tabSize: 2,
6859
+ prompt: "",
6860
+ escapeCodeTimeout: 50,
6861
+ terminal: true
6862
+ });
6863
+ const onResize = () => {
6864
+ if (!settled) renderState(errorMessage ? "error" : "active");
6865
+ };
6866
+ const onExit = () => {
6867
+ output.write(CURSOR_SHOW);
6868
+ };
6869
+ const cleanup = () => {
6870
+ if (settled) return;
6871
+ settled = true;
6872
+ input.off("keypress", onKeypress);
6873
+ output.off("resize", onResize);
6874
+ process.off("exit", onExit);
6875
+ rl.terminal = false;
6876
+ rl.close();
6877
+ rawInputSetMode(false);
6878
+ output.write(CURSOR_SHOW);
6879
+ };
6880
+ const rawInputSetMode = (mode) => {
6881
+ if (input.isTTY && typeof input.setRawMode === "function") input.setRawMode(mode);
6882
+ };
6883
+ const acceptCandidate = (candidate) => {
6884
+ buffer = candidate;
6885
+ cursor = [...buffer].length;
6886
+ errorMessage = "";
6887
+ refreshSuggestions(true);
6888
+ };
6889
+ const onKeypress = (str, key) => {
6890
+ if (settled) return;
6891
+ const keyName = key?.name ?? "";
6892
+ if (keyName === "escape" || key?.ctrl && keyName === "c") {
6893
+ renderState("cancel");
6894
+ cleanup();
6895
+ resolve(DIR_PROMPT_CANCEL);
6896
+ return;
6897
+ }
6898
+ if (keyName === "return" || keyName === "enter") {
6899
+ tabCycle = void 0;
6900
+ const validationError = options.validate?.(buffer);
6901
+ if (validationError) {
6902
+ errorMessage = validationError;
6903
+ renderState("error");
6904
+ return;
6905
+ }
6906
+ errorMessage = "";
6907
+ renderState("submit");
6908
+ cleanup();
6909
+ resolve(buffer);
6910
+ return;
6911
+ }
6912
+ if (keyName === "tab") {
6913
+ errorMessage = "";
6914
+ if (tabCycle && tabCycle.candidates.length > 0) {
6915
+ const len = tabCycle.candidates.length;
6916
+ tabCycle.index = key?.shift ? (tabCycle.index - 1 + len) % len : (tabCycle.index + 1) % len;
6917
+ const nextCandidate = tabCycle.candidates[tabCycle.index];
6918
+ if (nextCandidate !== void 0) {
6919
+ buffer = nextCandidate;
6920
+ cursor = [...buffer].length;
6921
+ }
6922
+ renderState("active");
6923
+ return;
6924
+ }
6925
+ if (completions.matches.length === 1 && completions.matches[0]) {
6926
+ acceptCandidate(completions.matches[0]);
6927
+ renderState("active");
6928
+ return;
6929
+ }
6930
+ if (completions.matches.length > 1) {
6931
+ if (completions.commonPrefix.length > buffer.length && completions.commonPrefix.toLowerCase().startsWith(buffer.toLowerCase())) {
6932
+ buffer = completions.commonPrefix;
6933
+ cursor = [...buffer].length;
6934
+ refreshSuggestions(true);
6935
+ renderState("active");
6936
+ return;
6937
+ }
6938
+ const initialIdx = key?.shift ? completions.matches.length - 1 : selectedIndex;
6939
+ const chosen = completions.matches[initialIdx];
6940
+ if (chosen !== void 0) {
6941
+ tabCycle = {
6942
+ candidates: completions.matches,
6943
+ labels: completions.labels,
6944
+ index: initialIdx
6945
+ };
6946
+ buffer = chosen;
6947
+ cursor = [...buffer].length;
6948
+ }
6949
+ renderState("active");
6950
+ return;
6951
+ }
6952
+ renderState("active");
6953
+ return;
6954
+ }
6955
+ if (keyName === "up" || keyName === "down") {
6956
+ errorMessage = "";
6957
+ const delta = keyName === "up" ? -1 : 1;
6958
+ if (tabCycle && tabCycle.candidates.length > 0) {
6959
+ const len = tabCycle.candidates.length;
6960
+ tabCycle.index = (tabCycle.index + delta + len) % len;
6961
+ const nextCandidate = tabCycle.candidates[tabCycle.index];
6962
+ if (nextCandidate !== void 0) {
6963
+ buffer = nextCandidate;
6964
+ cursor = [...buffer].length;
6965
+ }
6966
+ } else if (completions.matches.length > 0) {
6967
+ const len = completions.matches.length;
6968
+ selectedIndex = (selectedIndex + delta + len) % len;
6969
+ }
6970
+ renderState("active");
6971
+ return;
6972
+ }
6973
+ if (keyName === "right") {
6974
+ errorMessage = "";
6975
+ if (tabCycle) {
6976
+ refreshSuggestions(true);
6977
+ renderState("active");
6978
+ return;
6979
+ }
6980
+ const chars = [...buffer];
6981
+ if (cursor < chars.length) {
6982
+ cursor += 1;
6983
+ renderState("active");
6984
+ return;
6985
+ }
6986
+ const activeCandidate = completions.matches[selectedIndex];
6987
+ if (activeCandidate && computeGhostSuffix(buffer, activeCandidate).length > 0) {
6988
+ acceptCandidate(activeCandidate);
6989
+ renderState("active");
6990
+ }
6991
+ return;
6992
+ }
6993
+ if (keyName === "end" || key?.ctrl && keyName === "e") {
6994
+ errorMessage = "";
6995
+ if (tabCycle) {
6996
+ refreshSuggestions(true);
6997
+ renderState("active");
6998
+ return;
6999
+ }
7000
+ const chars = [...buffer];
7001
+ if (cursor < chars.length) {
7002
+ cursor = chars.length;
7003
+ renderState("active");
7004
+ return;
7005
+ }
7006
+ const activeCandidate = completions.matches[selectedIndex];
7007
+ if (activeCandidate && computeGhostSuffix(buffer, activeCandidate).length > 0) {
7008
+ acceptCandidate(activeCandidate);
7009
+ renderState("active");
7010
+ }
7011
+ return;
7012
+ }
7013
+ if (keyName === "left") {
7014
+ errorMessage = "";
7015
+ tabCycle = void 0;
7016
+ cursor = Math.max(0, cursor - 1);
7017
+ renderState("active");
7018
+ return;
7019
+ }
7020
+ if (keyName === "home" || key?.ctrl && keyName === "a") {
7021
+ errorMessage = "";
7022
+ tabCycle = void 0;
7023
+ cursor = 0;
7024
+ renderState("active");
7025
+ return;
7026
+ }
7027
+ if (keyName === "backspace") {
7028
+ errorMessage = "";
7029
+ tabCycle = void 0;
7030
+ if (cursor > 0) {
7031
+ const chars = [...buffer];
7032
+ chars.splice(cursor - 1, 1);
7033
+ buffer = chars.join("");
7034
+ cursor -= 1;
7035
+ refreshSuggestions(true);
7036
+ }
7037
+ renderState("active");
7038
+ return;
7039
+ }
7040
+ if (keyName === "delete") {
7041
+ errorMessage = "";
7042
+ tabCycle = void 0;
7043
+ const chars = [...buffer];
7044
+ if (cursor < chars.length) {
7045
+ chars.splice(cursor, 1);
7046
+ buffer = chars.join("");
7047
+ refreshSuggestions(true);
7048
+ }
7049
+ renderState("active");
7050
+ return;
7051
+ }
7052
+ if (key?.ctrl && keyName === "u") {
7053
+ errorMessage = "";
7054
+ tabCycle = void 0;
7055
+ if (cursor > 0) {
7056
+ buffer = [...buffer].slice(cursor).join("");
7057
+ cursor = 0;
7058
+ refreshSuggestions(true);
7059
+ }
7060
+ renderState("active");
7061
+ return;
7062
+ }
7063
+ if (key?.ctrl && keyName === "w") {
7064
+ errorMessage = "";
7065
+ tabCycle = void 0;
7066
+ if (cursor > 0) {
7067
+ const chars = [...buffer];
7068
+ const before = chars.slice(0, cursor).join("");
7069
+ const after = chars.slice(cursor).join("");
7070
+ const newBefore = deleteLastPathSegment(before);
7071
+ buffer = `${newBefore}${after}`;
7072
+ cursor = [...newBefore].length;
7073
+ refreshSuggestions(true);
7074
+ }
7075
+ renderState("active");
7076
+ return;
7077
+ }
7078
+ if (!key?.ctrl && !key?.meta && str !== void 0 && str.length > 0) {
7079
+ const printable = stripNonPrintable(str);
7080
+ if (printable.length > 0) {
7081
+ errorMessage = "";
7082
+ const chars = [...buffer];
7083
+ const insertedChars = [...printable];
7084
+ chars.splice(cursor, 0, ...insertedChars);
7085
+ buffer = chars.join("");
7086
+ cursor += insertedChars.length;
7087
+ refreshSuggestions(true);
7088
+ renderState("active");
7089
+ }
7090
+ }
7091
+ };
7092
+ rl.prompt();
7093
+ output.write(`${pc.gray(S_BAR)}\n${CURSOR_HIDE}`);
7094
+ input.on("keypress", onKeypress);
7095
+ output.on("resize", onResize);
7096
+ process.on("exit", onExit);
7097
+ rawInputSetMode(true);
7098
+ renderState("active");
7099
+ });
7100
+ }
6384
7101
  // src/interactive.ts
6385
7102
  var WizardCancelledError = class extends Error {
6386
7103
  constructor() {
@@ -6389,7 +7106,7 @@ var WizardCancelledError = class extends Error {
6389
7106
  }
6390
7107
  };
6391
7108
  function unwrapPrompt(value) {
6392
- if (isCancel(value)) {
7109
+ if (isCancel(value) || isDirectoryPromptCancel(value)) {
6393
7110
  cancel("Operation cancelled.");
6394
7111
  throw new WizardCancelledError();
6395
7112
  }
@@ -6717,11 +7434,16 @@ async function runInteractiveWizard() {
6717
7434
  label: "Merged (single EPUB for all selected volumes)"
6718
7435
  }]
6719
7436
  }));
6720
- const outputDir = unwrapPrompt(await text({
6721
- message: "Output directory:",
7437
+ const outputDir = unwrapPrompt(await promptDirectory({
7438
+ message: `Base output directory (subdir: ${sanitizeFilename(novel.title)}):`,
6722
7439
  initialValue: config.outputDir,
6723
- defaultValue: config.outputDir,
6724
- validate: (value) => value?.trim() ? void 0 : "Output directory cannot be empty"
7440
+ placeholder: ".",
7441
+ preview: (value) => {
7442
+ const trimmed = value.trim();
7443
+ if (!trimmed) return;
7444
+ return resolveExportTargetDir(trimmed, novel.title, true);
7445
+ },
7446
+ validate: (value) => value.trim() ? void 0 : "Output directory cannot be empty"
6725
7447
  })).trim();
6726
7448
  const illustrations = unwrapPrompt(await confirm({
6727
7449
  message: "Download and embed chapter illustrations?",
@@ -6746,6 +7468,7 @@ async function runInteractiveWizard() {
6746
7468
  source,
6747
7469
  token,
6748
7470
  outputDir,
7471
+ subdir: true,
6749
7472
  mode,
6750
7473
  volumes: selectedVolumeIndices.join(","),
6751
7474
  illustrations,