@aronnaxlin/bgm-cli 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/LICENSE +660 -0
  2. package/README.en.md +122 -0
  3. package/README.md +127 -0
  4. package/README.zh-TW.md +122 -0
  5. package/package.json +41 -0
  6. package/src/cli.js +993 -0
  7. package/src/commands/blog.js +213 -0
  8. package/src/commands/calendar.js +32 -0
  9. package/src/commands/character.js +291 -0
  10. package/src/commands/collection.js +418 -0
  11. package/src/commands/episode.js +379 -0
  12. package/src/commands/group.js +488 -0
  13. package/src/commands/index.js +362 -0
  14. package/src/commands/notify.js +74 -0
  15. package/src/commands/person.js +297 -0
  16. package/src/commands/status.js +74 -0
  17. package/src/commands/subject.js +537 -0
  18. package/src/commands/timeline.js +288 -0
  19. package/src/commands/trending.js +58 -0
  20. package/src/commands/tui.js +1537 -0
  21. package/src/commands/user.js +83 -0
  22. package/src/core/client.js +2065 -0
  23. package/src/core/config.js +450 -0
  24. package/src/core/http.js +144 -0
  25. package/src/core/output.js +3888 -0
  26. package/src/core/proxy.js +47 -0
  27. package/src/core/reactions.js +62 -0
  28. package/src/core/turnstile.js +526 -0
  29. package/src/data/bangumi-emotes.json +311 -0
  30. package/src/utils/args.js +113 -0
  31. package/src/utils/auth-flow.js +373 -0
  32. package/src/utils/auth.js +90 -0
  33. package/src/utils/calendar.js +23 -0
  34. package/src/utils/collection-ops.js +333 -0
  35. package/src/utils/collection.js +240 -0
  36. package/src/utils/formatters.js +157 -0
  37. package/src/utils/helpers.js +283 -0
  38. package/src/utils/hot.js +182 -0
  39. package/src/utils/install.js +40 -0
  40. package/src/utils/prompts.js +87 -0
  41. package/src/utils/relay.js +74 -0
  42. package/src/utils/status.js +68 -0
  43. package/src/utils/tui-interactive.js +197 -0
  44. package/src/utils/tui-render.js +86 -0
  45. package/src/utils/turnstile-flow.js +154 -0
  46. package/src/utils/validators.js +412 -0
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Interactive prompt utilities.
3
+ */
4
+
5
+ import readline from "node:readline";
6
+ import { Writable } from "node:stream";
7
+ import { CommandError } from "../core/output.js";
8
+
9
+ export async function askRequired(rl, label, defaultValue) {
10
+ const value = await askOptional(rl, label, defaultValue);
11
+ if (!value) {
12
+ throw new CommandError(`Missing required value: ${label}`);
13
+ }
14
+ return value;
15
+ }
16
+
17
+ export async function askOptional(rl, label, defaultValue) {
18
+ const suffix = defaultValue ? ` [${defaultValue}]` : "";
19
+ const answer = await rl.question(`${label}${suffix}: `);
20
+ const value = answer.trim();
21
+ if (value) {
22
+ return value;
23
+ }
24
+ return defaultValue ?? "";
25
+ }
26
+
27
+ export async function askHiddenRequired(label, defaultValue) {
28
+ const value = await askHiddenOptional(label, defaultValue);
29
+ if (!value) {
30
+ throw new CommandError(`Missing required value: ${label}`);
31
+ }
32
+ return value;
33
+ }
34
+
35
+ export async function askHiddenOptional(label, defaultValue) {
36
+ const suffix = defaultValue ? ` [${defaultValue}]` : "";
37
+ const mutedOutput = new Writable({
38
+ write(chunk, encoding, callback) {
39
+ if (!mutedOutput.muted) {
40
+ process.stdout.write(chunk, encoding);
41
+ }
42
+ callback();
43
+ },
44
+ });
45
+ mutedOutput.muted = false;
46
+
47
+ const rl = readline.createInterface({
48
+ input: process.stdin,
49
+ output: mutedOutput,
50
+ terminal: true,
51
+ });
52
+
53
+ try {
54
+ const answer = await new Promise((resolve) => {
55
+ rl.question(`${label}${suffix}: `, resolve);
56
+ mutedOutput.muted = true;
57
+ });
58
+ process.stdout.write("\n");
59
+ const value = String(answer ?? "").trim();
60
+ if (value) {
61
+ return value;
62
+ }
63
+ return defaultValue ?? "";
64
+ } finally {
65
+ rl.close();
66
+ }
67
+ }
68
+
69
+ export async function askChoice(rl, label, choices, defaultKey) {
70
+ console.log(`${label}:`);
71
+ for (const choice of choices) {
72
+ console.log(` ${choice.key}. ${choice.label}`);
73
+ }
74
+
75
+ const answer = await askOptional(rl, "Choose", defaultKey);
76
+ const normalized = String(answer).trim() || defaultKey;
77
+ const matched = choices.find(
78
+ (choice) =>
79
+ choice.key === normalized || choice.value === normalized.toLowerCase(),
80
+ );
81
+
82
+ if (!matched) {
83
+ throw new CommandError(`Invalid option: ${answer}`);
84
+ }
85
+
86
+ return matched.value;
87
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Hosted OAuth/Turnstile relay callback utilities.
3
+ */
4
+
5
+ import { CommandError } from "../core/output.js";
6
+ import { DEFAULT_TURNSTILE_TIMEOUT_MS } from "../core/turnstile.js";
7
+
8
+ export function computeHostedSessionTimeoutMs(expiresAt) {
9
+ if (!expiresAt) {
10
+ return DEFAULT_TURNSTILE_TIMEOUT_MS;
11
+ }
12
+
13
+ const parsed = new Date(expiresAt).getTime();
14
+ if (Number.isNaN(parsed)) {
15
+ return DEFAULT_TURNSTILE_TIMEOUT_MS;
16
+ }
17
+
18
+ return Math.max(parsed - Date.now(), 0);
19
+ }
20
+
21
+ export async function readHostedRelayJsonBody(req) {
22
+ const chunks = [];
23
+ let size = 0;
24
+
25
+ for await (const chunk of req) {
26
+ size += chunk.length;
27
+ if (size > 256 * 1024) {
28
+ throw new CommandError("Hosted relay callback body is too large.");
29
+ }
30
+ chunks.push(chunk);
31
+ }
32
+
33
+ const raw = Buffer.concat(chunks).toString("utf8");
34
+ if (!raw) {
35
+ return {};
36
+ }
37
+
38
+ try {
39
+ return JSON.parse(raw);
40
+ } catch {
41
+ throw new CommandError("Hosted relay callback payload is not valid JSON.");
42
+ }
43
+ }
44
+
45
+ export function respondHostedRelayPreflight(req, res) {
46
+ res.writeHead(204, buildHostedRelayCorsHeaders(req));
47
+ res.end();
48
+ }
49
+
50
+ export function respondHostedRelayJson(req, res, statusCode, payload) {
51
+ res.writeHead(statusCode, {
52
+ "Content-Type": "application/json; charset=utf-8",
53
+ ...buildHostedRelayCorsHeaders(req),
54
+ });
55
+ res.end(JSON.stringify(payload));
56
+ }
57
+
58
+ export function buildHostedRelayCorsHeaders(req) {
59
+ const requestOrigin = typeof req.headers.origin === "string" ? req.headers.origin : "*";
60
+ return {
61
+ "Access-Control-Allow-Origin": requestOrigin,
62
+ "Access-Control-Allow-Methods": "POST, OPTIONS",
63
+ "Access-Control-Allow-Headers": "Content-Type",
64
+ "Access-Control-Allow-Private-Network": "true",
65
+ Vary: "Origin",
66
+ };
67
+ }
68
+
69
+ export function respondHtml(res, statusCode, statusMessage, body) {
70
+ res.writeHead(statusCode, statusMessage, {
71
+ "Content-Type": "text/html; charset=utf-8",
72
+ });
73
+ res.end(`<!doctype html><html><body>${body}</body></html>`);
74
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Status page payload builders.
3
+ */
4
+
5
+ import { normalizeStatusAudience } from "./validators.js";
6
+
7
+ export function buildStatusCurrentPayload(current, { site, audience }) {
8
+ const components = Array.isArray(current.components)
9
+ ? current.components.filter((component) => {
10
+ if (site && String(component.domain).toLowerCase() !== site) {
11
+ return false;
12
+ }
13
+ if (audience && normalizeStatusAudience(component.kind) !== audience) {
14
+ return false;
15
+ }
16
+ return true;
17
+ })
18
+ : [];
19
+ const affectedComponents = components.filter((component) => component.status && component.status !== "ok");
20
+ const unresolvedIncidents = affectedComponents.flatMap((component) => {
21
+ const incidents = Array.isArray(component.incidents) ? component.incidents : [];
22
+ return incidents
23
+ .filter((incident) => incident && !incident.end_ts)
24
+ .map((incident) => ({
25
+ label: component.label ?? `${component.domain} · ${component.kind}`,
26
+ domain: component.domain,
27
+ kind: component.kind,
28
+ status: incident.status,
29
+ startTs: incident.start_ts,
30
+ }));
31
+ });
32
+
33
+ return {
34
+ resource: "status-current",
35
+ source: "https://bgm-status.ry.mk/api/status",
36
+ updatedAt: current.updated_at,
37
+ upstreamStatus: current.status,
38
+ upstreamMessage: current.message,
39
+ monitored: components.length,
40
+ affected: affectedComponents.length,
41
+ status: summarizeCurrentStatus(components),
42
+ filters: {
43
+ site,
44
+ audience,
45
+ },
46
+ affectedComponents: affectedComponents.map((component) => ({
47
+ label: component.label ?? `${component.domain} · ${component.kind}`,
48
+ domain: component.domain,
49
+ kind: component.kind,
50
+ status: component.status,
51
+ lastCheck: component.last_check,
52
+ })),
53
+ unresolvedIncidents,
54
+ };
55
+ }
56
+
57
+ export function summarizeCurrentStatus(components) {
58
+ let worst = "ok";
59
+ for (const component of components) {
60
+ if (component?.status === "down") {
61
+ return "down";
62
+ }
63
+ if (component?.status === "degraded") {
64
+ worst = "degraded";
65
+ }
66
+ }
67
+ return worst;
68
+ }
@@ -0,0 +1,197 @@
1
+ /**
2
+ * TUI interactive primitives (menus, prompts, wait-for-continue).
3
+ */
4
+
5
+ import process from "node:process";
6
+ import { emitKeypressEvents } from "node:readline";
7
+ import { CommandError } from "../core/output.js";
8
+ import { askOptional, askRequired } from "./prompts.js";
9
+ import {
10
+ drawDivider,
11
+ drawSectionTitle,
12
+ inverse,
13
+ renderTuiHeader,
14
+ renderTuiInputScreen,
15
+ } from "./tui-render.js";
16
+
17
+ export async function askMenuChoice(label, choices, defaultValue, extras = {}) {
18
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
19
+ const fallbackChoice = choices.find(
20
+ (choice) => choice.value === defaultValue || choice.key === defaultValue,
21
+ ) ?? choices[0];
22
+ return fallbackChoice?.value;
23
+ }
24
+
25
+ emitKeypressEvents(process.stdin);
26
+ const options = choices.map((choice) => ({
27
+ ...choice,
28
+ selected: choice.value === defaultValue || choice.key === defaultValue,
29
+ }));
30
+ const directKeys = options
31
+ .map((choice) => choice.key)
32
+ .filter((choiceKey) => choiceKey !== undefined && choiceKey !== null && choiceKey !== "");
33
+ let index = Math.max(0, options.findIndex((choice) => choice.selected));
34
+ if (index === -1) {
35
+ index = 0;
36
+ }
37
+ let keyBuffer = "";
38
+
39
+ return new Promise((resolve, reject) => {
40
+ const wasRaw = Boolean(process.stdin.isRaw);
41
+ const quitValue = extras.quitValue ?? "back";
42
+ const quitLabel = extras.quitLabel ?? (quitValue === "exit" ? "exit" : "back");
43
+
44
+ const cleanup = () => {
45
+ process.stdin.off("keypress", onKeypress);
46
+ if (!wasRaw && process.stdin.isTTY) {
47
+ process.stdin.setRawMode(false);
48
+ }
49
+ };
50
+
51
+ const render = () => {
52
+ renderTuiHeader();
53
+ console.log(drawSectionTitle(label));
54
+ console.log(drawDivider());
55
+ if (extras.summary) {
56
+ console.log(extras.summary);
57
+ console.log(drawDivider());
58
+ }
59
+ for (let i = 0; i < options.length; i += 1) {
60
+ const prefix = i === index ? "›" : " ";
61
+ const line = `${prefix} ${options[i].label}`;
62
+ console.log(i === index ? inverse(line) : line);
63
+ }
64
+ console.log("");
65
+ console.log(drawDivider());
66
+ const keyHint = keyBuffer ? ` typed: ${keyBuffer}` : "";
67
+ console.log(`↑/↓ move digits jump Enter confirm q ${quitLabel}${keyHint}`);
68
+ };
69
+
70
+ const onKeypress = (_str, key = {}) => {
71
+ if (key.name === "up" || key.name === "k") {
72
+ keyBuffer = "";
73
+ index = index > 0 ? index - 1 : options.length - 1;
74
+ render();
75
+ return;
76
+ }
77
+ if (key.name === "down" || key.name === "j") {
78
+ keyBuffer = "";
79
+ index = index < options.length - 1 ? index + 1 : 0;
80
+ render();
81
+ return;
82
+ }
83
+ if (key.name === "return" || key.name === "enter") {
84
+ cleanup();
85
+ if (keyBuffer) {
86
+ const exactMatch = options.find((choice) => choice.key === keyBuffer);
87
+ if (exactMatch) {
88
+ resolve(exactMatch.value);
89
+ return;
90
+ }
91
+ }
92
+ resolve(options[index].value);
93
+ return;
94
+ }
95
+ if (key.name === "q" || key.name === "escape") {
96
+ keyBuffer = "";
97
+ cleanup();
98
+ resolve(quitValue);
99
+ return;
100
+ }
101
+ if (key.name === "backspace" || key.name === "delete") {
102
+ keyBuffer = keyBuffer.slice(0, -1);
103
+ render();
104
+ return;
105
+ }
106
+ if (key.ctrl && key.name === "c") {
107
+ cleanup();
108
+ reject(new CommandError("TUI cancelled."));
109
+ return;
110
+ }
111
+
112
+ const raw = typeof _str === "string" ? _str : "";
113
+ if (/^[0-9]$/.test(raw)) {
114
+ const nextBuffer = `${keyBuffer}${raw}`;
115
+ const exactMatch = options.find((choice) => choice.key === nextBuffer);
116
+ const prefixMatches = directKeys.filter((choiceKey) => String(choiceKey).startsWith(nextBuffer));
117
+
118
+ if (prefixMatches.length > 0) {
119
+ keyBuffer = nextBuffer;
120
+ if (exactMatch) {
121
+ index = options.findIndex((choice) => choice.key === nextBuffer);
122
+ if (prefixMatches.length === 1) {
123
+ cleanup();
124
+ resolve(exactMatch.value);
125
+ return;
126
+ }
127
+ }
128
+ render();
129
+ return;
130
+ }
131
+
132
+ const singleDigitMatch = options.find((choice) => choice.key === raw);
133
+ if (singleDigitMatch) {
134
+ keyBuffer = raw;
135
+ index = options.findIndex((choice) => choice.key === raw);
136
+ render();
137
+ }
138
+ }
139
+ };
140
+
141
+ if (!wasRaw && process.stdin.isTTY) {
142
+ process.stdin.setRawMode(true);
143
+ }
144
+ process.stdin.on("keypress", onKeypress);
145
+ render();
146
+ });
147
+ }
148
+
149
+ export async function waitForTuiContinue() {
150
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
151
+ return;
152
+ }
153
+
154
+ console.log("");
155
+ console.log(drawDivider());
156
+ console.log("Press Enter to continue.");
157
+
158
+ emitKeypressEvents(process.stdin);
159
+
160
+ await new Promise((resolve, reject) => {
161
+ const wasRaw = Boolean(process.stdin.isRaw);
162
+
163
+ const cleanup = () => {
164
+ process.stdin.off("keypress", onKeypress);
165
+ if (!wasRaw && process.stdin.isTTY) {
166
+ process.stdin.setRawMode(false);
167
+ }
168
+ };
169
+
170
+ const onKeypress = (_str, key = {}) => {
171
+ if (key.name === "return" || key.name === "enter" || key.name === "space") {
172
+ cleanup();
173
+ resolve();
174
+ return;
175
+ }
176
+ if (key.ctrl && key.name === "c") {
177
+ cleanup();
178
+ reject(new CommandError("TUI cancelled."));
179
+ }
180
+ };
181
+
182
+ if (!wasRaw && process.stdin.isTTY) {
183
+ process.stdin.setRawMode(true);
184
+ }
185
+ process.stdin.on("keypress", onKeypress);
186
+ });
187
+ }
188
+
189
+ export async function askTuiOptional(rl, label, defaultValue = "", description = "") {
190
+ renderTuiInputScreen(label, defaultValue, description);
191
+ return askOptional(rl, label, defaultValue);
192
+ }
193
+
194
+ export async function askTuiRequired(rl, label, defaultValue = "", description = "") {
195
+ renderTuiInputScreen(label, defaultValue, description);
196
+ return askRequired(rl, label, defaultValue);
197
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * TUI rendering utilities.
3
+ */
4
+
5
+ import path from "node:path";
6
+ import { getConfigFilePath } from "../core/config.js";
7
+
8
+ export function renderTuiHeader() {
9
+ clearScreen();
10
+ const width = 72;
11
+ console.log(drawBoxLine("top", width));
12
+ console.log(drawBoxText("bgm-cli TUI", width));
13
+ console.log(drawBoxLine("mid", width));
14
+ console.log(drawBoxText(`Config: ${path.basename(getConfigFilePath())}`, width));
15
+ console.log(drawBoxText("Hints: see footer", width));
16
+ console.log(drawBoxLine("bottom", width));
17
+ console.log("");
18
+ }
19
+
20
+ export function renderTuiInputScreen(label, defaultValue, description) {
21
+ renderTuiHeader();
22
+ console.log(drawSectionTitle(label));
23
+ console.log(drawDivider());
24
+ if (description) {
25
+ console.log(description);
26
+ console.log("");
27
+ }
28
+ if (defaultValue !== undefined && defaultValue !== null && defaultValue !== "") {
29
+ console.log(`Press Enter to use the default value: ${defaultValue}`);
30
+ } else {
31
+ console.log("Type a value and press Enter.");
32
+ }
33
+ console.log("");
34
+ }
35
+
36
+ export function isTuiBackAction(value) {
37
+ return value === "back" || value === "exit";
38
+ }
39
+
40
+ export function clearScreen() {
41
+ process.stdout.write("\x1Bc");
42
+ }
43
+
44
+ export function inverse(value) {
45
+ return `\x1b[7m${value}\x1b[0m`;
46
+ }
47
+
48
+ export function drawDivider(width = 72) {
49
+ return "─".repeat(width);
50
+ }
51
+
52
+ export function drawSectionTitle(title) {
53
+ return `[ ${title} ]`;
54
+ }
55
+
56
+ export function drawBoxLine(position, width) {
57
+ const inner = "─".repeat(Math.max(0, width - 2));
58
+ switch (position) {
59
+ case "top":
60
+ return `┌${inner}┐`;
61
+ case "mid":
62
+ return `├${inner}┤`;
63
+ case "bottom":
64
+ return `└${inner}┘`;
65
+ default:
66
+ return `│${inner}│`;
67
+ }
68
+ }
69
+
70
+ export function drawBoxText(text, width) {
71
+ const innerWidth = Math.max(0, width - 2);
72
+ const value = String(text);
73
+ const clipped = value.length > innerWidth ? `${value.slice(0, innerWidth - 3)}...` : value;
74
+ return `│${clipped.padEnd(innerWidth, " ")}│`;
75
+ }
76
+
77
+ export function renderTuiResultScreen(title, content, summary = "") {
78
+ renderTuiHeader();
79
+ console.log(drawSectionTitle(title));
80
+ console.log(drawDivider());
81
+ if (summary) {
82
+ console.log(summary);
83
+ console.log(drawDivider());
84
+ }
85
+ console.log(content);
86
+ }
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Turnstile token acquisition flow utilities.
3
+ */
4
+
5
+ import { OAuthBackendClient } from "../core/client.js";
6
+ import { BangumiApiError as ApiError } from "../core/http.js";
7
+ import { getConfig } from "../core/config.js";
8
+ import { DEFAULT_TURNSTILE_TIMEOUT_MS, startTurnstileFlow } from "../core/turnstile.js";
9
+ import {
10
+ normalizeTurnstileTimeoutMs,
11
+ previewToken,
12
+ toBoolean,
13
+ tryOpenExternalUrl,
14
+ writeProgress,
15
+ } from "./helpers.js";
16
+ import { CommandError } from "../core/output.js";
17
+ import process from "node:process";
18
+ import { startHostedRelayReceiver } from "./auth-flow.js";
19
+
20
+ export function shouldUseHostedTurnstileBackend(options, config) {
21
+ if (!config?.oauthServerBaseUrl) {
22
+ return false;
23
+ }
24
+
25
+ if (toBoolean(options.manual, false)) {
26
+ return false;
27
+ }
28
+
29
+ if (toBoolean(options.localHelper, false)) {
30
+ return false;
31
+ }
32
+
33
+ if (options.listenHost !== undefined || options.port !== undefined || options.publicOrigin !== undefined) {
34
+ return false;
35
+ }
36
+
37
+ return true;
38
+ }
39
+
40
+ export function shouldFallbackFromHostedTurnstile(error) {
41
+ if (!(error instanceof ApiError)) {
42
+ return false;
43
+ }
44
+
45
+ return error.status === 404 || error.status === 405 || error.status === 501 || error.status >= 500;
46
+ }
47
+
48
+ export async function acquireTurnstileToken(options, context = {}, meta = {}) {
49
+ if (shouldUseHostedTurnstileBackend(options, getConfig())) {
50
+ try {
51
+ return await acquireHostedTurnstileToken(context, meta);
52
+ } catch (error) {
53
+ if (shouldFallbackFromHostedTurnstile(error)) {
54
+ writeProgress(context, "The hosted official Turnstile flow is unavailable right now. bgm-cli will fall back to the local helper flow.");
55
+ } else {
56
+ throw error;
57
+ }
58
+ }
59
+ }
60
+
61
+ const timeoutMs = normalizeTurnstileTimeoutMs(options.timeoutSeconds);
62
+ const flow = await startTurnstileFlow({
63
+ listenHost: options.listenHost,
64
+ port: options.port,
65
+ publicOrigin: options.publicOrigin,
66
+ timeoutMs,
67
+ actionLabel: meta.actionLabel,
68
+ });
69
+
70
+ const manualOnly = toBoolean(options.manual, false);
71
+ let openedBrowser = false;
72
+
73
+ writeProgress(context, `${meta.actionLabel ? `Turnstile verification is required to ${meta.actionLabel}.` : "Turnstile verification is required."}`);
74
+ writeProgress(context, "Mode: local fallback helper");
75
+ writeProgress(context, `Helper page: ${flow.verificationUrl}`);
76
+ writeProgress(context, `Listening on: ${flow.listenHost}:${flow.port}`);
77
+ writeProgress(context, "The token is short-lived and is intended for the next write operation only.");
78
+ writeProgress(context, "The helper page shows a copyable browser script, a next.bgm.tv shortcut, and a manual paste box.");
79
+ writeProgress(context, "If the page does not open automatically, open the helper URL yourself in a browser.");
80
+ writeProgress(context, "bgm-cli is now waiting for the helper page to send a token back.");
81
+ writeProgress(context, "For remote or VPS usage, rerun with `--manual --port 8765` and open the helper page through an SSH tunnel, or provide `--public-origin`.");
82
+
83
+ if (!manualOnly) {
84
+ openedBrowser = tryOpenExternalUrl(flow.verificationUrl);
85
+ writeProgress(context, openedBrowser ? "Browser opened." : "Automatic browser launch failed or is unavailable.");
86
+ }
87
+
88
+ const result = await flow.completion;
89
+ writeProgress(context, "Turnstile verification completed.");
90
+
91
+ return {
92
+ ...result,
93
+ openedBrowser,
94
+ timeoutMs,
95
+ };
96
+ }
97
+
98
+ export async function acquireHostedTurnstileToken(context = {}, meta = {}) {
99
+ const config = getConfig();
100
+ const backend = new OAuthBackendClient(config);
101
+ const relay = await startHostedRelayReceiver({
102
+ kind: "turnstile",
103
+ timeoutMs: DEFAULT_TURNSTILE_TIMEOUT_MS,
104
+ });
105
+ const session = await backend.createTurnstileSession({
106
+ relayUrl: relay.callbackUrl,
107
+ });
108
+ const authorizeUrl = session.authorize_url;
109
+ let openedBrowser = false;
110
+
111
+ writeProgress(context, `${meta.actionLabel ? `Turnstile verification is required to ${meta.actionLabel}.` : "Turnstile verification is required."}`);
112
+ writeProgress(context, "Mode: hosted official Bangumi Turnstile");
113
+ writeProgress(context, `Turnstile backend: ${config.oauthServerBaseUrl}`);
114
+ writeProgress(context, `Open this official URL in your browser: ${authorizeUrl}`);
115
+ writeProgress(context, "Bangumi will show the official Turnstile verification page, then redirect back to the hosted callback.");
116
+ writeProgress(context, "The token is short-lived and is intended for the next write operation only.");
117
+ writeProgress(context, "After verification succeeds, the hosted callback page will try to send the token back to this terminal automatically.");
118
+
119
+ openedBrowser = tryOpenExternalUrl(authorizeUrl);
120
+ writeProgress(context, openedBrowser ? "Browser opened." : "Automatic browser launch failed or is unavailable.");
121
+
122
+ const result = await relay.completion;
123
+ writeProgress(context, "Turnstile verification completed.");
124
+
125
+ return {
126
+ token: result.turnstileToken,
127
+ tokenPreview: previewToken(result.turnstileToken),
128
+ authorizeUrl,
129
+ redirectUri: session.redirect_uri,
130
+ openedBrowser,
131
+ timeoutMs: relay.timeoutMs,
132
+ backendBaseUrl: config.oauthServerBaseUrl,
133
+ };
134
+ }
135
+
136
+ export async function resolveTurnstileTokenForMutation(options, { actionLabel, context }) {
137
+ const explicitToken = typeof options.turnstileToken === "string" ? options.turnstileToken.trim() : "";
138
+ if (explicitToken) {
139
+ return explicitToken;
140
+ }
141
+
142
+ if (!process.stdin.isTTY && !process.stdout.isTTY) {
143
+ throw new CommandError(`Turnstile verification is required to ${actionLabel}. Run this command in a terminal so bgm-cli can open the official verification page or the local fallback helper, or pass --turnstile-token explicitly.`);
144
+ }
145
+
146
+ if (toBoolean(options.manual, false)) {
147
+ writeProgress(context, `No --turnstile-token provided. Because you passed --manual, bgm-cli will skip the hosted official flow and use the local helper fallback to ${actionLabel}.`);
148
+ } else if (!toBoolean(options.interactive, false)) {
149
+ writeProgress(context, `No --turnstile-token provided. bgm-cli will first try Bangumi's official hosted Turnstile flow to ${actionLabel}.`);
150
+ }
151
+
152
+ const result = await acquireTurnstileToken(options, context, { actionLabel });
153
+ return result.token;
154
+ }