import test from "node:test"; import assert from "node:assert/strict"; import { mkdir, mkdtemp, readdir, rm, utimes, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; // Run with: // pnpm -C editor exec tsx --test "app/api/ops/x-run/route.test.ts" // // The X run's door: the body's shape, the refusals that come before any job, // a stale jar refusing a new run (its file kept, deferred, for a Resume), and // GET's console — the X posts channels in the default order and the jar's age. // Every case is answered from the disk alone: no job runs and nothing reaches X. const ROOT = await mkdtemp(path.join(os.tmpdir(), "x-run-route-")); process.env.WORKER_TOKEN = "test-token"; process.env.TRANSCRIPTS_DIR = ROOT; process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); await writeFile( process.env.SETTINGS_FILE, JSON.stringify({ social: { x: { cookieSource: "profile", maxCookieAgeMinutes: 60 } }, channelPriority: { focus: { kind: "none" }, channels: { "low-x": { tier: "low" }, "top-x": { tier: "normal", rank: 1 } } }, }), ); async function channel(slug: string, config: Record) { const dir = path.join(ROOT, "channels", slug); await mkdir(dir, { recursive: true }); await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", ...config })); } const x = (handle: string) => ({ sourceKind: "social", platform: "twitter", postFetcher: "x-gallery-dl", socialHandle: handle, url: `https://x.com/${handle}`, name: `${handle} (X)`, }); await channel("low-x", x("low")); await channel("mid-x", x("mid")); await channel("top-x", x("top")); await channel("bsky", { sourceKind: "social", platform: "bluesky", url: "https://bsky.app/profile/a.bsky.social" }); // A jar 16 days old. const jarDir = path.join(ROOT, ".x-session"); await mkdir(path.join(jarDir, "profile"), { recursive: true }); await writeFile(path.join(jarDir, "cookies.txt"), "# Netscape HTTP Cookie File\n.x.com\tTRUE\t/\tTRUE\t0\tauth_token\tfake\n"); const old = new Date(Date.now() - 16 * 24 * 60 * 60_000); await utimes(path.join(jarDir, "cookies.txt"), old, old); const { POST, GET } = await import("./route"); test.after(() => rm(ROOT, { recursive: true, force: true })); const AUTH = { authorization: "Bearer test-token" }; async function post(body: Record) { const res = await POST( new Request("http://localhost/api/ops/x-run", { method: "POST", headers: { ...AUTH, "content-type": "application/json" }, body: JSON.stringify(body), }), ); return { status: res.status, body: (await res.json()) as { ok: boolean; error?: string; run?: string } }; } async function get(q = "") { const res = await GET(new Request(`http://localhost/api/ops/x-run${q}`, { headers: AUTH })); return { status: res.status, body: (await res.json()) as Record & { error?: string } }; } test("the body: one of channels or resume; slugs checked; a limit over 200 refused", async () => { assert.match((await post({})).body.error!, /"channels" \(a new run\) or "resume" \(a run id\) is required/); assert.match((await post({ channels: ["top-x"], resume: "xr-x" })).body.error!, /one at a time/); assert.match((await post({ channels: ["../etc"] })).body.error!, /not a valid channel slug/); assert.match((await post({ channels: ["top-x"], extra: 1 })).body.error!, /unknown key\(s\): extra/); assert.equal((await post({ channels: ["bsky"] })).body.error, "bsky is not an X posts channel."); assert.match((await post({ channels: ["top-x"], limit: 500 })).body.error!, /from 1 to 200/); assert.match((await post({ resume: "nope" })).body.error!, /is not an X run id/); }); test("a stale jar refuses a new run before any job; the run's file is kept, deferred, for a Resume", async () => { const res = await post({ channels: ["top-x", "mid-x"] }); assert.equal(res.status, 400); assert.match(res.body.error!, /^X cookies were last refreshed 16 days ago \(limit 60 min\)/); assert.match(res.body.run!, /^xr-/); assert.deepEqual(await readdir(path.join(ROOT, ".jobs")).catch(() => []), []); const view = await get(`?run=${res.body.run}`); assert.equal(view.status, 200); const run = view.body.run as { status: string; summary: string; resumable: number }; assert.equal(run.status, "deferred"); assert.equal(run.summary, "0 done, 2 deferred until the next refresh"); assert.equal(run.resumable, 2); }); test("GET: the X posts channels in the default order, the jar against the limit; an unknown run is a 404", async () => { const { status, body } = await get(); assert.equal(status, 200); const candidates = body.candidates as { slug: string; tier: string }[]; assert.deepEqual( candidates.map((c) => [c.slug, c.tier]), [["top-x", "normal"], ["mid-x", "normal"], ["low-x", "low"]], ); const jar = body.jar as { allowed: boolean; maxAgeMinutes: number; staleAt: string; ageChecked: boolean }; assert.equal(jar.allowed, false); assert.equal(jar.maxAgeMinutes, 60); assert.equal(jar.ageChecked, true); assert.ok(Date.parse(jar.staleAt) < Date.now()); assert.equal(body.maxPosts, 200); assert.equal((await get("?run=xr-01ZZZZZZZZZZZZZZZZZZZZZZZZ")).status, 404); assert.equal((await get("?nope=1")).status, 400); });