Skip to content

Commit 1c4ffb3

Browse files
cdervclaude
andcommitted
Add Chrome for Testing download utilities
Shared infrastructure for downloading binaries from the Google Chrome for Testing (CfT) API. Provides platform detection, API fetching, binary search, and download+extract functions that will be used by installable tool implementations. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent 938561b commit 1c4ffb3

4 files changed

Lines changed: 367 additions & 0 deletions

File tree

‎src/deno_ral/fs.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { resolve, SEP as SEPARATOR } from "./path.ts";
99
import { copySync } from "fs/copy";
1010
import { existsSync } from "fs/exists";
1111
import { originalRealPathSync } from "./original-real-path.ts";
12+
import { debug } from "./log.ts";
1213

1314
export { ensureDir, ensureDirSync } from "fs/ensure-dir";
1415
export { existsSync } from "fs/exists";
@@ -175,3 +176,18 @@ export function safeModeFromFile(path: string): number | undefined {
175176
}
176177
}
177178
}
179+
180+
/**
181+
* Set file mode in a platform-safe way. No-op on Windows (where chmod
182+
* is not supported). Swallows errors on other platforms since permission
183+
* changes are often non-fatal (e.g., on filesystems that don't support it).
184+
*/
185+
export function safeChmodSync(path: string, mode: number): void {
186+
if (Deno.build.os !== "windows") {
187+
try {
188+
Deno.chmodSync(path, mode);
189+
} catch (e) {
190+
debug(`safeChmodSync: failed to chmod ${path}: ${e}`);
191+
}
192+
}
193+
}

‎src/deno_ral/platform.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,5 @@ export const isMac = Deno.build.os === "darwin";
99
export const isLinux = Deno.build.os === "linux";
1010

1111
export const os = Deno.build.os;
12+
13+
export const arch = Deno.build.arch;
Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
/*
2+
* chrome-for-testing.ts
3+
*
4+
* Utilities for downloading binaries from the Chrome for Testing (CfT) API.
5+
* https://github.com/GoogleChromeLabs/chrome-for-testing
6+
* https://googlechromelabs.github.io/chrome-for-testing/
7+
*
8+
* Copyright (C) 2026 Posit Software, PBC
9+
*/
10+
11+
import { basename } from "../../deno_ral/path.ts";
12+
import { safeChmodSync, safeRemoveSync, walkSync } from "../../deno_ral/fs.ts";
13+
import { debug } from "../../deno_ral/log.ts";
14+
import { arch, isWindows, os } from "../../deno_ral/platform.ts";
15+
import { unzip } from "../../core/zip.ts";
16+
import { InstallContext } from "../types.ts";
17+
18+
/** CfT platform identifiers matching the Google Chrome for Testing API. */
19+
export type CftPlatform =
20+
| "linux64"
21+
| "mac-arm64"
22+
| "mac-x64"
23+
| "win32"
24+
| "win64";
25+
26+
/** Platform detection result. */
27+
export interface PlatformInfo {
28+
platform: CftPlatform;
29+
os: string;
30+
arch: string;
31+
}
32+
33+
/**
34+
* Map os + arch to a CfT platform string.
35+
* Throws on unsupported platforms (e.g., linux aarch64 — to be handled by Playwright CDN).
36+
*/
37+
export function detectCftPlatform(): PlatformInfo {
38+
const platformMap: Record<string, CftPlatform> = {
39+
"linux-x86_64": "linux64",
40+
"darwin-aarch64": "mac-arm64",
41+
"darwin-x86_64": "mac-x64",
42+
"windows-x86_64": "win64",
43+
"windows-x86": "win32",
44+
};
45+
46+
const key = `${os}-${arch}`;
47+
const platform = platformMap[key];
48+
49+
if (!platform) {
50+
if (os === "linux" && arch === "aarch64") {
51+
throw new Error(
52+
"linux-arm64 is not supported by Chrome for Testing. " +
53+
"Use 'quarto install chromium' for arm64 support.",
54+
);
55+
}
56+
throw new Error(
57+
`Unsupported platform for Chrome for Testing: ${os} ${arch}`,
58+
);
59+
}
60+
61+
return { platform, os, arch };
62+
}
63+
64+
/** A single download entry from the CfT API. */
65+
export interface CftDownload {
66+
platform: CftPlatform;
67+
url: string;
68+
}
69+
70+
/** Parsed stable release from the CfT last-known-good-versions API. */
71+
export interface CftStableRelease {
72+
version: string;
73+
downloads: {
74+
chrome?: CftDownload[];
75+
"chrome-headless-shell"?: CftDownload[];
76+
chromedriver?: CftDownload[];
77+
};
78+
}
79+
80+
const kCftVersionsUrl =
81+
"https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions-with-downloads.json";
82+
83+
/**
84+
* Fetch the latest stable Chrome version and download URLs from the CfT API.
85+
*/
86+
export async function fetchLatestCftRelease(): Promise<CftStableRelease> {
87+
let response: Response;
88+
try {
89+
response = await fetch(kCftVersionsUrl);
90+
} catch (e) {
91+
throw new Error(
92+
`Failed to fetch Chrome for Testing API: ${
93+
e instanceof Error ? e.message : String(e)
94+
}`,
95+
);
96+
}
97+
98+
if (!response.ok) {
99+
throw new Error(
100+
`Chrome for Testing API returned ${response.status}: ${response.statusText}`,
101+
);
102+
}
103+
104+
// deno-lint-ignore no-explicit-any
105+
let data: any;
106+
try {
107+
data = await response.json();
108+
} catch {
109+
throw new Error("Chrome for Testing API returned invalid JSON");
110+
}
111+
112+
const stable = data?.channels?.Stable;
113+
if (!stable || !stable.version || !stable.downloads) {
114+
throw new Error(
115+
"Chrome for Testing API response missing expected 'channels.Stable' structure",
116+
);
117+
}
118+
119+
return {
120+
version: stable.version,
121+
downloads: stable.downloads,
122+
};
123+
}
124+
125+
/**
126+
* Find a named executable inside an extracted CfT directory.
127+
* Handles platform-specific naming (.exe on Windows) and nested directory structures.
128+
* Returns absolute path to the executable, or undefined if not found.
129+
*/
130+
export function findCftExecutable(
131+
extractedDir: string,
132+
binaryName: string,
133+
): string | undefined {
134+
const target = isWindows ? `${binaryName}.exe` : binaryName;
135+
136+
for (const entry of walkSync(extractedDir, { includeDirs: false })) {
137+
if (basename(entry.path) === target) {
138+
return entry.path;
139+
}
140+
}
141+
142+
return undefined;
143+
}
144+
145+
/**
146+
* Download a CfT zip from URL, extract to targetDir, set executable permissions.
147+
* Uses InstallContext.download() for progress reporting with the given label.
148+
* When binaryName is provided, sets executable permission only on that binary.
149+
* Returns the target directory path.
150+
*/
151+
export async function downloadAndExtractCft(
152+
label: string,
153+
url: string,
154+
targetDir: string,
155+
context: InstallContext,
156+
binaryName?: string,
157+
): Promise<string> {
158+
const tempZipPath = Deno.makeTempFileSync({ suffix: ".zip" });
159+
160+
try {
161+
await context.download(label, url, tempZipPath);
162+
await unzip(tempZipPath, targetDir);
163+
} finally {
164+
safeRemoveSync(tempZipPath);
165+
}
166+
167+
if (binaryName) {
168+
const executable = findCftExecutable(targetDir, binaryName);
169+
if (executable) {
170+
safeChmodSync(executable, 0o755);
171+
} else {
172+
debug(`downloadAndExtractCft: expected binary '${binaryName}' not found in ${targetDir}`);
173+
}
174+
}
175+
176+
return targetDir;
177+
}
Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
/*
2+
* chrome-for-testing.test.ts
3+
*
4+
* Copyright (C) 2026 Posit Software, PBC
5+
*/
6+
7+
import { unitTest } from "../../test.ts";
8+
import { assert, assertEquals } from "testing/asserts";
9+
import { arch, os } from "../../../src/deno_ral/platform.ts";
10+
import { join } from "../../../src/deno_ral/path.ts";
11+
import { safeRemoveSync } from "../../../src/deno_ral/fs.ts";
12+
import { isWindows } from "../../../src/deno_ral/platform.ts";
13+
import { runningInCI } from "../../../src/core/ci-info.ts";
14+
import { InstallContext } from "../../../src/tools/types.ts";
15+
import {
16+
detectCftPlatform,
17+
downloadAndExtractCft,
18+
fetchLatestCftRelease,
19+
findCftExecutable,
20+
} from "../../../src/tools/impl/chrome-for-testing.ts";
21+
22+
// Step 1: detectCftPlatform()
23+
unitTest("detectCftPlatform - returns valid CftPlatform for current system", async () => {
24+
const result = detectCftPlatform();
25+
const validPlatforms = ["linux64", "mac-arm64", "mac-x64", "win32", "win64"];
26+
assert(
27+
validPlatforms.includes(result.platform),
28+
`Expected one of ${validPlatforms.join(", ")}, got: ${result.platform}`,
29+
);
30+
assert(result.os.length > 0, "os should be non-empty");
31+
assert(result.arch.length > 0, "arch should be non-empty");
32+
});
33+
34+
unitTest("detectCftPlatform - returns win64 on Windows x86_64", async () => {
35+
if (os !== "windows" || arch !== "x86_64") {
36+
return; // Skip on non-Windows
37+
}
38+
const result = detectCftPlatform();
39+
assertEquals(result.platform, "win64");
40+
assertEquals(result.os, "windows");
41+
assertEquals(result.arch, "x86_64");
42+
});
43+
44+
// Step 2: fetchLatestCftRelease()
45+
// These tests make real HTTP calls to the CfT API — skip on CI.
46+
unitTest("fetchLatestCftRelease - returns valid version string", async () => {
47+
const release = await fetchLatestCftRelease();
48+
assert(release.version, "version should be non-empty");
49+
assert(
50+
/^\d+\.\d+\.\d+\.\d+$/.test(release.version),
51+
`version should match X.Y.Z.W format, got: ${release.version}`,
52+
);
53+
}, { ignore: runningInCI() });
54+
55+
unitTest("fetchLatestCftRelease - has chrome-headless-shell downloads", async () => {
56+
const release = await fetchLatestCftRelease();
57+
const downloads = release.downloads["chrome-headless-shell"];
58+
assert(downloads, "chrome-headless-shell downloads should exist");
59+
assert(downloads!.length > 0, "should have at least one download");
60+
}, { ignore: runningInCI() });
61+
62+
unitTest("fetchLatestCftRelease - download URLs are valid", async () => {
63+
const release = await fetchLatestCftRelease();
64+
const downloads = release.downloads["chrome-headless-shell"]!;
65+
for (const dl of downloads) {
66+
assert(
67+
dl.url.startsWith("https://storage.googleapis.com/"),
68+
`URL should start with googleapis.com, got: ${dl.url}`,
69+
);
70+
assert(
71+
dl.url.includes(release.version),
72+
`URL should contain version ${release.version}, got: ${dl.url}`,
73+
);
74+
}
75+
}, { ignore: runningInCI() });
76+
77+
// Step 3: findCftExecutable()
78+
unitTest("findCftExecutable - finds binary in CfT directory structure", async () => {
79+
const tempDir = Deno.makeTempDirSync();
80+
try {
81+
const subdir = join(tempDir, "chrome-headless-shell-linux64");
82+
Deno.mkdirSync(subdir);
83+
const binaryName = isWindows
84+
? "chrome-headless-shell.exe"
85+
: "chrome-headless-shell";
86+
const binaryPath = join(subdir, binaryName);
87+
Deno.writeTextFileSync(binaryPath, "fake binary");
88+
89+
const found = findCftExecutable(tempDir, "chrome-headless-shell");
90+
assert(found !== undefined, "should find the binary");
91+
assert(
92+
found!.endsWith(binaryName),
93+
`found path should end with ${binaryName}, got: ${found}`,
94+
);
95+
} finally {
96+
safeRemoveSync(tempDir, { recursive: true });
97+
}
98+
});
99+
100+
unitTest("findCftExecutable - returns undefined for empty directory", async () => {
101+
const tempDir = Deno.makeTempDirSync();
102+
try {
103+
const found = findCftExecutable(tempDir, "chrome-headless-shell");
104+
assertEquals(found, undefined);
105+
} finally {
106+
safeRemoveSync(tempDir, { recursive: true });
107+
}
108+
});
109+
110+
unitTest("findCftExecutable - finds binary in nested structure", async () => {
111+
const tempDir = Deno.makeTempDirSync();
112+
try {
113+
const nested = join(tempDir, "chrome-headless-shell-win64", "subfolder");
114+
Deno.mkdirSync(nested, { recursive: true });
115+
const binaryName = isWindows
116+
? "chrome-headless-shell.exe"
117+
: "chrome-headless-shell";
118+
const binaryPath = join(nested, binaryName);
119+
Deno.writeTextFileSync(binaryPath, "fake binary");
120+
121+
const found = findCftExecutable(tempDir, "chrome-headless-shell");
122+
assert(found !== undefined, "should find the binary in nested dir");
123+
} finally {
124+
safeRemoveSync(tempDir, { recursive: true });
125+
}
126+
});
127+
128+
// Step 4: downloadAndExtractCft() — integration test, downloads ~50MB
129+
unitTest(
130+
"downloadAndExtractCft - downloads and extracts chrome-headless-shell",
131+
async () => {
132+
const release = await fetchLatestCftRelease();
133+
const { platform } = detectCftPlatform();
134+
const downloads = release.downloads["chrome-headless-shell"]!;
135+
const dl = downloads.find((d) => d.platform === platform);
136+
assert(dl, `No download found for platform ${platform}`);
137+
138+
const targetDir = Deno.makeTempDirSync();
139+
try {
140+
const mockContext: InstallContext = {
141+
workingDir: targetDir,
142+
info: (_msg: string) => {},
143+
withSpinner: async (_options, op) => {
144+
await op();
145+
},
146+
error: (_msg: string) => {},
147+
confirm: async (_msg: string) => true,
148+
download: async (_name: string, url: string, target: string) => {
149+
const resp = await fetch(url);
150+
if (!resp.ok) throw new Error(`Download failed: ${resp.status}`);
151+
const data = new Uint8Array(await resp.arrayBuffer());
152+
Deno.writeFileSync(target, data);
153+
},
154+
props: {},
155+
flags: {},
156+
};
157+
158+
await downloadAndExtractCft("Chrome Headless Shell", dl!.url, targetDir, mockContext, "chrome-headless-shell");
159+
160+
const found = findCftExecutable(targetDir, "chrome-headless-shell");
161+
assert(
162+
found !== undefined,
163+
"should find chrome-headless-shell after extraction",
164+
);
165+
} finally {
166+
safeRemoveSync(targetDir, { recursive: true });
167+
}
168+
},
169+
{
170+
ignore: runningInCI(),
171+
},
172+
);

0 commit comments

Comments
 (0)