Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
276 changes: 203 additions & 73 deletions src/walkthrough/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,25 @@ import type { Config } from "../plugins/config/index.ts";
import type { Logger } from "../plugins/logger/index.ts";
import type { SourceAdapter } from "../sources/adapters/index.ts";
import { getAdapter } from "../sources/adapters/index.ts";
import type { SourceDescriptor } from "../sources/types.ts";
import { createProgress } from "./progress.ts";
import { checkAuth, refreshSession } from "./steps/auth-check.ts";
import { promptCoverUrl } from "./steps/cover-prompt.ts";
import type { ExecuteDeps } from "./steps/execute.ts";
import { executeWalkthrough } from "./steps/execute.ts";
import { pickMode } from "./steps/mode-picker.ts";
import { promptNextAction } from "./steps/next-action-prompt.ts";
import { promptPack } from "./steps/pack-prompt.ts";
import { pickRange } from "./steps/range-picker.ts";
import { pickSearchResult } from "./steps/search-results-picker.ts";
import { pickSource } from "./steps/source-picker.ts";
import { promptTitle } from "./steps/title-prompt.ts";
import { promptVolumeName } from "./steps/volume-name-prompt.ts";
import type {
ChapterListing,
SearchHit,
SessionProbeClientFactory,
VolumeListing,
WalkthroughCancelled,
WalkthroughInput,
WalkthroughResult,
Expand Down Expand Up @@ -67,6 +72,15 @@ export interface WalkthroughFailed {
reason: string;
}

/**
* In-memory cache of listings already fetched for the current manga (hit),
* so the "same manga" post-download branch never re-hits the adapter.
*/
interface ChapterListingCache {
chapters: ChapterListing[] | null;
volumes: VolumeListing[] | null;
}

/**
* Composes all 9 walkthrough steps in order.
* Returns the assembled plan + execution result on success.
Expand All @@ -80,10 +94,7 @@ export async function runWalkthrough(
const outDir = opts.outDir ?? process.cwd();

try {
// Step 1 — title
const title = await promptTitle();

// Step 2 — source
// Step 2 — source (picked once per session; reused across "new manga" iterations)
const source = await pickSource();

// Step 3 — auth check (probe session when factory provided; production uses real fallback-http)
Expand Down Expand Up @@ -122,80 +133,79 @@ export async function runWalkthrough(
// Resolve adapter for this source (after auth check so session is persisted if needed)
const adapter = resolveAdapter(source.id, { logger: opts.logger, config: opts.config });

// Step 4 — search results (with CF retry)
const hit = await withSessionRetry(
() =>
pickSearchResult({
query: title,
sourceLabel: source.label,
adapter,
}),
isCloudflareError,
doRefresh,
opts.logger,
"walkthrough.search_retry",
);

// Step 5 — mode
const mode = await pickMode();
let lastResult: WalkthroughResult | null = null;
let hit: SearchHit | null = null;
let cache: ChapterListingCache | null = null;

// Step 6 — range (with CF retry)
const selectedBundles = await withSessionRetry(
() => pickRange({ hit, mode, adapter }),
isCloudflareError,
doRefresh,
opts.logger,
"walkthrough.range_retry",
);

// Step 7 — pack prompt (chapter mode only)
// volume mode always packs
const groupIntoVolume = mode === "volume" ? true : await promptPack();
// Post-auth/source loop: each iteration resolves a manga (search or reuse) and downloads.
outer: for (;;) {
// "New manga" entry point (also the first iteration): title + search.
if (hit === null) {
// Step 1 — title
const title = await promptTitle();

// Step 7b — volume name (chapter mode + groupIntoVolume only; volume mode uses bundle.num)
const volumeName =
mode === "chapter" && groupIntoVolume
? await promptVolumeName({ logger: opts.logger })
: null;
// Step 4 — search results (with CF retry)
hit = await withSessionRetry(
() =>
pickSearchResult({
query: title,
sourceLabel: source.label,
adapter,
}),
isCloudflareError,
doRefresh,
opts.logger,
"walkthrough.search_retry",
);
cache = { chapters: null, volumes: null };

// Step 8 — cover URL (only when packing)
const coverUrl = groupIntoVolume ? await promptCoverUrl({ logger: opts.logger }) : null;

const result: WalkthroughResult = {
title,
source,
hit,
mode,
selectedBundles,
groupIntoVolume,
volumeName,
coverUrl,
};
lastResult = await runDownloadFlow({
title,
hit,
cache,
adapter,
source,
outDir,
logger: opts.logger,
doRefresh,
executeDeps: opts.executeDeps,
progressEnabled: opts.progressEnabled ?? false,
});
} else {
// "Same manga" entry point: reuse hit + cached listings, re-enter at pickMode.
if (cache === null) cache = { chapters: null, volumes: null };
lastResult = await runDownloadFlow({
title: lastResult?.title ?? "",
hit,
cache,
adapter,
source,
outDir,
logger: opts.logger,
doRefresh,
executeDeps: opts.executeDeps,
progressEnabled: opts.progressEnabled ?? false,
});
}

// Step 9 — execute (fetchChapterInput calls are wrapped inside executeWalkthrough)
const progress = createProgress({
enabled: opts.progressEnabled ?? false,
totalChapters: selectedBundles.length,
});
await executeWalkthrough(
{
source,
hit,
mode,
selectedBundles,
groupIntoVolume,
volumeName,
coverUrl,
outDir,
adapter,
logger: opts.logger,
refreshFn: doRefresh,
progress,
},
opts.executeDeps,
);
// Post-download: what next?
const next = await promptNextAction();
switch (next) {
case "same-manga":
continue outer;
case "new-manga":
hit = null;
cache = null;
continue outer;
case "quit":
break outer;
}
}

return result;
if (!lastResult) {
throw new WalkthroughError("Walkthrough ended without a completed download.");
}
return lastResult;
} catch (err) {
// @inquirer/prompts throws ExitPromptError when the user presses Ctrl+C
if (err instanceof Error && err.name === "ExitPromptError") {
Expand All @@ -211,3 +221,123 @@ export async function runWalkthrough(
throw err;
}
}

interface DownloadFlowOptions {
title: string;
hit: SearchHit;
cache: ChapterListingCache;
adapter: SourceAdapter;
source: SourceDescriptor;
outDir: string;
logger: Logger;
doRefresh: () => Promise<void>;
executeDeps?: ExecuteDeps;
progressEnabled: boolean;
}

/**
* Runs steps 5-9 (mode → range → pack prompts → execute) for an already-resolved
* manga (hit). Reuses cached chapter/volume listings when present so "same manga"
* iterations never re-call adapter.search or adapter.listChapters/listVolumes.
*/
async function runDownloadFlow(flowOpts: DownloadFlowOptions): Promise<WalkthroughResult> {
const {
title,
hit,
cache,
adapter,
source,
outDir,
logger,
doRefresh,
executeDeps,
progressEnabled,
} = flowOpts;

// Step 5 — mode
const mode = await pickMode();

// Step 6 — range (with CF retry). Reuse cached listing for this hit when available.
const rangeResult = await withSessionRetry(
() =>
pickRange({
hit,
mode,
adapter,
preloadedChapters: mode === "chapter" ? (cache.chapters ?? undefined) : undefined,
preloadedVolumes: mode === "volume" ? (cache.volumes ?? undefined) : undefined,
}),
isCloudflareError,
doRefresh,
logger,
"walkthrough.range_retry",
);
const selectedBundles = rangeResult.bundles;

// Cache the listing actually used (fetched or preloaded) for subsequent "same manga" iterations.
if (rangeResult.chapters) cache.chapters = rangeResult.chapters;
if (rangeResult.volumes) cache.volumes = rangeResult.volumes;

// Step 7 — pack prompt (chapter mode only)
// volume mode always packs
const groupIntoVolume = mode === "volume" ? true : await promptPack();

// Step 7b — volume name (chapter mode + groupIntoVolume only; volume mode uses bundle.num)
const volumeName =
mode === "chapter" && groupIntoVolume ? await promptVolumeName({ logger }) : null;

// Step 8 — cover URL (only when packing)
const coverUrl = groupIntoVolume ? await promptCoverUrl({ logger }) : null;

const result: WalkthroughResult = {
title,
source,
hit,
mode,
selectedBundles,
groupIntoVolume,
volumeName,
coverUrl,
};

// Step 9 — execute (fetchChapterInput calls are wrapped inside executeWalkthrough).
// A fresh progress handle is created per download flow iteration so the bar always
// reflects this iteration's own bundle count, then finished before returning.
const progress = createProgress({
enabled: progressEnabled,
totalChapters: selectedBundles.length,
});
const { failed } = await executeWalkthrough(
{
source,
hit,
mode,
selectedBundles,
groupIntoVolume,
volumeName,
coverUrl,
outDir,
adapter,
logger,
refreshFn: doRefresh,
progress,
},
executeDeps,
);

// Partial failure is resilient: still return to the next-action prompt, but
// surface a one-line summary so the user isn't left guessing.
if (failed > 0) {
logger.warn(
{
event: "walkthrough.download_summary_failed",
context: "walkthrough",
failed,
total: selectedBundles.length,
},
`${failed} chapter(s) failed to download`,
);
}

return result;
}
42 changes: 42 additions & 0 deletions src/walkthrough/steps/next-action-prompt.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { describe, expect, test } from "bun:test";

describe("promptNextAction", () => {
test("returns 'same-manga' when selected", async () => {
const { mock } = await import("bun:test");
mock.module("../prompts.ts", () => ({
select: async () => "same-manga",
input: async () => "",
checkbox: async () => [],
confirm: async () => false,
editor: async () => "",
}));
const { promptNextAction } = await import("./next-action-prompt.ts");
expect(await promptNextAction()).toBe("same-manga");
});

test("returns 'new-manga' when selected", async () => {
const { mock } = await import("bun:test");
mock.module("../prompts.ts", () => ({
select: async () => "new-manga",
input: async () => "",
checkbox: async () => [],
confirm: async () => false,
editor: async () => "",
}));
const { promptNextAction } = await import("./next-action-prompt.ts");
expect(await promptNextAction()).toBe("new-manga");
});

test("returns 'quit' when selected", async () => {
const { mock } = await import("bun:test");
mock.module("../prompts.ts", () => ({
select: async () => "quit",
input: async () => "",
checkbox: async () => [],
confirm: async () => false,
editor: async () => "",
}));
const { promptNextAction } = await import("./next-action-prompt.ts");
expect(await promptNextAction()).toBe("quit");
});
});
16 changes: 16 additions & 0 deletions src/walkthrough/steps/next-action-prompt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { select } from "../prompts.ts";

export type NextAction = "same-manga" | "new-manga" | "quit";

/** Post-download step: offer to keep going with the same manga, search a new one, or quit. */
export async function promptNextAction(): Promise<NextAction> {
const result = await select<NextAction>({
message: "Done. What next?",
choices: [
{ name: "Same manga — pick another volume/range", value: "same-manga" },
{ name: "New manga — search again", value: "new-manga" },
{ name: "Quit", value: "quit" },
],
});
return result;
}
Loading