bexxcv 0.0.0-stage → 1.0.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 +493 -2
- package/dist/__main__.d.ts +2 -0
- package/dist/__main__.js +156 -0
- package/dist/__version__.d.ts +5 -0
- package/dist/__version__.js +5 -0
- package/dist/addons.d.ts +7 -0
- package/dist/addons.js +56 -0
- package/dist/browser-pin.d.ts +15 -0
- package/dist/browser-pin.js +34 -0
- package/dist/data-files/browser-pin.json +7 -0
- package/dist/data-files/territoryInfo.xml +2024 -0
- package/dist/exceptions.d.ts +79 -0
- package/dist/exceptions.js +159 -0
- package/dist/fingerprints.d.ts +5 -0
- package/dist/fingerprints.js +92 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/ip.d.ts +23 -0
- package/dist/ip.js +98 -0
- package/dist/locale.d.ts +26 -0
- package/dist/locale.js +292 -0
- package/dist/mappings/browserforge.config.d.ts +44 -0
- package/dist/mappings/browserforge.config.js +43 -0
- package/dist/mappings/fonts.config.d.ts +6 -0
- package/dist/mappings/fonts.config.js +822 -0
- package/dist/mappings/warnings.config.d.ts +16 -0
- package/dist/mappings/warnings.config.js +28 -0
- package/dist/multiversion.d.ts +27 -0
- package/dist/multiversion.js +88 -0
- package/dist/pkgman.d.ts +69 -0
- package/dist/pkgman.js +529 -0
- package/dist/selfupdate.d.ts +8 -0
- package/dist/selfupdate.js +84 -0
- package/dist/server.d.ts +3 -0
- package/dist/server.js +6 -0
- package/dist/sync_api.d.ts +11 -0
- package/dist/sync_api.js +47 -0
- package/dist/utils.d.ts +45 -0
- package/dist/utils.js +514 -0
- package/dist/virtdisplay.d.ts +12 -0
- package/dist/virtdisplay.js +139 -0
- package/dist/warnings.d.ts +4 -0
- package/dist/warnings.js +33 -0
- package/dist/webgl/sample.d.ts +19 -0
- package/dist/webgl/sample.js +103 -0
- package/dist/xvfb.d.ts +6 -0
- package/dist/xvfb.js +25 -0
- package/package.json +103 -5
package/dist/pkgman.js
ADDED
|
@@ -0,0 +1,529 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import * as fs from "node:fs";
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
import * as os from "node:os";
|
|
6
|
+
import * as path from "node:path";
|
|
7
|
+
import { setTimeout } from "node:timers/promises";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
import AdmZip from "adm-zip";
|
|
10
|
+
import cliProgress from "cli-progress";
|
|
11
|
+
import prettyBytes from "pretty-bytes";
|
|
12
|
+
import { CONSTRAINTS } from "./__version__.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";
|
|
16
|
+
const ARCH_MAP = {
|
|
17
|
+
x64: "x86_64",
|
|
18
|
+
ia32: "i686",
|
|
19
|
+
arm64: "arm64",
|
|
20
|
+
arm: "arm64",
|
|
21
|
+
};
|
|
22
|
+
const OS_MAP = {
|
|
23
|
+
darwin: "mac",
|
|
24
|
+
linux: "lin",
|
|
25
|
+
win32: "win",
|
|
26
|
+
};
|
|
27
|
+
function getAuthorizationHeaders(url) {
|
|
28
|
+
const githubToken = process.env.GITHUB_TOKEN;
|
|
29
|
+
if (!githubToken)
|
|
30
|
+
return {};
|
|
31
|
+
const host = new URL(url).hostname;
|
|
32
|
+
if (host === "api.github.com" || host === "github.com") {
|
|
33
|
+
return { Authorization: `Bearer ${githubToken}` };
|
|
34
|
+
}
|
|
35
|
+
return {};
|
|
36
|
+
}
|
|
37
|
+
if (!(process.platform in OS_MAP)) {
|
|
38
|
+
throw new UnsupportedOS(`OS ${process.platform} is not supported`);
|
|
39
|
+
}
|
|
40
|
+
export const OS_NAME = OS_MAP[process.platform];
|
|
41
|
+
const currentDir = import.meta.dirname ?? path.dirname(fileURLToPath(import.meta.url));
|
|
42
|
+
export const INSTALL_DIR = process.env.CAMOUFOX_INSTALL_DIR
|
|
43
|
+
? path.resolve(process.env.CAMOUFOX_INSTALL_DIR)
|
|
44
|
+
: userCacheDir("camoufox");
|
|
45
|
+
const formatBytes = (v, _, type) => type === "total" || type === "value" ? prettyBytes(v) : String(v);
|
|
46
|
+
export const LOCAL_DATA = path.join(currentDir, "data-files");
|
|
47
|
+
export const OS_ARCH_MATRIX = {
|
|
48
|
+
win: ["x86_64", "i686"],
|
|
49
|
+
mac: ["x86_64", "arm64"],
|
|
50
|
+
lin: ["x86_64", "arm64", "i686"],
|
|
51
|
+
};
|
|
52
|
+
const LAUNCH_FILE = {
|
|
53
|
+
win: "camoufox.exe",
|
|
54
|
+
mac: "../MacOS/camoufox",
|
|
55
|
+
lin: "camoufox-bin",
|
|
56
|
+
};
|
|
57
|
+
function isPlaywright161OrNewer() {
|
|
58
|
+
try {
|
|
59
|
+
const { version } = createRequire(import.meta.url)("playwright-core/package.json");
|
|
60
|
+
const [major, minor] = version.split(".").map(Number);
|
|
61
|
+
return major > 1 || (major === 1 && minor >= 61);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
export class Version {
|
|
68
|
+
release;
|
|
69
|
+
version;
|
|
70
|
+
sorted_rel;
|
|
71
|
+
constructor(release, version) {
|
|
72
|
+
this.release = release;
|
|
73
|
+
this.version = version;
|
|
74
|
+
this.sorted_rel = this.buildSortedRel();
|
|
75
|
+
}
|
|
76
|
+
buildSortedRel() {
|
|
77
|
+
const parts = this.release
|
|
78
|
+
.split(".")
|
|
79
|
+
.map((x) => Number.isNaN(Number(x)) ? x.charCodeAt(0) - 1024 : Number(x));
|
|
80
|
+
while (parts.length < 5) {
|
|
81
|
+
parts.push(0);
|
|
82
|
+
}
|
|
83
|
+
return parts;
|
|
84
|
+
}
|
|
85
|
+
get fullString() {
|
|
86
|
+
return `${this.version}-${this.release}`;
|
|
87
|
+
}
|
|
88
|
+
equals(other) {
|
|
89
|
+
return this.sorted_rel.join(".") === other.sorted_rel.join(".");
|
|
90
|
+
}
|
|
91
|
+
lessThan(other) {
|
|
92
|
+
for (let i = 0; i < this.sorted_rel.length; i++) {
|
|
93
|
+
if (this.sorted_rel[i] < other.sorted_rel[i])
|
|
94
|
+
return true;
|
|
95
|
+
if (this.sorted_rel[i] > other.sorted_rel[i])
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
isSupported() {
|
|
101
|
+
return !this.lessThan(VERSION_MIN) && this.lessThan(VERSION_MAX);
|
|
102
|
+
}
|
|
103
|
+
static fromPath(filePath = INSTALL_DIR) {
|
|
104
|
+
const versionPath = path.join(filePath.toString(), "version.json");
|
|
105
|
+
if (!fs.existsSync(versionPath)) {
|
|
106
|
+
throw new FileNotFoundError(`Version information not found at ${versionPath}. Please run \`bexxcv fetch\` to install.`);
|
|
107
|
+
}
|
|
108
|
+
const versionData = JSON.parse(fs.readFileSync(versionPath, "utf-8"));
|
|
109
|
+
return new Version(versionData.build ?? versionData.release, versionData.version);
|
|
110
|
+
}
|
|
111
|
+
static isSupportedPath(path) {
|
|
112
|
+
return Version.fromPath(path).isSupported();
|
|
113
|
+
}
|
|
114
|
+
static buildMinMax() {
|
|
115
|
+
return [
|
|
116
|
+
new Version(isPlaywright161OrNewer()
|
|
117
|
+
? CONSTRAINTS.PLAYWRIGHT_1_61_MIN_VERSION
|
|
118
|
+
: CONSTRAINTS.MIN_VERSION),
|
|
119
|
+
new Version(CONSTRAINTS.MAX_VERSION),
|
|
120
|
+
];
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const [VERSION_MIN, VERSION_MAX] = Version.buildMinMax();
|
|
124
|
+
const SUPPORTED_RANGE = `>=${VERSION_MIN.release}, <${VERSION_MAX.release}`;
|
|
125
|
+
export class GitHubDownloader {
|
|
126
|
+
githubRepo;
|
|
127
|
+
apiUrl;
|
|
128
|
+
constructor(githubRepo) {
|
|
129
|
+
this.githubRepo = githubRepo;
|
|
130
|
+
this.apiUrl = `https://api.github.com/repos/${githubRepo}/releases`;
|
|
131
|
+
}
|
|
132
|
+
checkAsset(asset, _release) {
|
|
133
|
+
return asset.browser_download_url;
|
|
134
|
+
}
|
|
135
|
+
releasesUrl() {
|
|
136
|
+
return this.apiUrl;
|
|
137
|
+
}
|
|
138
|
+
missingAssetError() {
|
|
139
|
+
throw new MissingRelease(`Could not find a release asset in ${this.githubRepo}.`);
|
|
140
|
+
}
|
|
141
|
+
async getAsset({ retries } = { retries: 5 }) {
|
|
142
|
+
let attempts = 0;
|
|
143
|
+
let response;
|
|
144
|
+
const url = this.releasesUrl();
|
|
145
|
+
while (attempts < retries) {
|
|
146
|
+
try {
|
|
147
|
+
response = await fetch(url, {
|
|
148
|
+
headers: getAuthorizationHeaders(url),
|
|
149
|
+
});
|
|
150
|
+
if (response.ok)
|
|
151
|
+
break;
|
|
152
|
+
}
|
|
153
|
+
catch (e) {
|
|
154
|
+
console.error(e, `retrying (${attempts + 1}/${retries})...`);
|
|
155
|
+
const jitter = Math.random() * 500;
|
|
156
|
+
const delayMs = Math.min(2_000 * 2 ** attempts + jitter, 30_000);
|
|
157
|
+
await setTimeout(delayMs);
|
|
158
|
+
}
|
|
159
|
+
attempts++;
|
|
160
|
+
}
|
|
161
|
+
if (!response || !response.ok) {
|
|
162
|
+
throw new Error(`Failed to fetch releases from ${url} after ${retries} attempts`);
|
|
163
|
+
}
|
|
164
|
+
const data = await response.json();
|
|
165
|
+
const releases = Array.isArray(data) ? data : [data];
|
|
166
|
+
for (const release of releases) {
|
|
167
|
+
if (release.prerelease || release.draft)
|
|
168
|
+
continue;
|
|
169
|
+
for (const asset of release.assets) {
|
|
170
|
+
const data = this.checkAsset(asset, release);
|
|
171
|
+
if (data) {
|
|
172
|
+
return data;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
this.missingAssetError();
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
export class CamoufoxFetcher extends GitHubDownloader {
|
|
180
|
+
arch;
|
|
181
|
+
_version_obj;
|
|
182
|
+
pattern;
|
|
183
|
+
_url;
|
|
184
|
+
isPrerelease = false;
|
|
185
|
+
sha256;
|
|
186
|
+
createdAt;
|
|
187
|
+
constructor() {
|
|
188
|
+
super("daijro/camoufox");
|
|
189
|
+
this.arch = CamoufoxFetcher.getPlatformArch();
|
|
190
|
+
this.pattern = new RegExp(`camoufox-(.+)-(.+)-${OS_NAME}\\.${this.arch}\\.zip`);
|
|
191
|
+
}
|
|
192
|
+
async init() {
|
|
193
|
+
await this.fetchLatest();
|
|
194
|
+
}
|
|
195
|
+
releasesUrl() {
|
|
196
|
+
const pin = effectivePin(loadConfig());
|
|
197
|
+
return pin && getRepoName(this.githubRepo) === pin.repoName
|
|
198
|
+
? `${this.apiUrl}/tags/${pin.tag}`
|
|
199
|
+
: this.apiUrl;
|
|
200
|
+
}
|
|
201
|
+
checkAsset(asset, release) {
|
|
202
|
+
const match = asset.name.match(this.pattern);
|
|
203
|
+
if (!match)
|
|
204
|
+
return null;
|
|
205
|
+
const version = new Version(match[2], match[1]);
|
|
206
|
+
if (!version.isSupported())
|
|
207
|
+
return null;
|
|
208
|
+
const pin = effectivePin(loadConfig());
|
|
209
|
+
if (pin &&
|
|
210
|
+
!pinMatches(pin, getRepoName(this.githubRepo), match[1], match[2])) {
|
|
211
|
+
return null;
|
|
212
|
+
}
|
|
213
|
+
this.isPrerelease = Boolean(release?.prerelease);
|
|
214
|
+
this.sha256 = asset.digest?.startsWith("sha256:")
|
|
215
|
+
? asset.digest.slice("sha256:".length)
|
|
216
|
+
: undefined;
|
|
217
|
+
this.createdAt = asset.created_at;
|
|
218
|
+
return [version, asset.browser_download_url];
|
|
219
|
+
}
|
|
220
|
+
missingAssetError() {
|
|
221
|
+
throw new MissingRelease(`No matching release found for ${OS_NAME} ${this.arch} in the supported range: (${SUPPORTED_RANGE}). Please update the library.`);
|
|
222
|
+
}
|
|
223
|
+
static getPlatformArch() {
|
|
224
|
+
const platArch = os.arch().toLowerCase();
|
|
225
|
+
if (!(platArch in ARCH_MAP)) {
|
|
226
|
+
throw new UnsupportedArchitecture(`Architecture ${platArch} is not supported`);
|
|
227
|
+
}
|
|
228
|
+
const arch = ARCH_MAP[platArch];
|
|
229
|
+
if (!OS_ARCH_MATRIX[OS_NAME].includes(arch)) {
|
|
230
|
+
throw new UnsupportedArchitecture(`Architecture ${arch} is not supported for ${OS_NAME}`);
|
|
231
|
+
}
|
|
232
|
+
return arch;
|
|
233
|
+
}
|
|
234
|
+
async fetchLatest() {
|
|
235
|
+
if (this._version_obj)
|
|
236
|
+
return;
|
|
237
|
+
const releaseData = await this.getAsset();
|
|
238
|
+
this._version_obj = releaseData[0];
|
|
239
|
+
this._url = releaseData[1];
|
|
240
|
+
}
|
|
241
|
+
static async downloadFile(url) {
|
|
242
|
+
const response = await fetch(url, {
|
|
243
|
+
headers: getAuthorizationHeaders(url),
|
|
244
|
+
});
|
|
245
|
+
return Buffer.from(await response.arrayBuffer());
|
|
246
|
+
}
|
|
247
|
+
async extractZip(zipFile, destDir = INSTALL_DIR.toString()) {
|
|
248
|
+
const zip = new AdmZip(zipFile);
|
|
249
|
+
zip.extractAllTo(destDir, true);
|
|
250
|
+
}
|
|
251
|
+
static cleanup() {
|
|
252
|
+
if (fs.existsSync(INSTALL_DIR)) {
|
|
253
|
+
fs.rmSync(INSTALL_DIR, { recursive: true });
|
|
254
|
+
return true;
|
|
255
|
+
}
|
|
256
|
+
return false;
|
|
257
|
+
}
|
|
258
|
+
setVersion(destDir = INSTALL_DIR.toString()) {
|
|
259
|
+
fs.writeFileSync(path.join(destDir, "version.json"), JSON.stringify({
|
|
260
|
+
version: this.version,
|
|
261
|
+
build: this.release,
|
|
262
|
+
prerelease: this.isPrerelease,
|
|
263
|
+
sha256: this.sha256 ?? null,
|
|
264
|
+
created_at: this.createdAt ?? null,
|
|
265
|
+
}));
|
|
266
|
+
}
|
|
267
|
+
static removeLeftovers(dir, prefix) {
|
|
268
|
+
for (const name of fs.readdirSync(dir)) {
|
|
269
|
+
if (name.startsWith(prefix) && isStale(path.join(dir, name))) {
|
|
270
|
+
fs.rmSync(path.join(dir, name), { recursive: true, force: true });
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
static activate(installDir, relativePath) {
|
|
275
|
+
setActive(relativePath);
|
|
276
|
+
removeLegacyInstall(installDir);
|
|
277
|
+
}
|
|
278
|
+
async install() {
|
|
279
|
+
await this.init();
|
|
280
|
+
const folder = versionFolderName(this.version, this.release, this.sha256);
|
|
281
|
+
const relativePath = `browsers/${getRepoName(this.githubRepo)}/${folder}`;
|
|
282
|
+
const installDir = path.join(INSTALL_DIR.toString(), relativePath);
|
|
283
|
+
fs.mkdirSync(browsersDir(), { recursive: true });
|
|
284
|
+
fs.writeFileSync(compatFlag(), "");
|
|
285
|
+
if (fs.existsSync(path.join(installDir, "version.json"))) {
|
|
286
|
+
console.log(`Camoufox v${this.verstr} is already installed.`);
|
|
287
|
+
CamoufoxFetcher.activate(installDir, relativePath);
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
const root = fs.realpathSync(INSTALL_DIR);
|
|
291
|
+
CamoufoxFetcher.removeLeftovers(path.dirname(root), `${path.basename(root)}.staging-`);
|
|
292
|
+
CamoufoxFetcher.removeLeftovers(browsersDir(), ".staging-");
|
|
293
|
+
const stagingDir = fs.mkdtempSync(path.join(browsersDir(), ".staging-"));
|
|
294
|
+
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "camoufox-"));
|
|
295
|
+
const tempFilePath = path.join(tempDir, "camoufox.zip");
|
|
296
|
+
const tempFileStream = fs.createWriteStream(tempFilePath);
|
|
297
|
+
try {
|
|
298
|
+
await webdl(this.url, "Downloading Camoufox...", true, tempFileStream);
|
|
299
|
+
await new Promise((r) => tempFileStream.close(r));
|
|
300
|
+
await verifySha256(tempFilePath, this.sha256, `Camoufox v${this.verstr}`);
|
|
301
|
+
await this.extractZip(tempFilePath, stagingDir);
|
|
302
|
+
this.setVersion(stagingDir);
|
|
303
|
+
if (OS_NAME !== "win") {
|
|
304
|
+
execFileSync("chmod", ["-R", "755", stagingDir]);
|
|
305
|
+
}
|
|
306
|
+
fs.mkdirSync(path.dirname(installDir), { recursive: true });
|
|
307
|
+
try {
|
|
308
|
+
fs.renameSync(stagingDir, installDir);
|
|
309
|
+
}
|
|
310
|
+
catch (e) {
|
|
311
|
+
if (!fs.existsSync(path.join(installDir, "version.json"))) {
|
|
312
|
+
if (!fs.existsSync(installDir))
|
|
313
|
+
throw e;
|
|
314
|
+
if (!isStale(installDir)) {
|
|
315
|
+
throw new Error(`Another process is installing Camoufox into ${installDir}, try again once it finishes.`);
|
|
316
|
+
}
|
|
317
|
+
fs.rmSync(installDir, { recursive: true, force: true });
|
|
318
|
+
fs.renameSync(stagingDir, installDir);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
CamoufoxFetcher.activate(installDir, relativePath);
|
|
322
|
+
console.log(`Camoufox successfully installed to ${installDir}.`);
|
|
323
|
+
}
|
|
324
|
+
catch (e) {
|
|
325
|
+
console.error(`Error installing Camoufox: ${e}`);
|
|
326
|
+
throw e;
|
|
327
|
+
}
|
|
328
|
+
finally {
|
|
329
|
+
try {
|
|
330
|
+
if (!tempFileStream.closed) {
|
|
331
|
+
await new Promise((resolve) => tempFileStream.close(() => resolve()));
|
|
332
|
+
}
|
|
333
|
+
fs.rmSync(tempDir, { recursive: true, force: true });
|
|
334
|
+
fs.rmSync(stagingDir, { recursive: true, force: true });
|
|
335
|
+
}
|
|
336
|
+
catch (cleanupErr) {
|
|
337
|
+
console.error(`Failed to remove staging dir: ${cleanupErr}`);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
get url() {
|
|
342
|
+
if (!this._url) {
|
|
343
|
+
throw new Error("Url is not available. Make sure to run fetchLatest first.");
|
|
344
|
+
}
|
|
345
|
+
return this._url;
|
|
346
|
+
}
|
|
347
|
+
get version() {
|
|
348
|
+
if (!this._version_obj || !this._version_obj.version) {
|
|
349
|
+
throw new Error("Version is not available. Make sure to run fetchLatest first.");
|
|
350
|
+
}
|
|
351
|
+
return this._version_obj.version;
|
|
352
|
+
}
|
|
353
|
+
get release() {
|
|
354
|
+
if (!this._version_obj) {
|
|
355
|
+
throw new Error("Release information is not available. Make sure to run the installation first.");
|
|
356
|
+
}
|
|
357
|
+
return this._version_obj.release;
|
|
358
|
+
}
|
|
359
|
+
get verstr() {
|
|
360
|
+
if (!this._version_obj) {
|
|
361
|
+
throw new Error("Version is not available. Make sure to run the installation first.");
|
|
362
|
+
}
|
|
363
|
+
return this._version_obj.fullString;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
function userCacheDir(appName) {
|
|
367
|
+
if (OS_NAME === "win") {
|
|
368
|
+
return path.join(os.homedir(), "AppData", "Local", appName, appName, "Cache");
|
|
369
|
+
}
|
|
370
|
+
else if (OS_NAME === "mac") {
|
|
371
|
+
return path.join(os.homedir(), "Library", "Caches", appName);
|
|
372
|
+
}
|
|
373
|
+
else {
|
|
374
|
+
const xdg = process.env.XDG_CACHE_HOME;
|
|
375
|
+
return path.join(xdg && path.isAbsolute(xdg) ? xdg : path.join(os.homedir(), ".cache"), appName);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
const SHARED_ENTRIES = new Set([
|
|
379
|
+
".0.5_FLAG",
|
|
380
|
+
"addons",
|
|
381
|
+
"browsers",
|
|
382
|
+
"config.json",
|
|
383
|
+
"fontconfig",
|
|
384
|
+
"geoip",
|
|
385
|
+
"repo_cache.json",
|
|
386
|
+
]);
|
|
387
|
+
function isStale(p) {
|
|
388
|
+
try {
|
|
389
|
+
return Date.now() - fs.statSync(p).mtimeMs > 24 * 60 * 60 * 1000;
|
|
390
|
+
}
|
|
391
|
+
catch {
|
|
392
|
+
return false;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
function removeLegacyInstall(installDir) {
|
|
396
|
+
const root = INSTALL_DIR.toString();
|
|
397
|
+
if (!fs.existsSync(path.join(root, "version.json")))
|
|
398
|
+
return;
|
|
399
|
+
try {
|
|
400
|
+
for (const name of fs.readdirSync(installDir)) {
|
|
401
|
+
if (!SHARED_ENTRIES.has(name)) {
|
|
402
|
+
fs.rmSync(path.join(root, name), { recursive: true, force: true });
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
catch (e) {
|
|
407
|
+
console.warn(`Failed to remove the previous install at ${root}: ${e}`);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
function activeInstallDir() {
|
|
411
|
+
return getActivePath() ?? INSTALL_DIR.toString();
|
|
412
|
+
}
|
|
413
|
+
export function installedVerStr() {
|
|
414
|
+
return Version.fromPath(activeInstallDir()).fullString;
|
|
415
|
+
}
|
|
416
|
+
export function camoufoxPath(_downloadIfMissing = true) {
|
|
417
|
+
const installDir = activeInstallDir();
|
|
418
|
+
if (!fs.existsSync(path.join(installDir, "version.json"))) {
|
|
419
|
+
const pin = effectivePin(loadConfig());
|
|
420
|
+
throw new CamoufoxNotInstalled(`Camoufox${pin ? ` v${pinSpec(pin)}` : ""} is not installed at ${INSTALL_DIR}. Please run \`bexxcv fetch\` to install.`);
|
|
421
|
+
}
|
|
422
|
+
if (!Version.isSupportedPath(installDir)) {
|
|
423
|
+
throw new UnsupportedVersion(`Camoufox v${installedVerStr()} is not supported by this library (supported range: ${SUPPORTED_RANGE}). Please run \`bexxcv fetch\` to install a supported version.`);
|
|
424
|
+
}
|
|
425
|
+
return installDir;
|
|
426
|
+
}
|
|
427
|
+
let pendingInstall;
|
|
428
|
+
export async function ensureCamoufoxInstalled() {
|
|
429
|
+
if (!effectivePin(loadConfig()))
|
|
430
|
+
return;
|
|
431
|
+
const installDir = activeInstallDir();
|
|
432
|
+
if (fs.existsSync(path.join(installDir, "version.json")) &&
|
|
433
|
+
Version.isSupportedPath(installDir)) {
|
|
434
|
+
return;
|
|
435
|
+
}
|
|
436
|
+
pendingInstall ??= new CamoufoxFetcher().install().finally(() => {
|
|
437
|
+
pendingInstall = undefined;
|
|
438
|
+
});
|
|
439
|
+
await pendingInstall;
|
|
440
|
+
}
|
|
441
|
+
export function getPath(file) {
|
|
442
|
+
if (OS_NAME === "mac") {
|
|
443
|
+
return path.resolve(camoufoxPath().toString(), "Camoufox.app", "Contents", "Resources", file);
|
|
444
|
+
}
|
|
445
|
+
return path.join(camoufoxPath().toString(), file);
|
|
446
|
+
}
|
|
447
|
+
export function launchPath() {
|
|
448
|
+
const lp = getPath(LAUNCH_FILE[OS_NAME]);
|
|
449
|
+
if (!fs.existsSync(lp)) {
|
|
450
|
+
throw new CamoufoxNotInstalled(`Camoufox is not installed at ${camoufoxPath()}. Please run \`bexxcv fetch\` to install.`);
|
|
451
|
+
}
|
|
452
|
+
return lp;
|
|
453
|
+
}
|
|
454
|
+
export async function webdl(url, desc = "", bar = true, buffer = null, { retries } = { retries: 5 }) {
|
|
455
|
+
let attempts = 0;
|
|
456
|
+
let response;
|
|
457
|
+
while (attempts < retries) {
|
|
458
|
+
try {
|
|
459
|
+
response = await fetch(url, { headers: getAuthorizationHeaders(url) });
|
|
460
|
+
if (response.ok)
|
|
461
|
+
break;
|
|
462
|
+
}
|
|
463
|
+
catch (e) {
|
|
464
|
+
console.error(e, `retrying (${attempts + 1}/${retries})...`);
|
|
465
|
+
const jitter = Math.random() * 500;
|
|
466
|
+
const delayMs = Math.min(2_000 * 2 ** attempts + jitter, 30_000);
|
|
467
|
+
await setTimeout(delayMs);
|
|
468
|
+
}
|
|
469
|
+
attempts++;
|
|
470
|
+
}
|
|
471
|
+
if (!response || !response.ok) {
|
|
472
|
+
throw new Error(`Failed to download from ${url} after ${retries} attempts`);
|
|
473
|
+
}
|
|
474
|
+
const totalSize = parseInt(response.headers.get("content-length") || "0", 10);
|
|
475
|
+
let progressBar = null;
|
|
476
|
+
if (bar && totalSize > 0) {
|
|
477
|
+
progressBar = new cliProgress.SingleBar({
|
|
478
|
+
format: `${desc} [{bar}] {percentage}% | ETA: {eta_formatted} | {value}/{total}`,
|
|
479
|
+
formatValue: formatBytes,
|
|
480
|
+
noTTYOutput: true,
|
|
481
|
+
}, cliProgress.Presets.shades_classic);
|
|
482
|
+
progressBar.start(totalSize, 0);
|
|
483
|
+
}
|
|
484
|
+
const chunks = [];
|
|
485
|
+
try {
|
|
486
|
+
for await (const chunk of response.body) {
|
|
487
|
+
if (buffer) {
|
|
488
|
+
buffer.write(chunk);
|
|
489
|
+
}
|
|
490
|
+
else {
|
|
491
|
+
chunks.push(chunk);
|
|
492
|
+
}
|
|
493
|
+
if (progressBar) {
|
|
494
|
+
progressBar.increment(chunk.length);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
finally {
|
|
499
|
+
progressBar?.stop();
|
|
500
|
+
}
|
|
501
|
+
return Buffer.concat(chunks);
|
|
502
|
+
}
|
|
503
|
+
async function verifySha256(file, expected, desc) {
|
|
504
|
+
if (!expected) {
|
|
505
|
+
console.warn(`No sha256 published for ${desc}, skipping verification.`);
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
const hash = createHash("sha256");
|
|
509
|
+
for await (const chunk of fs.createReadStream(file)) {
|
|
510
|
+
hash.update(chunk);
|
|
511
|
+
}
|
|
512
|
+
const actual = hash.digest("hex");
|
|
513
|
+
if (actual !== expected.toLowerCase()) {
|
|
514
|
+
throw new CorruptedDownload(`Checksum mismatch for ${desc}: expected sha256 ${expected.toLowerCase()}, got ${actual}.`);
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
export async function unzip(zipFile, extractPath, desc, bar = true) {
|
|
518
|
+
const zip = new AdmZip(zipFile);
|
|
519
|
+
const zipEntries = zip.getEntries();
|
|
520
|
+
if (bar) {
|
|
521
|
+
console.log(desc || "Extracting files...");
|
|
522
|
+
}
|
|
523
|
+
for (const entry of zipEntries) {
|
|
524
|
+
zip.extractEntryTo(entry, extractPath, true, true);
|
|
525
|
+
}
|
|
526
|
+
if (bar) {
|
|
527
|
+
console.log("Extraction complete.");
|
|
528
|
+
}
|
|
529
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { execFile, execFileSync } from "node:child_process";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
const PKG_NAME = "bexxcv";
|
|
6
|
+
function currentVersion() {
|
|
7
|
+
const pkgPath = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "package.json");
|
|
8
|
+
const raw = JSON.parse(readFileSync(pkgPath, "utf-8"));
|
|
9
|
+
return raw.version;
|
|
10
|
+
}
|
|
11
|
+
async function fetchLatestVersion() {
|
|
12
|
+
const res = await fetch(`https://registry.npmjs.org/${PKG_NAME}/latest`, {
|
|
13
|
+
headers: { Accept: "application/json" },
|
|
14
|
+
signal: AbortSignal.timeout(10_000),
|
|
15
|
+
});
|
|
16
|
+
if (!res.ok) {
|
|
17
|
+
throw new Error(`npm registry responded with ${res.status} for ${PKG_NAME}`);
|
|
18
|
+
}
|
|
19
|
+
const data = (await res.json());
|
|
20
|
+
return data.version;
|
|
21
|
+
}
|
|
22
|
+
function semverGt(a, b) {
|
|
23
|
+
const parse = (v) => v
|
|
24
|
+
.replace(/^v/, "")
|
|
25
|
+
.split(".")
|
|
26
|
+
.map((n) => Number.parseInt(n, 10) || 0);
|
|
27
|
+
const [aMaj = 0, aMin = 0, aPatch = 0] = parse(a);
|
|
28
|
+
const [bMaj = 0, bMin = 0, bPatch = 0] = parse(b);
|
|
29
|
+
if (aMaj !== bMaj)
|
|
30
|
+
return aMaj > bMaj;
|
|
31
|
+
if (aMin !== bMin)
|
|
32
|
+
return aMin > bMin;
|
|
33
|
+
return aPatch > bPatch;
|
|
34
|
+
}
|
|
35
|
+
function detectPM() {
|
|
36
|
+
for (const pm of ["pnpm", "yarn"]) {
|
|
37
|
+
try {
|
|
38
|
+
execFileSync(pm, ["--version"], { stdio: "ignore" });
|
|
39
|
+
return pm;
|
|
40
|
+
}
|
|
41
|
+
catch { }
|
|
42
|
+
}
|
|
43
|
+
return "npm";
|
|
44
|
+
}
|
|
45
|
+
function installArgs(pm, pkg) {
|
|
46
|
+
const target = `${pkg}@latest`;
|
|
47
|
+
if (pm === "npm")
|
|
48
|
+
return ["install", "-g", target];
|
|
49
|
+
if (pm === "pnpm")
|
|
50
|
+
return ["add", "-g", target];
|
|
51
|
+
return ["global", "add", target];
|
|
52
|
+
}
|
|
53
|
+
export async function checkSelfUpdate() {
|
|
54
|
+
const current = currentVersion();
|
|
55
|
+
const latest = await fetchLatestVersion();
|
|
56
|
+
return {
|
|
57
|
+
current,
|
|
58
|
+
latest,
|
|
59
|
+
hasUpdate: semverGt(latest, current),
|
|
60
|
+
releaseUrl: `https://www.npmjs.com/package/${PKG_NAME}/v/${latest}`,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
export async function applySelfUpdate() {
|
|
64
|
+
const info = await checkSelfUpdate();
|
|
65
|
+
if (!info.hasUpdate) {
|
|
66
|
+
console.log(`bexxcv is already up to date (v${info.current}).`);
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
console.log(`Updating bexxcv v${info.current} → v${info.latest} ...`);
|
|
70
|
+
const pm = detectPM();
|
|
71
|
+
const args = installArgs(pm, PKG_NAME);
|
|
72
|
+
console.log(`Running: ${pm} ${args.join(" ")}`);
|
|
73
|
+
await new Promise((resolve, reject) => {
|
|
74
|
+
const proc = execFile(pm, args, { stdio: "inherit" });
|
|
75
|
+
proc.on("close", (code) => {
|
|
76
|
+
if (code === 0)
|
|
77
|
+
resolve();
|
|
78
|
+
else
|
|
79
|
+
reject(new Error(`${pm} exited with code ${code}`));
|
|
80
|
+
});
|
|
81
|
+
proc.on("error", reject);
|
|
82
|
+
});
|
|
83
|
+
console.log(`bexxcv updated to v${info.latest}.`);
|
|
84
|
+
}
|
package/dist/server.d.ts
ADDED
package/dist/server.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type Browser, type BrowserContext, type BrowserType } from "playwright-core";
|
|
2
|
+
import { type LaunchOptions } from "./utils.js";
|
|
3
|
+
export interface BexxcvOptions extends LaunchOptions {
|
|
4
|
+
user_data_dir?: string;
|
|
5
|
+
auto_xvfb?: boolean;
|
|
6
|
+
}
|
|
7
|
+
export declare function Bexxcv<UserDataDir extends string | undefined = undefined, ReturnType = UserDataDir extends string ? BrowserContext : Browser>(launch_options?: BexxcvOptions & {
|
|
8
|
+
user_data_dir?: UserDataDir;
|
|
9
|
+
}): Promise<ReturnType>;
|
|
10
|
+
export declare const Camoufox: typeof Bexxcv;
|
|
11
|
+
export declare function NewBrowser<UserDataDir extends string | false = false, ReturnType = UserDataDir extends string ? BrowserContext : Browser>(playwright: BrowserType<Browser>, headless?: boolean | "virtual", fromOptions?: Record<string, any>, userDataDir?: UserDataDir, debug?: boolean, launch_options?: LaunchOptions): Promise<ReturnType>;
|
package/dist/sync_api.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { firefox, } from "playwright-core";
|
|
2
|
+
import { attachNoViewportDefault, launchOptions, spoofsWindowDimensions, syncAttachVD, } from "./utils.js";
|
|
3
|
+
import { VirtualDisplay } from "./virtdisplay.js";
|
|
4
|
+
import { needsXvfb } from "./xvfb.js";
|
|
5
|
+
export async function Bexxcv(launch_options = {}) {
|
|
6
|
+
const { headless, user_data_dir, auto_xvfb = true, ...opts } = launch_options;
|
|
7
|
+
const needsDisplay = auto_xvfb && needsXvfb();
|
|
8
|
+
const effectiveHeadless = (() => {
|
|
9
|
+
if (headless === "virtual")
|
|
10
|
+
return "virtual";
|
|
11
|
+
if (headless === true)
|
|
12
|
+
return true;
|
|
13
|
+
if (needsDisplay)
|
|
14
|
+
return "virtual";
|
|
15
|
+
return headless ?? false;
|
|
16
|
+
})();
|
|
17
|
+
return NewBrowser(firefox, effectiveHeadless, {}, user_data_dir ?? false, false, opts);
|
|
18
|
+
}
|
|
19
|
+
export const Camoufox = Bexxcv;
|
|
20
|
+
export async function NewBrowser(playwright, headless = false, fromOptions = {}, userDataDir = false, debug = false, launch_options = {}) {
|
|
21
|
+
let virtualDisplay = null;
|
|
22
|
+
const normalizedHeadless = headless === "virtual" ? false : headless || false;
|
|
23
|
+
if (headless === "virtual") {
|
|
24
|
+
virtualDisplay = new VirtualDisplay(debug);
|
|
25
|
+
launch_options.virtual_display = await virtualDisplay.get();
|
|
26
|
+
}
|
|
27
|
+
if (!fromOptions || Object.keys(fromOptions).length === 0) {
|
|
28
|
+
fromOptions = await launchOptions({
|
|
29
|
+
debug,
|
|
30
|
+
...launch_options,
|
|
31
|
+
headless: normalizedHeadless,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
const noViewportDefault = spoofsWindowDimensions(fromOptions);
|
|
35
|
+
if (typeof userDataDir === "string") {
|
|
36
|
+
if (noViewportDefault && !("viewport" in fromOptions)) {
|
|
37
|
+
fromOptions = { ...fromOptions, viewport: null };
|
|
38
|
+
}
|
|
39
|
+
const context = await playwright.launchPersistentContext(userDataDir, fromOptions);
|
|
40
|
+
return syncAttachVD(context, virtualDisplay);
|
|
41
|
+
}
|
|
42
|
+
const browser = await playwright.launch(fromOptions);
|
|
43
|
+
if (noViewportDefault) {
|
|
44
|
+
attachNoViewportDefault(browser);
|
|
45
|
+
}
|
|
46
|
+
return syncAttachVD(browser, virtualDisplay);
|
|
47
|
+
}
|