Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(scripts): fail a PR whose After capture is a Before capture (#4177)
Miguel Ángel8d0722115646
diff --git a/.github/workflows/pr-captures.yml b/.github/workflows/pr-captures.ymlindex 81d2b899ad..a4c4943edf 100644--- a/.github/workflows/pr-captures.yml+++ b/.github/workflows/pr-captures.yml@@ -18,7 +18,7 @@ jobs:captures:name: Studio and player capturesruns-on: ubuntu-latest- timeout-minutes: 3+ timeout-minutes: 10steps:- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4with:@@ -28,5 +28,7 @@ jobs:PR_BODY: ${{ github.event.pull_request.body }}PR_NUMBER: ${{ github.event.pull_request.number }}BASE_REF: ${{ github.event.pull_request.base.ref }}+ HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }}+ BASE_REPO: ${{ github.repository }}HEAD_SHA: ${{ github.event.pull_request.head.sha }}run: node scripts/check-pr-captures.mjs --base "origin/$BASE_REF" --head "$HEAD_SHA"diff --git a/scripts/check-pr-captures.mjs b/scripts/check-pr-captures.mjsindex 10c624798d..1c9a1bc9b8 100644--- a/scripts/check-pr-captures.mjs+++ b/scripts/check-pr-captures.mjs@@ -3,6 +3,7 @@// usage: node scripts/check-pr-captures.mjs --base origin/main --head <sha>; the body arrives in the env (see main).import { execFileSync } from "node:child_process";+import { createHash } from "node:crypto";import { realpathSync } from "node:fs";import { pathToFileURL } from "node:url";@@ -14,6 +15,7 @@ const MEDIA_PATH = /\.(?:png|jpe?g|gif|webp|svg|mp4|mov|webm)$/i;const ATTACHMENT_PATH = /^\/user-attachments\/assets\/[\w-]+/;const IMAGE_EMBED =/!\[[^\]]*\]\(\s*https?:\/\/|<(?:img|video|source)\b[^>]*\bsrc=["']https?:\/\//i;+const TRAILING_PUNCTUATION = /[.,;:!?*_`]+$/;const ANY_URL = /https?:\/\/[^\s)"'<>\]]+/gi;function parseUrl(raw) {@@ -190,6 +192,229 @@ export function evaluate({ body, files }) {return { ok: false, problems: [...verdict.problems, ...captures] };}+const DOWNLOAD_ATTEMPTS = 3;+const DOWNLOAD_DEADLINE_MS = 45_000;+const RETRY_DELAYS_MS = [1000, 3000];+const MAX_REDIRECTS = 5;+const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);+const MAX_ASSET_BYTES = 100 * 1024 * 1024;+const MAX_CAPTURES = 12;+const MAX_TOTAL_BYTES = 300 * 1024 * 1024;+/** An attachment redirects to GitHub's own signed-storage bucket; a redirect anywhere else is not followed. */+const TRUSTED_REDIRECT_HOST =+ /^(([a-z0-9-]+\.)*(github\.com|githubusercontent\.com)|github-production-[a-z0-9-]+-asset-[a-z0-9]+\.s3\.amazonaws\.com)$/;++class NonRetryable extends Error {}+/** Our own byte cap tripped: unlike a failed download, this never justifies skipping the check. */+export class LimitExceeded extends NonRetryable {}++/** The next hop of a redirect, refused unless it stays on https and on a GitHub asset host. */+function trustedNextHop(response, current) {+ const next = new URL(response.headers.get("location") ?? "", current);+ if (next.protocol === "https:" && TRUSTED_REDIRECT_HOST.test(next.hostname)) return next.href;+ throw new NonRetryable(`redirected to ${next.hostname}, which is not a GitHub asset host`);+}++/** One GET, following redirects only to hosts that serve GitHub attachments. */+async function fetchTrusted(url, fetchImpl, signal) {+ let current = url;+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {+ const response = await fetchImpl(current, { redirect: "manual", signal });+ if (!REDIRECT_STATUSES.has(response.status)) return response;+ current = trustedNextHop(response, current);+ }+ throw new NonRetryable("too many redirects");+}++/** Collects chunks, refusing once this asset or the shared budget of the whole check runs out of bytes. */+function cappedCollector(budget) {+ const chunks = [];+ let size = 0;+ return {+ size: () => size,+ bytes: () => Buffer.concat(chunks),+ take(chunk) {+ size += chunk.byteLength;+ budget.left -= chunk.byteLength;+ if (size > MAX_ASSET_BYTES) throw new LimitExceeded(`larger than ${MAX_ASSET_BYTES} bytes`);+ if (budget.left < 0)+ throw new LimitExceeded(`captures together exceed ${MAX_TOTAL_BYTES} bytes`);+ chunks.push(Buffer.from(chunk));+ },+ };+}++async function drainBody(response, take) {+ if (!response.body?.getReader) return take(await response.arrayBuffer());+ const reader = response.body.getReader();+ try {+ for (let part = await reader.read(); !part.done; part = await reader.read()) take(part.value);+ } finally {+ await reader.cancel().catch(() => {});+ }+}++/** The body as bytes; an attempt that fails for any reason but our own cap gives its bytes back. */+async function readCapped(response, budget) {+ const collector = cappedCollector(budget);+ try {+ await drainBody(response, collector.take);+ } catch (error) {+ if (!(error instanceof LimitExceeded)) budget.left += collector.size();+ throw error;+ }+ return collector.bytes();+}++const isRetryableStatus = (status) => status === 429 || status >= 500;+const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));++/** One attempt: the bytes, or a NonRetryable for a final status, or a plain Error for a retryable one. */+async function attemptDownload(url, fetchImpl, signal, budget) {+ const response = await fetchTrusted(url, fetchImpl, signal);+ if (response.ok) return readCapped(response, budget);+ const message = `HTTP ${response.status}`;+ throw isRetryableStatus(response.status) ? new Error(message) : new NonRetryable(message);+}++async function waitForRetry(attempt, sleep, signal) {+ if (attempt > 0) await sleep(RETRY_DELAYS_MS[attempt - 1]);+ if (signal.aborted) throw new NonRetryable(`not finished within ${DOWNLOAD_DEADLINE_MS} ms`);+}++/** The bytes behind a capture URL; a 429, 5xx or network error is retried with backoff, any other status is final. */+export async function downloadAsset(+ url,+ fetchImpl = fetch,+ sleep = pause,+ budget = { left: MAX_TOTAL_BYTES },+) {+ const signal = AbortSignal.timeout(DOWNLOAD_DEADLINE_MS);+ let failure;+ for (let attempt = 0; attempt < DOWNLOAD_ATTEMPTS; attempt++) {+ await waitForRetry(attempt, sleep, signal);+ try {+ return await attemptDownload(url, fetchImpl, signal, budget);+ } catch (error) {+ if (error instanceof NonRetryable) throw error;+ failure = error;+ }+ }+ throw failure;+}++/** The asset a link names: query, fragment and default port do not change it. */+const linkIdentity = (url) => (url === null ? "" : `${url.origin}${url.pathname}`);++/** Only GitHub attachment URLs are downloaded: a body must not make the runner fetch an arbitrary host. */+const captureUrls = (section) => [+ ...new Set(+ (section.text.match(ANY_URL) ?? [])+ .map((raw) => parseUrl(raw.replace(TRAILING_PUNCTUATION, "")))+ .filter((url) => url !== null && url.protocol === "https:" && isAttachmentUrl(url))+ .map(linkIdentity),+ ),+];++const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");++/** url -> hash for each capture, read one at a time so one large asset cannot starve a sibling of the shared budget. */+async function hashCaptures(name, urls, download) {+ const hashed = [];+ for (const url of urls) {+ let bytes;+ try {+ bytes = await download(url);+ } catch (error) {+ const problem = `could not download ${name} asset ${url}: ${error.message}`;+ hashed.push({ name, url, problem, refused: error instanceof LimitExceeded });+ continue;+ }+ hashed.push({ name, url, hash: sha256(bytes) });+ }+ return hashed;+}++const noProblems = () => ({ unreadable: [], identical: [], refused: [], notices: [] });++const linkLimitProblem = (urls) =>+ new Set(urls).size > MAX_CAPTURES+ ? {+ ...noProblems(),+ refused: [`more than ${MAX_CAPTURES} capture links; attach fewer, longer clips`],+ }+ : null;++const perCheckDownloader = () => {+ const budget = { left: MAX_TOTAL_BYTES };+ return (url) => downloadAsset(url, fetch, pause, budget);+};++const identicalPairs = (befores, afters) =>+ afters.flatMap((asset) =>+ befores+ .filter((old) => old.hash === asset.hash)+ .map((old) => `After asset ${asset.url} is byte-identical to Before asset ${old.url}`),+ );++async function compareCaptures(beforeUrls, afterUrls, download) {+ const shared = afterUrls.filter((url) => beforeUrls.includes(url));+ const unshared = (urls) => urls.filter((url) => !shared.includes(url));+ const befores = await hashCaptures("Before", unshared(beforeUrls), download);+ const afters = await hashCaptures("After", unshared(afterUrls), download);+ const problems = [...befores, ...afters].filter((asset) => asset.problem);+ const sameLink = shared.map((url) => `After asset ${url} is the same link as a Before asset`);+ return {+ unreadable: problems.filter((asset) => !asset.refused).map((asset) => asset.problem),+ identical: [+ ...sameLink,+ ...identicalPairs(+ befores.filter((asset) => asset.hash),+ afters.filter((asset) => asset.hash),+ ),+ ],+ refused: problems.filter((asset) => asset.refused).map((asset) => asset.problem),+ };+}++const trimmedLinks = (section) =>+ (section.text.match(ANY_URL) ?? []).map((raw) => raw.replace(TRAILING_PUNCTUATION, ""));++/** Media links the hash comparison cannot see: an http attachment is a typo to fix, any other host is only noted. */+function uncomparable(sections) {+ const skipped = sections.flatMap(trimmedLinks).filter(isMediaUrl);+ const comparable = new Set(sections.flatMap(captureUrls));+ const rest = skipped.filter((raw) => !comparable.has(linkIdentity(parseUrl(raw))));+ const insecure = rest.filter(+ (raw) => parseUrl(raw)?.protocol === "http:" && isAttachmentUrl(parseUrl(raw)),+ );+ return {+ refused: insecure.map((raw) => `${raw} is an http link; use the https link of the attachment`),+ notices: rest+ .filter((raw) => !insecure.includes(raw))+ .map((raw) => `not compared, not a GitHub attachment: ${raw}`),+ };+}++/** Every After asset must differ by content hash from every Before asset; an unreadable download is a problem. */+export async function duplicateCaptureProblems(body, download = perCheckDownloader()) {+ const sections = parseSections(body);+ const before = findSection(sections, "before");+ const after = findSection(sections, "after");+ if (!before || !after) return noProblems();+ const beforeUrls = captureUrls(before);+ const afterUrls = captureUrls(after);+ const tooMany = linkLimitProblem([...beforeUrls, ...afterUrls]);+ if (tooMany) return tooMany;+ const compared = await compareCaptures(beforeUrls, afterUrls, download);+ const skipped = uncomparable([before, after]);+ return {+ ...compared,+ refused: [...compared.refused, ...skipped.refused],+ notices: skipped.notices,+ };+}+export function attachCommand(prNumber) {return `gh pr edit ${prNumber} --attach ./before.png --attach ./after.png`;}@@ -226,18 +451,51 @@ function printFailure(problems, prNumber) {);}-function main() {+/** A fork's PR runs without secrets, so an unreadable capture there is skipped, never failed. */+export const isFork = (env) => Boolean(env.HEAD_REPO) && env.HEAD_REPO !== env.BASE_REPO;+export const blocking = (unreadable, mustFix, env) =>+ mustFix.length > 0 || (unreadable.length > 0 && !isFork(env));++function printList(heading, problems, out = console.error) {+ if (problems.length === 0) return;+ out(heading);+ for (const problem of problems) out(` - ${problem}`);+}++function reportCaptureProblems({ unreadable, identical, refused, notices }, env) {+ const skipped =+ "Skipped the duplicate-capture comparison: this PR is from a fork and a capture could not be downloaded without a token, which a fork cannot have.";+ if (isFork(env)) printList(skipped, unreadable, console.log);+ else printList("A capture could not be downloaded to compare:", unreadable);+ printList(+ "A capture under After is the same file as one under Before; re-attach the real After recording:",+ identical,+ );+ printList("The capture comparison cannot pass as it stands:", refused);+ printList("Links the duplicate check could not compare:", notices, console.log);+}++const prFromEnv = (env) => ({ body: env.PR_BODY ?? "", number: env.PR_NUMBER ?? "<number>" });+const findProblems = (body, files) =>+ files.length > 0 ? duplicateCaptureProblems(body) : noProblems();++async function main() {const args = process.argv.slice(2);const numstat = readNumstat(flag(args, "--base", "origin/main"), flag(args, "--head", "HEAD"));- const body = process.env.PR_BODY ?? "";- const { ok, problems } = evaluate({ body, files: parseNumstat(numstat) });- if (ok) {- console.log("packages/studio and packages/player: captures present, or nothing to show.");- return;+ const { body, number } = prFromEnv(process.env);+ const files = parseNumstat(numstat);+ const { ok, problems } = evaluate({ body, files });+ if (!ok) {+ printFailure(problems, number);+ process.exit(1);+ }+ const found = await findProblems(body, files);+ reportCaptureProblems(found, process.env);+ if (blocking(found.unreadable, [...found.identical, ...found.refused], process.env)) {+ process.exit(1);}- printFailure(problems, process.env.PR_NUMBER ?? "<number>");- process.exit(1);+ console.log("packages/studio and packages/player: captures present, or nothing to show.");}if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href)- main();+ await main();diff --git a/scripts/check-pr-captures.test.mjs b/scripts/check-pr-captures.test.mjsindex 360ff23175..70d58450f1 100644--- a/scripts/check-pr-captures.test.mjs+++ b/scripts/check-pr-captures.test.mjs@@ -1,12 +1,17 @@import { strict as assert } from "node:assert";import { spawnSync } from "node:child_process";-import { copyFileSync, mkdtempSync } from "node:fs";+import { copyFileSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { test } from "node:test";import {+ blocking,+ isFork,attachCommand,+ downloadAsset,+ duplicateCaptureProblems,+ LimitExceeded,evaluate,hasMedia,parseNumstat,@@ -235,3 +240,440 @@ test("a heading or media URL must match whole, not as a substring", () => {false,);});++const OLD = "https://github.com/user-attachments/assets/aaaaaaaa-0000-4000-8000-000000000001";+const NEW = "https://github.com/user-attachments/assets/bbbbbbbb-0000-4000-8000-000000000002";+const sameBytes = "https://github.com/user-attachments/assets/cccccccc-0000-4000-8000-000000000003";+const OLD2 = "https://github.com/user-attachments/assets/eeeeeeee-0000-4000-8000-000000000005";+const bytesByUrl = { [OLD]: "old", [NEW]: "new", [sameBytes]: "old", [OLD2]: "older" };+const fromMap = async (url) => {+ if (!(url in bytesByUrl)) throw new Error("HTTP 404");+ return Buffer.from(bytesByUrl[url]);+};+const bodyWith = (before, after) => `## Before\n${before}\n\n## After\n${after}\n`;+const clean = { unreadable: [], identical: [], refused: [], notices: [] };+const dupes = (body) => duplicateCaptureProblems(body, fromMap);++test("an After asset with different bytes than every Before asset passes", async () => {+ assert.deepEqual(await dupes(bodyWith(`[a](${OLD})`, `[b](${NEW})`)), clean);+});++test("an After asset with the same bytes as a Before asset fails, even under another URL", async () => {+ const { identical } = await dupes(bodyWith(`[a](${OLD})`, `[b](${sameBytes})`));+ assert.deepEqual(identical, [+ `After asset ${sameBytes} is byte-identical to Before asset ${OLD}`,+ ]);+});++test("the same URL under both headings fails", async () => {+ const { identical } = await dupes(bodyWith(`[a](${OLD})`, `[b](${OLD})`));+ assert.equal(identical.length, 1);+});++test("a duplicate of the second Before asset is found, not only of the first", async () => {+ const { identical } = await dupes(bodyWith(`[a](${OLD2})\n[b](${OLD})`, `[c](${sameBytes})`));+ assert.deepEqual(identical, [+ `After asset ${sameBytes} is byte-identical to Before asset ${OLD}`,+ ]);+});++test("one duplicate among several After assets is still found", async () => {+ const { identical } = await dupes(bodyWith(`[a](${OLD})`, `[b](${NEW})\n[c](${sameBytes})`));+ assert.deepEqual(identical, [+ `After asset ${sameBytes} is byte-identical to Before asset ${OLD}`,+ ]);+});++test("an asset that cannot be downloaded is a problem, not a pass", async () => {+ const missing = "https://github.com/user-attachments/assets/dddddddd-0000-4000-8000-000000000004";+ const { unreadable } = await dupes(bodyWith(`[a](${OLD})`, `[b](${missing})`));+ assert.deepEqual(unreadable, [`could not download After asset ${missing}: HTTP 404`]);+});++test("a body without both headings has nothing to compare", async () => {+ assert.deepEqual(await dupes(`## Before\n[a](${OLD})`), clean);+});++test("a URL that is not a GitHub attachment is never fetched", async () => {+ const fetched = [];+ const spy = async (url) => (fetched.push(url), Buffer.from("x"));+ const other = "http://169.254.169.254/latest/x.png";+ await duplicateCaptureProblems(bodyWith(``, ``), spy);+ assert.deepEqual(fetched, []);+});++const ok = () => ({+ ok: true,+ status: 200,+ arrayBuffer: async () => new TextEncoder().encode("x").buffer,+});+const noSleep = async () => {};++test("downloadAsset retries a 5xx or a network error with backoff and stops after three attempts", async () => {+ const outcomes = [{ ok: false, status: 502 }, new Error("socket hang up"), ok()];+ let calls = 0;+ const sleeps = [];+ const flaky = async () => {+ const next = outcomes[calls++];+ if (next instanceof Error) throw next;+ return next;+ };+ assert.equal((await downloadAsset(OLD, flaky, async (ms) => sleeps.push(ms))).toString(), "x");+ assert.equal(calls, 3);+ assert.deepEqual(sleeps, [1000, 3000]);+ calls = 0;+ await assert.rejects(+ downloadAsset(OLD, async () => (calls++, { ok: false, status: 500 }), noSleep),+ /HTTP 500/,+ );+ assert.equal(calls, 3);+});++test("downloadAsset does not retry a 404 or 403", async () => {+ for (const status of [404, 403]) {+ let calls = 0;+ await assert.rejects(+ downloadAsset(OLD, async () => (calls++, { ok: false, status }), noSleep),+ new RegExp(`HTTP ${status}`),+ );+ assert.equal(calls, 1);+ }+});++const redirect = (location) => ({ ok: false, status: 302, headers: new Headers({ location }) });++test("downloadAsset follows a redirect to signed storage but not to another host", async () => {+ const signed = "https://github-production-user-asset-6210df.s3.amazonaws.com/1/clip.mp4?X-Amz=1";+ const seen = [];+ const viaS3 = async (url) => (seen.push(url), url === OLD ? redirect(signed) : ok());+ assert.equal((await downloadAsset(OLD, viaS3, noSleep)).toString(), "x");+ assert.deepEqual(seen, [OLD, signed]);++ const internal = "https://metadata.internal.example/latest/x.png";+ const toInternal = async (url) => (seen.push(url), redirect(internal));+ seen.length = 0;+ await assert.rejects(downloadAsset(OLD, toInternal, noSleep), /not a GitHub asset host/);+ assert.deepEqual(seen, [OLD]);+});++test("downloadAsset asks for manual redirects so every hop is checked", async () => {+ let asked;+ await downloadAsset(OLD, async (_url, init) => ((asked = init.redirect), ok()), noSleep);+ assert.equal(asked, "manual");+});++test("a redirect over plain http is refused even to a trusted host", async () => {+ const insecure = "http://github.com/user-attachments/assets/x";+ await assert.rejects(+ downloadAsset(OLD, async () => redirect(insecure), noSleep),+ /not a GitHub asset host/,+ );+});++test("the duplicate check is skipped when the PR touches neither package", () => {+ const dir = mkdtempSync(join(tmpdir(), "captures-gate-"));+ const git = (...args) => spawnSync("git", args, { cwd: dir, encoding: "utf8" });+ git("init", "-q", "-b", "main");+ git("-c", "user.email=a@b", "-c", "user.name=t", "commit", "-q", "--allow-empty", "-m", "base");+ const copy = join(dir, "check.mjs");+ copyFileSync(new URL("./check-pr-captures.mjs", import.meta.url), copy);+ const body = bodyWith(`[a](${OLD})`, `[b](${OLD})`);+ const result = spawnSync("node", [copy, "--base", "main", "--head", "HEAD"], {+ cwd: dir,+ encoding: "utf8",+ env: { ...process.env, PR_BODY: body },+ });+ assert.equal(result.status, 0, result.stderr);+});++test("a redirect to another S3 bucket is refused, GitHub's asset bucket is not", async () => {+ const other = "https://attacker-bucket.s3.amazonaws.com/x.mp4";+ await assert.rejects(+ downloadAsset(OLD, async () => redirect(other), noSleep),+ /not a GitHub asset host/,+ );+ const lookalike = "https://github-production-user-asset-1.s3.amazonaws.com.evil.example/x";+ await assert.rejects(+ downloadAsset(OLD, async () => redirect(lookalike), noSleep),+ /not a GitHub asset host/,+ );+});++const streamOf = (...sizes) => ({+ ok: true,+ status: 200,+ body: new ReadableStream({+ start(controller) {+ for (const size of sizes) controller.enqueue(new Uint8Array(size));+ controller.close();+ },+ }),+});+const MB = 1024 * 1024;++test("downloadAsset refuses one asset over the per-asset cap", async () => {+ await assert.rejects(+ downloadAsset(OLD, async () => streamOf(60 * MB, 60 * MB), noSleep),+ /larger than/,+ );+});++test("downloadAsset refuses once the shared budget is spent, across assets", async () => {+ const budget = { left: 150 * MB };+ const get = async () => streamOf(90 * MB);+ await downloadAsset(OLD, get, noSleep, budget);+ await assert.rejects(downloadAsset(NEW, get, noSleep, budget), /together exceed/);+});++test("an unreadable capture blocks a same-repo PR but is skipped on a fork", () => {+ const same = { HEAD_REPO: "a/r", BASE_REPO: "a/r" };+ const fork = { HEAD_REPO: "someone/r", BASE_REPO: "a/r" };+ assert.equal(isFork(same), false);+ assert.equal(isFork(fork), true);+ assert.equal(isFork({}), false);+ assert.equal(isFork({ BASE_REPO: "a/r" }), false);+ assert.equal(blocking(["x"], [], same), true);+ assert.equal(blocking(["x"], [], fork), false);+ assert.equal(blocking([], ["dup"], fork), true);+});++test("the same link under both headings is caught without any download", async () => {+ let fetched = 0;+ const { identical } = await duplicateCaptureProblems(bodyWith(OLD, OLD), async () => {+ fetched++;+ return Buffer.from("x");+ });+ assert.equal(identical.length, 1);+ assert.equal(fetched, 0);+});++test("a plain http attachment link is never fetched", async () => {+ const insecure = OLD.replace("https:", "http:");+ const seen = [];+ await duplicateCaptureProblems(+ bodyWith(insecure, NEW),+ async (url) => (seen.push(url), Buffer.from(url)),+ );+ assert.deepEqual(seen, [NEW]);+});++test("a lookalike of a trusted host is refused as a redirect", async () => {+ for (const host of ["evilgithub.com", "github.com.evil.example", "notgithubusercontent.com"]) {+ await assert.rejects(+ downloadAsset(OLD, async () => redirect(`https://${host}/x`), noSleep),+ /not a GitHub asset host/,+ );+ }+});++test("a redirect loop stops after the redirect limit", async () => {+ let calls = 0;+ const loop = async () => (calls++, redirect("https://github.com/user-attachments/assets/loop"));+ await assert.rejects(downloadAsset(OLD, loop, noSleep), /too many redirects/);+ assert.equal(calls, 6);+});++test("a 429 is retried", async () => {+ let calls = 0;+ const limited = async () => (++calls < 2 ? { ok: false, status: 429 } : ok());+ assert.equal((await downloadAsset(OLD, limited, noSleep)).toString(), "x");+});++test("the body reader is cancelled when the cap stops a download", async () => {+ let cancelled = false;+ const body = new ReadableStream({+ pull: (controller) => controller.enqueue(new Uint8Array(60 * MB)),+ cancel: () => (cancelled = true),+ });+ await assert.rejects(+ downloadAsset(OLD, async () => ({ ok: true, status: 200, body }), noSleep),+ /larger than/,+ );+ assert.equal(cancelled, true);+});++test("the deadline covers every attempt, so a slow asset is not retried past it", async () => {+ const deadline = new AbortController();+ let calls = 0;+ const failsAfterDeadline = async () => {+ calls++;+ deadline.abort();+ throw new Error("network");+ };+ const realTimeout = AbortSignal.timeout;+ AbortSignal.timeout = () => deadline.signal;+ try {+ await assert.rejects(downloadAsset(OLD, failsAfterDeadline, noSleep), /not finished within/);+ } finally {+ AbortSignal.timeout = realTimeout;+ }+ assert.equal(calls, 1);+});++function runCli(env, body = bodyWith(`[a](${OLD})`, `[b](${NEW})`)) {+ const dir = mkdtempSync(join(tmpdir(), "captures-cli-"));+ const git = (...args) => spawnSync("git", args, { cwd: dir, encoding: "utf8" });+ git("init", "-q", "-b", "main");+ git("-c", "user.email=a@b", "-c", "user.name=t", "commit", "-q", "--allow-empty", "-m", "base");+ git("checkout", "-q", "-b", "pr");+ mkdirSync(join(dir, "packages/studio/src"), { recursive: true });+ writeFileSync(join(dir, "packages/studio/src/a.ts"), "x\n".repeat(50));+ git("add", "-A");+ git("-c", "user.email=a@b", "-c", "user.name=t", "commit", "-q", "-m", "change");+ const copy = join(dir, "check.mjs");+ copyFileSync(new URL("./check-pr-captures.mjs", import.meta.url), copy);+ const preload = join(dir, "no-network.mjs");+ writeFileSync(preload, "globalThis.fetch = async () => ({ ok: false, status: 404 });\n");+ return spawnSync("node", ["--import", preload, copy, "--base", "main", "--head", "HEAD"], {+ cwd: dir,+ encoding: "utf8",+ env: { ...process.env, PR_BODY: body, ...env },+ });+}++test("the CLI fails a same-repo PR whose capture cannot be downloaded", () => {+ const result = runCli({ HEAD_REPO: "a/r", BASE_REPO: "a/r" });+ assert.equal(result.status, 1, result.stdout + result.stderr);+ assert.match(result.stderr, /could not be downloaded/);+});++test("the CLI skips, and says why, for a fork PR whose capture cannot be downloaded", () => {+ const result = runCli({ HEAD_REPO: "someone/r", BASE_REPO: "a/r" });+ assert.equal(result.status, 0, result.stdout + result.stderr);+ assert.match(result.stdout, /from a fork/);+});++const forkEnv = { HEAD_REPO: "someone/r", BASE_REPO: "a/r" };++test("our own cap tripping is refused, not counted as an unreadable download", async () => {+ const capped = async (url) => {+ if (url === NEW) throw new LimitExceeded("captures together exceed the budget");+ return Buffer.from("old");+ };+ const result = await duplicateCaptureProblems(bodyWith(`[a](${OLD})`, `[b](${NEW})`), capped);+ assert.equal(result.unreadable.length, 0);+ assert.equal(result.refused.length, 1);+ assert.equal(+ blocking(result.unreadable, [...result.identical, ...result.refused], forkEnv),+ true,+ );+});++test("a failed attempt gives its bytes back to the shared budget", async () => {+ const budget = { left: 150 * MB };+ let attempt = 0;+ let sent = 0;+ const flaky = async () => {+ if (++attempt > 1) return streamOf(1);+ return {+ ok: true,+ status: 200,+ body: new ReadableStream({+ pull(controller) {+ if (sent++ === 0) controller.enqueue(new Uint8Array(50 * MB));+ else controller.error(new Error("connection reset"));+ },+ }),+ };+ };+ await downloadAsset(OLD, flaky, noSleep, budget);+ assert.equal(budget.left, 150 * MB - 1);+});++test("trailing punctuation and a query string do not change which asset a link names", async () => {+ const seen = [];+ const record = async (url) => (seen.push(url), Buffer.from(url));+ await duplicateCaptureProblems(bodyWith(`see ${OLD}.`, `${NEW}?raw=1, done`), record);+ assert.deepEqual(seen, [OLD, NEW]);+ const same = await duplicateCaptureProblems(bodyWith(OLD, `${OLD}?raw=1`), record);+ assert.equal(same.identical.length, 1);+});++test("more capture links than the limit is refused", async () => {+ const links = Array.from(+ { length: 13 },+ (_, i) =>+ `https://github.com/user-attachments/assets/${String(i).padStart(8, "0")}-0000-4000-8000-000000000000`,+ );+ const result = await duplicateCaptureProblems(bodyWith(links.join("\n"), NEW), fromMap);+ assert.equal(result.refused.length, 1);+});++test("the CLI still fails a fork PR whose After link is a Before link", () => {+ const result = runCli({ HEAD_REPO: "someone/r", BASE_REPO: "a/r" }, bodyWith(OLD, OLD));+ assert.equal(result.status, 1, result.stdout + result.stderr);+ assert.match(result.stderr, /same link/);+});++test("the CLI fails a fork PR that hits a limit of the check", () => {+ const links = Array.from(+ { length: 13 },+ (_, i) =>+ `https://github.com/user-attachments/assets/${String(i).padStart(8, "0")}-0000-4000-8000-000000000000`,+ );+ const result = runCli(+ { HEAD_REPO: "someone/r", BASE_REPO: "a/r" },+ bodyWith(links.join("\n"), NEW),+ );+ assert.equal(result.status, 1, result.stdout + result.stderr);+ assert.match(result.stderr, /cannot pass as it stands/);+});++test("exactly twelve capture links are accepted, shared links count once, markdown wrappers are stripped", async () => {+ const link = (i) =>+ `https://github.com/user-attachments/assets/${String(i).padStart(8, "0")}-0000-4000-8000-000000000000`;+ const twelve = Array.from({ length: 12 }, (_, i) => link(i));+ const ok = await duplicateCaptureProblems(bodyWith(twelve.join("\n"), link(99)), async (u) =>+ Buffer.from(u),+ );+ assert.equal(ok.refused.length, 1);+ const atCap = await duplicateCaptureProblems(+ bodyWith(twelve.slice(0, 11).join("\n"), link(99)),+ async (u) => Buffer.from(u),+ );+ assert.equal(atCap.refused.length, 0);+ const shared = await duplicateCaptureProblems(+ bodyWith(twelve.join("\n"), twelve.join("\n")),+ async (u) => Buffer.from(u),+ );+ assert.equal(shared.refused.length, 0);+ const seen = [];+ await duplicateCaptureProblems(+ bodyWith(`**${OLD}**`, `_${NEW}_ and \`${sameBytes}\``),+ async (u) => (seen.push(u), Buffer.from(u)),+ );+ assert.deepEqual(seen, [OLD, NEW, sameBytes]);+});++test("an http attachment link is refused, an external media link is only noted", async () => {+ const insecure = OLD.replace("https:", "http:");+ const external = "https://example.com/clip.mp4";+ const both = await duplicateCaptureProblems(bodyWith(insecure, `${NEW} ${external}`), fromMap);+ assert.equal(both.refused.length, 1);+ assert.match(both.refused[0], /use the https link/);+ assert.deepEqual(both.notices, [`not compared, not a GitHub attachment: ${external}`]);+ const sameExternal = await duplicateCaptureProblems(bodyWith(external, external), fromMap);+ assert.equal(sameExternal.refused.length, 0);+ assert.equal(sameExternal.notices.length, 2);+});++test("a link with an explicit port or upper-case host is compared, not reported as skipped", async () => {+ const odd = NEW.replace("https://github.com", "https://GitHub.com:443");+ const result = await duplicateCaptureProblems(bodyWith(OLD, odd), fromMap);+ assert.deepEqual(result.notices, []);+});++test("a cap trip does not give its bytes back to the budget", async () => {+ const budget = { left: 300 * MB };+ await assert.rejects(downloadAsset(OLD, async () => streamOf(60 * MB, 60 * MB), noSleep, budget));+ assert.ok(budget.left < 300 * MB - 100 * MB);+});++test("the CLI passes on notices alone", () => {+ const result = runCli(+ { HEAD_REPO: "a/r", BASE_REPO: "a/r" },+ bodyWith("https://example.com/a.mp4", "https://example.com/b.mp4"),+ );+ assert.equal(result.status, 0, result.stdout + result.stderr);+ assert.match(result.stdout, /not compared/);+});