camoufox-js 0.12.1 → 0.14.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.
package/README.md CHANGED
@@ -19,6 +19,11 @@ directory is ephemeral or persisted separately (similar to Playwright's
19
19
  CAMOUFOX_INSTALL_DIR=/opt/camoufox npx camoufox-js fetch
20
20
  ```
21
21
 
22
+ Each camoufox-js release is tested with one Camoufox build (`src/data-files/browser-pin.json`), and `fetch` installs
23
+ exactly that build into `browsers/<repo>/<version>-<build>/` inside that directory. This is the layout the Python
24
+ library uses, so both can share one cache. If the build is missing, the first launch downloads it, unless
25
+ `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` is set.
26
+
22
27
  ## Usage
23
28
 
24
29
  You can launch Playwright-controlled Camoufox using this package like this:
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The browser build this library is tested with, in the same format as the
3
+ * Python library's browser-pin.json. `camoufox fetch` installs and launches
4
+ * exactly this build unless the user explicitly chose another one.
5
+ */
6
+ export declare const PIN_FILE: string;
7
+ export interface BrowserPin {
8
+ tag: string;
9
+ repo: string;
10
+ repoName: string;
11
+ version: string;
12
+ build: string;
13
+ }
14
+ export declare function pinSpec(pin: BrowserPin): string;
15
+ export declare function loadPin(file?: string): BrowserPin | null;
16
+ /**
17
+ * The pin, unless the user chose a channel or a build themselves.
18
+ */
19
+ export declare function effectivePin(config: {
20
+ channel?: string;
21
+ pinned?: string;
22
+ }): BrowserPin | null;
23
+ export declare function pinMatches(pin: BrowserPin, repoName: string, version: string, build: string): boolean;
@@ -0,0 +1,42 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ const currentDir = import.meta.dirname ?? path.dirname(fileURLToPath(import.meta.url));
5
+ /**
6
+ * The browser build this library is tested with, in the same format as the
7
+ * Python library's browser-pin.json. `camoufox fetch` installs and launches
8
+ * exactly this build unless the user explicitly chose another one.
9
+ */
10
+ export const PIN_FILE = path.join(currentDir, "data-files", "browser-pin.json");
11
+ export function pinSpec(pin) {
12
+ return `${pin.version}-${pin.build}`;
13
+ }
14
+ export function loadPin(file = PIN_FILE) {
15
+ let data;
16
+ try {
17
+ data = JSON.parse(fs.readFileSync(file, "utf-8"));
18
+ }
19
+ catch {
20
+ return null;
21
+ }
22
+ if (!data?.tag)
23
+ return null;
24
+ return {
25
+ tag: data.tag,
26
+ repo: String(data.repo),
27
+ repoName: String(data.repo_name).toLowerCase(),
28
+ version: String(data.version),
29
+ build: String(data.build),
30
+ };
31
+ }
32
+ /**
33
+ * The pin, unless the user chose a channel or a build themselves.
34
+ */
35
+ export function effectivePin(config) {
36
+ return config.channel || config.pinned ? null : loadPin();
37
+ }
38
+ export function pinMatches(pin, repoName, version, build) {
39
+ return (repoName.toLowerCase() === pin.repoName &&
40
+ version === pin.version &&
41
+ build === pin.build);
42
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "tag": "v152.0.4-beta.30",
3
+ "repo": "daijro/camoufox",
4
+ "repo_name": "Official",
5
+ "version": "152.0.4",
6
+ "build": "beta.30"
7
+ }
@@ -71,6 +71,9 @@ export declare class VirtualDisplayNotSupported extends VirtualDisplayError {
71
71
  export declare class CamoufoxNotInstalled extends Error {
72
72
  constructor(message?: string);
73
73
  }
74
+ export declare class CorruptedDownload extends Error {
75
+ constructor(message?: string);
76
+ }
74
77
  export declare class FileNotFoundError extends Error {
75
78
  constructor(message?: string);
76
79
  }
@@ -145,6 +145,12 @@ export class CamoufoxNotInstalled extends Error {
145
145
  this.name = "CamoufoxNotInstalled";
146
146
  }
147
147
  }
148
+ export class CorruptedDownload extends Error {
149
+ constructor(message) {
150
+ super(message ?? "The download is corrupted.");
151
+ this.name = "CorruptedDownload";
152
+ }
153
+ }
148
154
  export class FileNotFoundError extends Error {
149
155
  constructor(message) {
150
156
  super(message ?? "File couldn't be found.");
@@ -0,0 +1,40 @@
1
+ import { Version } from "./pkgman.js";
2
+ /**
3
+ * The Python library's multi-version layout (multiversion.py), shared with it: builds live in
4
+ * INSTALL_DIR/browsers/<repo>/<version>-<build>[-<sha8>]/ and config.json records the active
5
+ * one and whether the user chose a channel or a build.
6
+ */
7
+ export declare const browsersDir: () => string;
8
+ export declare const configFile: () => string;
9
+ export declare const compatFlag: () => string;
10
+ export interface CamoufoxConfig {
11
+ active_version?: string | null;
12
+ channel?: string;
13
+ pinned?: string;
14
+ pinned_sha?: string;
15
+ [key: string]: unknown;
16
+ }
17
+ export declare function loadConfig(): CamoufoxConfig;
18
+ export declare function saveConfig(config: CamoufoxConfig): void;
19
+ export declare function setActive(relativePath: string): void;
20
+ export declare function getRepoName(githubRepo: string): string;
21
+ export declare function versionFolderName(version: string, build: string, sha256?: string): string;
22
+ export interface InstalledVersion {
23
+ repoName: string;
24
+ version: Version;
25
+ path: string;
26
+ relativePath: string;
27
+ isActive: boolean;
28
+ isPrerelease: boolean;
29
+ sha256?: string;
30
+ }
31
+ /**
32
+ * Builds in browsers/, sorted by repo, then newest first.
33
+ */
34
+ export declare function listInstalled(): InstalledVersion[];
35
+ /**
36
+ * The build to launch: the pinned one unless the user explicitly chose another, else the
37
+ * active one. Null when that build isn't installed. Unlike the Python library, it doesn't
38
+ * record the result in config.json, as launches may run concurrently or from a read-only dir.
39
+ */
40
+ export declare function getActivePath(): string | null;
@@ -0,0 +1,105 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { effectivePin, pinMatches } from "./browser-pin.js";
4
+ import { INSTALL_DIR, Version } from "./pkgman.js";
5
+ /**
6
+ * The Python library's multi-version layout (multiversion.py), shared with it: builds live in
7
+ * INSTALL_DIR/browsers/<repo>/<version>-<build>[-<sha8>]/ and config.json records the active
8
+ * one and whether the user chose a channel or a build.
9
+ */
10
+ // pkgman imports this module too, so paths are resolved on use rather than at load.
11
+ export const browsersDir = () => path.join(INSTALL_DIR.toString(), "browsers");
12
+ export const configFile = () => path.join(INSTALL_DIR.toString(), "config.json");
13
+ export const compatFlag = () => path.join(INSTALL_DIR.toString(), ".0.5_FLAG");
14
+ export function loadConfig() {
15
+ try {
16
+ return JSON.parse(fs.readFileSync(configFile(), "utf-8"));
17
+ }
18
+ catch {
19
+ return {};
20
+ }
21
+ }
22
+ export function saveConfig(config) {
23
+ fs.mkdirSync(INSTALL_DIR, { recursive: true });
24
+ // Through a rename, so a concurrent reader never sees a half-written file.
25
+ const tmp = `${configFile()}.${process.pid}.tmp`;
26
+ fs.writeFileSync(tmp, JSON.stringify(config, null, 2));
27
+ fs.renameSync(tmp, configFile());
28
+ }
29
+ export function setActive(relativePath) {
30
+ saveConfig({ ...loadConfig(), active_version: relativePath });
31
+ }
32
+ // Folder names of the Python library's repos.yml entries.
33
+ const REPO_NAMES = { "daijro/camoufox": "official" };
34
+ export function getRepoName(githubRepo) {
35
+ return REPO_NAMES[githubRepo] ?? githubRepo.split("/")[0].toLowerCase();
36
+ }
37
+ export function versionFolderName(version, build, sha256) {
38
+ const base = `${version}-${build}`;
39
+ return sha256 ? `${base}-${sha256.slice(0, 8)}` : base;
40
+ }
41
+ /**
42
+ * Builds in browsers/, sorted by repo, then newest first.
43
+ */
44
+ export function listInstalled() {
45
+ const installed = [];
46
+ if (!fs.existsSync(browsersDir()))
47
+ return installed;
48
+ const active = loadConfig().active_version;
49
+ for (const repo of fs.readdirSync(browsersDir(), { withFileTypes: true })) {
50
+ if (!repo.isDirectory() || repo.name.startsWith("."))
51
+ continue;
52
+ const repoDir = path.join(browsersDir(), repo.name);
53
+ for (const folder of fs.readdirSync(repoDir, { withFileTypes: true })) {
54
+ const dir = path.join(repoDir, folder.name);
55
+ const versionJson = path.join(dir, "version.json");
56
+ if (!folder.isDirectory() || !fs.existsSync(versionJson))
57
+ continue;
58
+ try {
59
+ const data = JSON.parse(fs.readFileSync(versionJson, "utf-8"));
60
+ const relativePath = `browsers/${repo.name}/${folder.name}`;
61
+ installed.push({
62
+ repoName: repo.name,
63
+ version: Version.fromPath(dir),
64
+ path: dir,
65
+ relativePath,
66
+ isActive: relativePath === active,
67
+ isPrerelease: data.prerelease ?? false,
68
+ sha256: data.sha256 ?? undefined,
69
+ });
70
+ }
71
+ catch {
72
+ // A corrupt version.json is not a usable install.
73
+ }
74
+ }
75
+ }
76
+ const compare = (a, b) => a.lessThan(b) ? -1 : b.lessThan(a) ? 1 : 0;
77
+ return installed.sort((a, b) => (a.repoName < b.repoName ? 1 : a.repoName > b.repoName ? -1 : 0) ||
78
+ compare(b.version, a.version));
79
+ }
80
+ /**
81
+ * The build to launch: the pinned one unless the user explicitly chose another, else the
82
+ * active one. Null when that build isn't installed. Unlike the Python library, it doesn't
83
+ * record the result in config.json, as launches may run concurrently or from a read-only dir.
84
+ */
85
+ export function getActivePath() {
86
+ const config = loadConfig();
87
+ const active = config.active_version;
88
+ const pin = effectivePin(config);
89
+ if (pin) {
90
+ const inst = listInstalled().find((v) => pinMatches(pin, v.repoName, v.version.version ?? "", v.version.release));
91
+ return inst?.path ?? null;
92
+ }
93
+ if (active) {
94
+ const activePath = path.join(INSTALL_DIR.toString(), active);
95
+ if (fs.existsSync(path.join(activePath, "version.json"))) {
96
+ return activePath;
97
+ }
98
+ }
99
+ if (!config.channel && !config.pinned) {
100
+ const [newest] = listInstalled();
101
+ if (newest)
102
+ return newest.path;
103
+ }
104
+ return null;
105
+ }
package/dist/pkgman.d.ts CHANGED
@@ -12,7 +12,7 @@ export declare const LOCAL_DATA: PathLike;
12
12
  export declare const OS_ARCH_MATRIX: {
13
13
  [key: string]: string[];
14
14
  };
15
- declare class Version {
15
+ export declare class Version {
16
16
  release: string;
17
17
  version?: string;
18
18
  sorted_rel: number[];
@@ -30,7 +30,8 @@ export declare class GitHubDownloader {
30
30
  githubRepo: string;
31
31
  apiUrl: string;
32
32
  constructor(githubRepo: string);
33
- checkAsset(asset: any): any;
33
+ checkAsset(asset: any, _release?: any): any;
34
+ releasesUrl(): string;
34
35
  missingAssetError(): void;
35
36
  getAsset({ retries }?: {
36
37
  retries: number;
@@ -41,9 +42,13 @@ export declare class CamoufoxFetcher extends GitHubDownloader {
41
42
  _version_obj?: Version;
42
43
  pattern: RegExp;
43
44
  _url?: string;
45
+ isPrerelease: boolean;
46
+ sha256?: string;
47
+ createdAt?: string;
44
48
  constructor();
45
49
  init(): Promise<void>;
46
- checkAsset(asset: any): [Version, string] | null;
50
+ releasesUrl(): string;
51
+ checkAsset(asset: any, release?: any): [Version, string] | null;
47
52
  missingAssetError(): void;
48
53
  static getPlatformArch(): string;
49
54
  fetchLatest(): Promise<void>;
@@ -52,6 +57,7 @@ export declare class CamoufoxFetcher extends GitHubDownloader {
52
57
  static cleanup(): boolean;
53
58
  setVersion(destDir?: string): void;
54
59
  private static removeLeftovers;
60
+ private static activate;
55
61
  install(): Promise<void>;
56
62
  get url(): string;
57
63
  get version(): string;
@@ -59,11 +65,18 @@ export declare class CamoufoxFetcher extends GitHubDownloader {
59
65
  get verstr(): string;
60
66
  }
61
67
  export declare function installedVerStr(): string;
62
- export declare function camoufoxPath(downloadIfMissing?: boolean): PathLike;
68
+ /**
69
+ * @param _downloadIfMissing Ignored, downloads happen in {@link ensureCamoufoxInstalled}.
70
+ */
71
+ export declare function camoufoxPath(_downloadIfMissing?: boolean): PathLike;
72
+ /**
73
+ * Installs the pinned build when no supported install is available, as the Python
74
+ * library does on launch. An explicitly chosen build is never replaced.
75
+ */
76
+ export declare function ensureCamoufoxInstalled(): Promise<void>;
63
77
  export declare function getPath(file: string): string;
64
78
  export declare function launchPath(): string;
65
79
  export declare function webdl(url: string, desc?: string, bar?: boolean, buffer?: Writable | null, { retries }?: {
66
80
  retries: number;
67
81
  }): Promise<Buffer>;
68
82
  export declare function unzip(zipFile: Buffer, extractPath: string, desc?: string, bar?: boolean): Promise<void>;
69
- export {};
package/dist/pkgman.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { execFileSync } from "node:child_process";
2
+ import { createHash } from "node:crypto";
2
3
  import * as fs from "node:fs";
3
4
  import { createRequire } from "node:module";
4
5
  import * as os from "node:os";
@@ -9,7 +10,9 @@ import AdmZip from "adm-zip";
9
10
  import cliProgress from "cli-progress";
10
11
  import prettyBytes from "pretty-bytes";
11
12
  import { CONSTRAINTS } from "./__version__.js";
12
- import { CamoufoxNotInstalled, FileNotFoundError, MissingRelease, UnsupportedArchitecture, UnsupportedOS, UnsupportedVersion, } from "./exceptions.js";
13
+ import { effectivePin, pinMatches, pinSpec } from "./browser-pin.js";
14
+ import { CamoufoxNotInstalled, CorruptedDownload, FileNotFoundError, MissingRelease, UnsupportedArchitecture, UnsupportedOS, UnsupportedVersion, } from "./exceptions.js";
15
+ import { browsersDir, compatFlag, getActivePath, getRepoName, loadConfig, setActive, versionFolderName, } from "./multiversion.js";
13
16
  const ARCH_MAP = {
14
17
  x64: "x86_64",
15
18
  ia32: "i686",
@@ -67,7 +70,7 @@ function isPlaywright161OrNewer() {
67
70
  return false;
68
71
  }
69
72
  }
70
- class Version {
73
+ export class Version {
71
74
  release;
72
75
  version;
73
76
  sorted_rel;
@@ -109,7 +112,8 @@ class Version {
109
112
  throw new FileNotFoundError(`Version information not found at ${versionPath}. Please run \`camoufox fetch\` to install.`);
110
113
  }
111
114
  const versionData = JSON.parse(fs.readFileSync(versionPath, "utf-8"));
112
- return new Version(versionData.release, versionData.version);
115
+ // The flat layout wrote `release`, the versioned one (shared with the Python library) writes `build`.
116
+ return new Version(versionData.build ?? versionData.release, versionData.version);
113
117
  }
114
118
  static isSupportedPath(path) {
115
119
  return Version.fromPath(path).isSupported();
@@ -132,19 +136,23 @@ export class GitHubDownloader {
132
136
  this.githubRepo = githubRepo;
133
137
  this.apiUrl = `https://api.github.com/repos/${githubRepo}/releases`;
134
138
  }
135
- checkAsset(asset) {
139
+ checkAsset(asset, _release) {
136
140
  return asset.browser_download_url;
137
141
  }
142
+ releasesUrl() {
143
+ return this.apiUrl;
144
+ }
138
145
  missingAssetError() {
139
146
  throw new MissingRelease(`Could not find a release asset in ${this.githubRepo}.`);
140
147
  }
141
148
  async getAsset({ retries } = { retries: 5 }) {
142
149
  let attempts = 0;
143
150
  let response;
151
+ const url = this.releasesUrl();
144
152
  while (attempts < retries) {
145
153
  try {
146
- response = await fetch(this.apiUrl, {
147
- headers: getAuthorizationHeaders(this.apiUrl),
154
+ response = await fetch(url, {
155
+ headers: getAuthorizationHeaders(url),
148
156
  });
149
157
  if (response.ok)
150
158
  break;
@@ -156,14 +164,15 @@ export class GitHubDownloader {
156
164
  attempts++;
157
165
  }
158
166
  if (!response || !response.ok) {
159
- throw new Error(`Failed to fetch releases from ${this.apiUrl} after ${retries} attempts`);
167
+ throw new Error(`Failed to fetch releases from ${url} after ${retries} attempts`);
160
168
  }
161
- const releases = await response.json();
169
+ const data = await response.json();
170
+ const releases = Array.isArray(data) ? data : [data];
162
171
  for (const release of releases) {
163
172
  if (release.prerelease || release.draft)
164
173
  continue;
165
174
  for (const asset of release.assets) {
166
- const data = this.checkAsset(asset);
175
+ const data = this.checkAsset(asset, release);
167
176
  if (data) {
168
177
  return data;
169
178
  }
@@ -177,6 +186,9 @@ export class CamoufoxFetcher extends GitHubDownloader {
177
186
  _version_obj;
178
187
  pattern;
179
188
  _url;
189
+ isPrerelease = false;
190
+ sha256;
191
+ createdAt;
180
192
  constructor() {
181
193
  super("daijro/camoufox");
182
194
  this.arch = CamoufoxFetcher.getPlatformArch();
@@ -185,13 +197,30 @@ export class CamoufoxFetcher extends GitHubDownloader {
185
197
  async init() {
186
198
  await this.fetchLatest();
187
199
  }
188
- checkAsset(asset) {
200
+ releasesUrl() {
201
+ const pin = effectivePin(loadConfig());
202
+ return pin && getRepoName(this.githubRepo) === pin.repoName
203
+ ? `${this.apiUrl}/tags/${pin.tag}`
204
+ : this.apiUrl;
205
+ }
206
+ checkAsset(asset, release) {
189
207
  const match = asset.name.match(this.pattern);
190
208
  if (!match)
191
209
  return null;
192
210
  const version = new Version(match[2], match[1]);
193
211
  if (!version.isSupported())
194
212
  return null;
213
+ // Install exactly the tested build, unless the user explicitly chose another one.
214
+ const pin = effectivePin(loadConfig());
215
+ if (pin &&
216
+ !pinMatches(pin, getRepoName(this.githubRepo), match[1], match[2])) {
217
+ return null;
218
+ }
219
+ this.isPrerelease = Boolean(release?.prerelease);
220
+ this.sha256 = asset.digest?.startsWith("sha256:")
221
+ ? asset.digest.slice("sha256:".length)
222
+ : undefined;
223
+ this.createdAt = asset.created_at;
195
224
  return [version, asset.browser_download_url];
196
225
  }
197
226
  missingAssetError() {
@@ -233,44 +262,79 @@ export class CamoufoxFetcher extends GitHubDownloader {
233
262
  return false;
234
263
  }
235
264
  setVersion(destDir = INSTALL_DIR.toString()) {
236
- fs.writeFileSync(path.join(destDir, "version.json"), JSON.stringify({ version: this.version, release: this.release }));
265
+ fs.writeFileSync(path.join(destDir, "version.json"), JSON.stringify({
266
+ version: this.version,
267
+ build: this.release,
268
+ prerelease: this.isPrerelease,
269
+ sha256: this.sha256 ?? null,
270
+ created_at: this.createdAt ?? null,
271
+ }));
237
272
  }
238
273
  // Remove staging dirs left behind by an interrupted install.
239
- static removeLeftovers(installDir) {
240
- const parent = path.dirname(installDir);
241
- const prefix = `${path.basename(installDir)}.staging-`;
242
- for (const name of fs.readdirSync(parent)) {
243
- if (name.startsWith(prefix)) {
244
- fs.rmSync(path.join(parent, name), { recursive: true, force: true });
274
+ static removeLeftovers(dir, prefix) {
275
+ for (const name of fs.readdirSync(dir)) {
276
+ // Fresh ones may belong to an install still running in another process.
277
+ if (name.startsWith(prefix) && isStale(path.join(dir, name))) {
278
+ fs.rmSync(path.join(dir, name), { recursive: true, force: true });
245
279
  }
246
280
  }
247
281
  }
282
+ static activate(installDir, relativePath) {
283
+ setActive(relativePath);
284
+ removeLegacyInstall(installDir);
285
+ }
248
286
  async install() {
249
287
  await this.init();
250
- // Resolve a symlinked install dir so the swap replaces its target, not the link.
251
- const installDir = fs.existsSync(INSTALL_DIR)
252
- ? fs.realpathSync(INSTALL_DIR)
253
- : INSTALL_DIR.toString();
254
- fs.mkdirSync(path.dirname(installDir), { recursive: true });
255
- CamoufoxFetcher.removeLeftovers(installDir);
256
- // Staged next to the install dir so the final rename stays on one filesystem.
288
+ const folder = versionFolderName(this.version, this.release, this.sha256);
289
+ const relativePath = `browsers/${getRepoName(this.githubRepo)}/${folder}`;
290
+ const installDir = path.join(INSTALL_DIR.toString(), relativePath);
291
+ fs.mkdirSync(browsersDir(), { recursive: true });
292
+ // Tells the Python library this directory uses its layout, so it doesn't wipe it.
293
+ fs.writeFileSync(compatFlag(), "");
294
+ if (fs.existsSync(path.join(installDir, "version.json"))) {
295
+ console.log(`Camoufox v${this.verstr} is already installed.`);
296
+ CamoufoxFetcher.activate(installDir, relativePath);
297
+ return;
298
+ }
299
+ // Older releases staged next to the (symlink-resolved) install dir.
300
+ const root = fs.realpathSync(INSTALL_DIR);
301
+ CamoufoxFetcher.removeLeftovers(path.dirname(root), `${path.basename(root)}.staging-`);
302
+ CamoufoxFetcher.removeLeftovers(browsersDir(), ".staging-");
303
+ // Staged inside browsers/ so the final rename stays on one filesystem. Dot-prefixed
304
+ // entries are skipped by install listings, including the Python library's.
257
305
  // Set up outside the try so finally can always tear down the ~600MB staging dirs.
258
- const stagingDir = fs.mkdtempSync(`${installDir}.staging-`);
306
+ const stagingDir = fs.mkdtempSync(path.join(browsersDir(), ".staging-"));
259
307
  const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "camoufox-"));
260
308
  const tempFilePath = path.join(tempDir, "camoufox.zip");
261
309
  const tempFileStream = fs.createWriteStream(tempFilePath);
262
310
  try {
263
311
  await webdl(this.url, "Downloading Camoufox...", true, tempFileStream);
264
312
  await new Promise((r) => tempFileStream.close(r));
313
+ await verifySha256(tempFilePath, this.sha256, `Camoufox v${this.verstr}`);
265
314
  await this.extractZip(tempFilePath, stagingDir);
266
315
  this.setVersion(stagingDir);
267
316
  if (OS_NAME !== "win") {
268
317
  execFileSync("chmod", ["-R", "755", stagingDir]);
269
318
  }
270
- // Replace the previous install only once the new one is complete.
271
- fs.rmSync(installDir, { recursive: true, force: true });
272
- fs.renameSync(stagingDir, installDir);
273
- console.log("Camoufox successfully installed.");
319
+ fs.mkdirSync(path.dirname(installDir), { recursive: true });
320
+ try {
321
+ fs.renameSync(stagingDir, installDir);
322
+ }
323
+ catch (e) {
324
+ // Unless another process finished the same install in the meantime, the target is
325
+ // an install in progress (the Python library extracts in place) or an abandoned one.
326
+ if (!fs.existsSync(path.join(installDir, "version.json"))) {
327
+ if (!fs.existsSync(installDir))
328
+ throw e;
329
+ if (!isStale(installDir)) {
330
+ throw new Error(`Another process is installing Camoufox into ${installDir}, try again once it finishes.`);
331
+ }
332
+ fs.rmSync(installDir, { recursive: true, force: true });
333
+ fs.renameSync(stagingDir, installDir);
334
+ }
335
+ }
336
+ CamoufoxFetcher.activate(installDir, relativePath);
337
+ console.log(`Camoufox successfully installed to ${installDir}.`);
274
338
  }
275
339
  catch (e) {
276
340
  console.error(`Error installing Camoufox: ${e}`);
@@ -329,27 +393,86 @@ function userCacheDir(appName) {
329
393
  return path.join(xdg && path.isAbsolute(xdg) ? xdg : path.join(os.homedir(), ".cache"), appName);
330
394
  }
331
395
  }
332
- export function installedVerStr() {
333
- return Version.fromPath().fullString;
396
+ // Root entries of the layout shared with the Python library, never part of a flat install.
397
+ const SHARED_ENTRIES = new Set([
398
+ ".0.5_FLAG",
399
+ "addons",
400
+ "browsers",
401
+ "config.json",
402
+ "fontconfig",
403
+ "geoip",
404
+ "repo_cache.json",
405
+ ]);
406
+ // Older than any download or extraction still in progress.
407
+ function isStale(p) {
408
+ try {
409
+ return Date.now() - fs.statSync(p).mtimeMs > 24 * 60 * 60 * 1000;
410
+ }
411
+ catch {
412
+ return false;
413
+ }
334
414
  }
335
- export function camoufoxPath(downloadIfMissing = true) {
336
- // Ensure the directory exists and is not empty
337
- if (!fs.existsSync(INSTALL_DIR) || fs.readdirSync(INSTALL_DIR).length === 0) {
338
- if (!downloadIfMissing) {
339
- throw new Error(`Camoufox executable not found at ${INSTALL_DIR}`);
415
+ /**
416
+ * Removes a flat install of an older release from the root of INSTALL_DIR. It holds the
417
+ * same top-level entries as the build just installed into `installDir`.
418
+ */
419
+ function removeLegacyInstall(installDir) {
420
+ const root = INSTALL_DIR.toString();
421
+ if (!fs.existsSync(path.join(root, "version.json")))
422
+ return;
423
+ try {
424
+ for (const name of fs.readdirSync(installDir)) {
425
+ if (!SHARED_ENTRIES.has(name)) {
426
+ fs.rmSync(path.join(root, name), { recursive: true, force: true });
427
+ }
340
428
  }
341
429
  }
342
- else if (fs.existsSync(INSTALL_DIR) &&
343
- Version.isSupportedPath(INSTALL_DIR)) {
344
- return INSTALL_DIR;
430
+ catch (e) {
431
+ // The new install is complete; a leftover (e.g. a file still in use on Windows) must not fail it.
432
+ console.warn(`Failed to remove the previous install at ${root}: ${e}`);
345
433
  }
346
- else {
434
+ }
435
+ /**
436
+ * The install a launch uses: the pinned (or explicitly chosen) build from browsers/,
437
+ * else a flat install of an older release at the root of INSTALL_DIR.
438
+ */
439
+ function activeInstallDir() {
440
+ return getActivePath() ?? INSTALL_DIR.toString();
441
+ }
442
+ export function installedVerStr() {
443
+ return Version.fromPath(activeInstallDir()).fullString;
444
+ }
445
+ /**
446
+ * @param _downloadIfMissing Ignored, downloads happen in {@link ensureCamoufoxInstalled}.
447
+ */
448
+ export function camoufoxPath(_downloadIfMissing = true) {
449
+ const installDir = activeInstallDir();
450
+ if (!fs.existsSync(path.join(installDir, "version.json"))) {
451
+ const pin = effectivePin(loadConfig());
452
+ throw new CamoufoxNotInstalled(`Camoufox${pin ? ` v${pinSpec(pin)}` : ""} is not installed at ${INSTALL_DIR}. Please run \`camoufox fetch\` to install.`);
453
+ }
454
+ if (!Version.isSupportedPath(installDir)) {
347
455
  throw new UnsupportedVersion(`Camoufox v${installedVerStr()} is not supported by this library (supported range: ${SUPPORTED_RANGE}). Please run \`camoufox fetch\` to install a supported version.`);
348
456
  }
349
- // Install and recheck
350
- const fetcher = new CamoufoxFetcher();
351
- fetcher.install().then(() => camoufoxPath());
352
- return INSTALL_DIR;
457
+ return installDir;
458
+ }
459
+ let pendingInstall;
460
+ /**
461
+ * Installs the pinned build when no supported install is available, as the Python
462
+ * library does on launch. An explicitly chosen build is never replaced.
463
+ */
464
+ export async function ensureCamoufoxInstalled() {
465
+ if (!effectivePin(loadConfig()))
466
+ return;
467
+ const installDir = activeInstallDir();
468
+ if (fs.existsSync(path.join(installDir, "version.json")) &&
469
+ Version.isSupportedPath(installDir)) {
470
+ return;
471
+ }
472
+ pendingInstall ??= new CamoufoxFetcher().install().finally(() => {
473
+ pendingInstall = undefined;
474
+ });
475
+ await pendingInstall;
353
476
  }
354
477
  export function getPath(file) {
355
478
  if (OS_NAME === "mac") {
@@ -411,6 +534,20 @@ export async function webdl(url, desc = "", bar = true, buffer = null, { retries
411
534
  }
412
535
  return Buffer.concat(chunks);
413
536
  }
537
+ async function verifySha256(file, expected, desc) {
538
+ if (!expected) {
539
+ console.warn(`No sha256 published for ${desc}, skipping verification.`);
540
+ return;
541
+ }
542
+ const hash = createHash("sha256");
543
+ for await (const chunk of fs.createReadStream(file)) {
544
+ hash.update(chunk);
545
+ }
546
+ const actual = hash.digest("hex");
547
+ if (actual !== expected.toLowerCase()) {
548
+ throw new CorruptedDownload(`Checksum mismatch for ${desc}: expected sha256 ${expected.toLowerCase()}, got ${actual}.`);
549
+ }
550
+ }
414
551
  export async function unzip(zipFile, extractPath, desc, bar = true) {
415
552
  const zip = new AdmZip(zipFile);
416
553
  const zipEntries = zip.getEntries();
package/dist/utils.js CHANGED
@@ -10,7 +10,7 @@ import { fromBrowserforge, generateFingerprint, SUPPORTED_OS, } from "./fingerpr
10
10
  import { publicIP, validIPv4, validIPv6 } from "./ip.js";
11
11
  import { geoipAllowed, getGeolocation, handleLocales } from "./locale.js";
12
12
  import FONTS from "./mappings/fonts.config.js";
13
- import { getPath, installedVerStr, launchPath, OS_NAME } from "./pkgman.js";
13
+ import { ensureCamoufoxInstalled, getPath, installedVerStr, launchPath, OS_NAME, } from "./pkgman.js";
14
14
  import { LeakWarning } from "./warnings.js";
15
15
  import { sampleWebGL } from "./webgl/sample.js";
16
16
  // Camoufox preferences to cache previous pages and requests
@@ -381,6 +381,10 @@ export async function launchOptions({ config, os, block_images, block_webrtc, bl
381
381
  if (!operatingSystems && webgl_config) {
382
382
  throw new Error("OS must be set when using webgl_config");
383
383
  }
384
+ if (!executable_path &&
385
+ !getAsBooleanFromENV("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD", false)) {
386
+ await ensureCamoufoxInstalled();
387
+ }
384
388
  // Add the default addons
385
389
  await addDefaultAddons(addons, exclude_addons);
386
390
  // Confirm all addon paths are valid
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "camoufox-js",
3
- "version": "0.12.1",
3
+ "version": "0.14.0",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "bin": "dist/__main__.js",
@@ -18,7 +18,7 @@
18
18
  "url": "https://github.com/apify/camoufox-js/issues"
19
19
  },
20
20
  "engines": {
21
- "node": ">= 22"
21
+ "node": ">= 22.13"
22
22
  },
23
23
  "license": "MPL-2.0",
24
24
  "description": "Experimental JS port of Camoufox for Python.",
@@ -27,7 +27,7 @@
27
27
  "better-sqlite3": "^13.0.1",
28
28
  "cli-progress": "^3.12.0",
29
29
  "commander": "^14.0.0",
30
- "fingerprint-generator": "^2.1.86",
30
+ "fingerprint-generator": "^3.0.0",
31
31
  "glob": "^13.0.0",
32
32
  "impit": "^0.14.1",
33
33
  "language-tags": "^2.0.1",