diff --git a/scripts/archive-topics.ts b/scripts/archive-topics.ts new file mode 100644 index 0000000..2ebd351 --- /dev/null +++ b/scripts/archive-topics.ts @@ -0,0 +1,144 @@ +import { mkdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import process from "node:process"; + +import { chromium, type APIRequestContext } from "@playwright/test"; + +/** + * 주제를 보관 상태로 내린다. + * + *

지우지 않는다. `status` 를 `ARCHIVED` 로 바꾸면 공개 목록에서 빠지고 되돌릴 수 있다 — + * 잘못 내린 것을 다시 올릴 방법이 없으면 이 작업 자체가 위험해진다. + * + *

기록이 붙어 있는 주제는 건드리지 않는다. 내려도 되는 것은 아직 아무 기록도 가리키지 않는 + * 주제뿐이고, 그 판단을 손으로 적어 둔 목록에 맡기지 않고 서버에 물어 확인한다. + * + * 사용법: + * node scripts/archive-topics.ts --login + * node scripts/archive-topics.ts [slug...] + * node scripts/archive-topics.ts --dry-run [slug...] + */ + +const BASE = "https://hyeonworks.com"; +const SESSION_FILE = "artifacts/design-review/studio-session.json"; + +type TopicEdit = Readonly> & { + id?: string; + slug?: string; + name?: string; + version?: number; + status?: string; +}; + +async function login(): Promise { + const browser = await chromium.launch({ headless: false }); + const context = await browser.newContext({ viewport: { width: 1440, height: 900 } }); + const page = await context.newPage(); + await page.goto(`${BASE}/studio`); + process.stdout.write("열린 창에서 로그인하세요. Studio 화면이 뜨면 자동으로 저장합니다...\n"); + try { + await page.waitForSelector('a[href="/studio/documents"]', { timeout: 300_000 }); + await mkdir(path.dirname(SESSION_FILE), { recursive: true }); + await context.storageState({ path: SESSION_FILE }); + process.stdout.write(`세션 저장: ${SESSION_FILE}\n`); + } finally { + await browser.close(); + } +} + +async function json(request: APIRequestContext, url: string): Promise { + const response = await request.get(url, { headers: { Accept: "application/json" } }); + if (!response.ok()) throw new Error(`${url} → ${response.status()}`); + return (await response.json()) as unknown; +} + +function envelopeData(value: unknown): unknown { + return typeof value === "object" && value !== null && "data" in value + ? (value as { data: unknown }).data + : value; +} + +async function main(): Promise { + if (process.argv.includes("--login")) { + await login(); + return; + } + + const dryRun = process.argv.includes("--dry-run"); + const slugs = process.argv.slice(2).filter((entry) => !entry.startsWith("--")); + if (slugs.length === 0) { + process.stderr.write("내릴 주제의 slug 를 적어 주세요.\n"); + process.exitCode = 1; + return; + } + + await readFile(SESSION_FILE, "utf8").catch(() => { + throw new Error(`세션이 없습니다(${SESSION_FILE}). --login 으로 먼저 로그인하세요.`); + }); + + const browser = await chromium.launch(); + try { + const context = await browser.newContext({ storageState: SESSION_FILE }); + const request = context.request; + + /* + 쓰기에는 CSRF 토큰이 필요하다. 세션 조회가 토큰과 그것을 실을 헤더 이름을 함께 준다 — + 헤더 이름을 손으로 적어 두면 서버가 그 이름을 바꾸는 날 403 만 보고 이유를 알 수 없다. + */ + const session = envelopeData(await json(request, `${BASE}/api/v1/studio/session`)) as { + csrfToken: string; + csrfHeaderName: string; + }; + + const topics = envelopeData(await json(request, `${BASE}/api/v1/studio/topics`)) as TopicEdit[]; + const publicTopics = envelopeData( + await json(request, `${BASE}/api/v1/public/topics`), + ) as { items: ReadonlyArray<{ slug: string; recordCount: number }> }; + const recordCounts = new Map( + publicTopics.items.map((topic) => [topic.slug, topic.recordCount]), + ); + + for (const slug of slugs) { + const topic = topics.find((candidate) => candidate.slug === slug); + if (!topic?.id) { + process.stdout.write(` ✗ ${slug} — 그런 주제가 없습니다\n`); + continue; + } + const count = recordCounts.get(slug) ?? 0; + if (count > 0) { + process.stdout.write(` ✗ ${slug} — 기록 ${count}개가 붙어 있어 내리지 않습니다\n`); + continue; + } + if (topic.status === "ARCHIVED") { + process.stdout.write(` · ${slug} — 이미 보관 상태입니다\n`); + continue; + } + if (dryRun) { + process.stdout.write(` (예행) ${slug} — ${topic.name} 을 보관으로 내립니다\n`); + continue; + } + + /* + 계약이 요구하는 필드(name/slug)를 그대로 돌려보내고 status 와 expectedVersion 만 얹는다. + 빠뜨리면 서버가 그 값을 비운 것으로 읽는다. + */ + const response = await request.put(`${BASE}/api/v1/studio/topics/${topic.id}`, { + headers: { + "Content-Type": "application/json", + Accept: "application/json", + [session.csrfHeaderName]: session.csrfToken, + }, + data: { ...topic, status: "ARCHIVED", expectedVersion: topic.version }, + }); + if (!response.ok()) { + process.stdout.write(` ✗ ${slug} — ${response.status()} ${await response.text()}\n`); + continue; + } + process.stdout.write(` ✓ ${slug} — ${topic.name} 을 보관으로 내렸습니다\n`); + } + } finally { + await browser.close(); + } +} + +await main();