camoucore 0.3.0 → 0.6.1

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.
Files changed (168) hide show
  1. package/LICENSE +4 -3
  2. package/dist/camoufox/__main__.d.ts +10 -0
  3. package/dist/camoufox/__main__.js +1175 -0
  4. package/dist/camoufox/__version__.d.ts +31 -0
  5. package/dist/camoufox/__version__.js +32 -0
  6. package/dist/camoufox/_humanize_playwright.d.ts +54 -0
  7. package/dist/camoufox/_humanize_playwright.js +429 -0
  8. package/dist/camoufox/addons.d.ts +21 -0
  9. package/dist/camoufox/addons.js +56 -0
  10. package/dist/camoufox/async_api.d.ts +9 -0
  11. package/dist/camoufox/async_api.js +9 -0
  12. package/dist/camoufox/browser-pin.d.ts +46 -0
  13. package/dist/camoufox/browser-pin.js +96 -0
  14. package/dist/camoufox/cli.d.ts +7 -0
  15. package/dist/camoufox/cli.js +20 -0
  16. package/dist/camoufox/coherence.d.ts +141 -0
  17. package/dist/camoufox/coherence.js +708 -0
  18. package/dist/camoufox/data-files/browser-pin.json +7 -0
  19. package/dist/camoufox/data-files/essential-fonts.json +5 -0
  20. package/dist/camoufox/data-files/fingerprint-presets-v150.json +14544 -0
  21. package/dist/camoufox/data-files/fingerprint-presets.json +5192 -0
  22. package/dist/camoufox/data-files/font-bases.json +1887 -0
  23. package/dist/camoufox/data-files/font-groups.json +716 -0
  24. package/dist/camoufox/data-files/fonts.json +240 -0
  25. package/dist/camoufox/data-files/fpgen.yml +44 -0
  26. package/dist/camoufox/data-files/launcher-constants.json +66 -0
  27. package/dist/camoufox/data-files/media-devices.json +148 -0
  28. package/dist/camoufox/data-files/repos.yml +40 -0
  29. package/dist/camoufox/data-files/voice-manifests.json +1864 -0
  30. package/dist/camoufox/data-files/voice-uris.json +188 -0
  31. package/dist/camoufox/data-files/warnings.yml +132 -0
  32. package/dist/camoufox/display_profile.d.ts +17 -0
  33. package/dist/camoufox/display_profile.js +72 -0
  34. package/dist/camoufox/driver_defaults.d.ts +25 -0
  35. package/dist/camoufox/driver_defaults.js +114 -0
  36. package/dist/camoufox/exceptions.d.ts +78 -0
  37. package/dist/camoufox/exceptions.js +135 -0
  38. package/dist/camoufox/fingerprints.d.ts +341 -0
  39. package/dist/camoufox/fingerprints.js +1682 -0
  40. package/dist/camoufox/gpudisplay.d.ts +158 -0
  41. package/dist/camoufox/gpudisplay.js +695 -0
  42. package/dist/camoufox/host_rendering.d.ts +38 -0
  43. package/dist/camoufox/host_rendering.js +180 -0
  44. package/dist/camoufox/humanize.d.ts +89 -0
  45. package/dist/camoufox/humanize.js +143 -0
  46. package/dist/camoufox/index.d.ts +21 -0
  47. package/dist/camoufox/index.js +21 -0
  48. package/dist/camoufox/ip.d.ts +45 -0
  49. package/dist/camoufox/ip.js +114 -0
  50. package/dist/camoufox/multiversion.d.ts +131 -0
  51. package/dist/camoufox/multiversion.js +489 -0
  52. package/dist/camoufox/node-floor.d.ts +5 -0
  53. package/dist/camoufox/node-floor.js +17 -0
  54. package/dist/camoufox/paths.d.ts +45 -0
  55. package/dist/camoufox/paths.js +59 -0
  56. package/dist/camoufox/pkgman.d.ts +331 -0
  57. package/dist/camoufox/pkgman.js +972 -0
  58. package/dist/camoufox/product.d.ts +8 -0
  59. package/dist/camoufox/product.js +8 -0
  60. package/dist/camoufox/pycompat.d.ts +97 -0
  61. package/dist/camoufox/pycompat.js +458 -0
  62. package/dist/camoufox/server.d.ts +36 -0
  63. package/dist/camoufox/server.js +82 -0
  64. package/dist/camoufox/sync_api.d.ts +77 -0
  65. package/dist/camoufox/sync_api.js +194 -0
  66. package/dist/camoufox/utils.d.ts +515 -0
  67. package/dist/camoufox/utils.js +1995 -0
  68. package/dist/camoufox/warnings.d.ts +16 -0
  69. package/dist/camoufox/warnings.js +65 -0
  70. package/dist/camoufox/webgl.d.ts +52 -0
  71. package/dist/camoufox/webgl.js +264 -0
  72. package/dist/camouwolf/__main__.d.ts +10 -0
  73. package/dist/camouwolf/__main__.js +1180 -0
  74. package/dist/camouwolf/__version__.d.ts +31 -0
  75. package/dist/camouwolf/__version__.js +32 -0
  76. package/dist/camouwolf/_humanize_playwright.d.ts +53 -0
  77. package/dist/camouwolf/_humanize_playwright.js +427 -0
  78. package/dist/camouwolf/addons.d.ts +42 -0
  79. package/dist/camouwolf/addons.js +113 -0
  80. package/dist/camouwolf/async_api.d.ts +9 -0
  81. package/dist/camouwolf/async_api.js +9 -0
  82. package/dist/camouwolf/browser-pin.d.ts +46 -0
  83. package/dist/camouwolf/browser-pin.js +96 -0
  84. package/dist/camouwolf/cli.d.ts +7 -0
  85. package/dist/camouwolf/cli.js +20 -0
  86. package/dist/camouwolf/clienthints.d.ts +61 -0
  87. package/dist/camouwolf/clienthints.js +176 -0
  88. package/dist/camouwolf/coherence.d.ts +152 -0
  89. package/dist/camouwolf/coherence.js +554 -0
  90. package/dist/camouwolf/data-files/browser-pin.json +7 -0
  91. package/dist/camouwolf/data-files/camouwolf.defaults.json +118 -0
  92. package/dist/camouwolf/data-files/data/bundle-fonts.json +1983 -0
  93. package/dist/camouwolf/data-files/data/chrome-languages.json +517 -0
  94. package/dist/camouwolf/data-files/data/properties.json +321 -0
  95. package/dist/camouwolf/data-files/data/system-colors.json +35 -0
  96. package/dist/camouwolf/data-files/data/ubo.json +6 -0
  97. package/dist/camouwolf/data-files/fpgen.yml +41 -0
  98. package/dist/camouwolf/data-files/launcher-constants.json +26 -0
  99. package/dist/camouwolf/data-files/repos.yml +23 -0
  100. package/dist/camouwolf/data-files/warnings.yml +96 -0
  101. package/dist/camouwolf/driver_defaults.d.ts +25 -0
  102. package/dist/camouwolf/driver_defaults.js +114 -0
  103. package/dist/camouwolf/exceptions.d.ts +95 -0
  104. package/dist/camouwolf/exceptions.js +150 -0
  105. package/dist/camouwolf/fingerprints.d.ts +227 -0
  106. package/dist/camouwolf/fingerprints.js +753 -0
  107. package/dist/camouwolf/gpudisplay.d.ts +171 -0
  108. package/dist/camouwolf/gpudisplay.js +711 -0
  109. package/dist/camouwolf/host_rendering.d.ts +18 -0
  110. package/dist/camouwolf/host_rendering.js +114 -0
  111. package/dist/camouwolf/humanize.d.ts +84 -0
  112. package/dist/camouwolf/humanize.js +128 -0
  113. package/dist/camouwolf/index.d.ts +22 -0
  114. package/dist/camouwolf/index.js +21 -0
  115. package/dist/camouwolf/multiversion.d.ts +131 -0
  116. package/dist/camouwolf/multiversion.js +491 -0
  117. package/dist/camouwolf/node-floor.d.ts +5 -0
  118. package/dist/camouwolf/node-floor.js +17 -0
  119. package/dist/camouwolf/paths.d.ts +34 -0
  120. package/dist/camouwolf/paths.js +58 -0
  121. package/dist/camouwolf/pkgman.d.ts +331 -0
  122. package/dist/camouwolf/pkgman.js +972 -0
  123. package/dist/camouwolf/product.d.ts +3 -0
  124. package/dist/camouwolf/product.js +3 -0
  125. package/dist/camouwolf/pycompat.d.ts +92 -0
  126. package/dist/camouwolf/pycompat.js +461 -0
  127. package/dist/camouwolf/server.d.ts +36 -0
  128. package/dist/camouwolf/server.js +81 -0
  129. package/dist/camouwolf/switches.d.ts +77 -0
  130. package/dist/camouwolf/switches.js +222 -0
  131. package/dist/camouwolf/sync_api.d.ts +84 -0
  132. package/dist/camouwolf/sync_api.js +173 -0
  133. package/dist/camouwolf/utils.d.ts +644 -0
  134. package/dist/camouwolf/utils.js +2057 -0
  135. package/dist/camouwolf/warnings.d.ts +14 -0
  136. package/dist/camouwolf/warnings.js +59 -0
  137. package/dist/camouwolf/webgl.d.ts +41 -0
  138. package/dist/camouwolf/webgl.js +198 -0
  139. package/dist/data.d.ts +1 -1
  140. package/dist/data.js +3 -3
  141. package/dist/download.js +1 -1
  142. package/dist/exceptions.d.ts +1 -1
  143. package/dist/exceptions.js +1 -1
  144. package/dist/geolocation.js +1 -1
  145. package/dist/host.js +1 -1
  146. package/dist/ip.js +1 -1
  147. package/dist/locales.js +1 -1
  148. package/dist/mcp/cli.d.ts +15 -0
  149. package/dist/mcp/cli.js +108 -0
  150. package/dist/mcp/index.d.ts +8 -0
  151. package/dist/mcp/index.js +8 -0
  152. package/dist/mcp/main.d.ts +2 -0
  153. package/dist/mcp/main.js +8 -0
  154. package/dist/mcp/secrets.d.ts +50 -0
  155. package/dist/mcp/secrets.js +193 -0
  156. package/dist/mcp/server.d.ts +48 -0
  157. package/dist/mcp/server.js +653 -0
  158. package/dist/mcp/tree.d.ts +10 -0
  159. package/dist/mcp/tree.js +36 -0
  160. package/dist/passthrough.d.ts +1 -1
  161. package/dist/product.js +1 -1
  162. package/dist/settings.js +1 -1
  163. package/dist/telemetry.d.ts +0 -1
  164. package/dist/telemetry.js +5 -4
  165. package/dist/virtdisplay.d.ts +1 -1
  166. package/dist/virtdisplay.js +1 -1
  167. package/dist/warnings.js +1 -1
  168. package/package.json +57 -13
@@ -0,0 +1,1180 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * The `camouwolf` CLI.
4
+ *
5
+ * TypeScript twin of python/camoucore/src/camoucore/camouwolf/__main__.py. Every command is present,
6
+ * with the same arguments, output and config/cache files. The interactive
7
+ * pickers (`set`, `set --geoip`, `remove --select`) use a numbered
8
+ * prompt in place of inquirer's arrow-key list.
9
+ */
10
+ import "./node-floor.js";
11
+ import * as fs from "node:fs";
12
+ import * as path from "node:path";
13
+ import * as readline from "node:readline";
14
+ import { Argument, Command, Option } from "commander";
15
+ import { ensureModel } from "fpgen-js";
16
+ import { allowGeoip, downloadMmdb, GEOIP_DIR, getMmdbPath, loadGeoipConfig, loadGeoipRepos, saveGeoipConfig, warnIfDeprecated, } from "../geolocation.js";
17
+ import { writeUserDefaults } from "../settings.js";
18
+ import { LIBRARY_VERSION } from "./__version__.js";
19
+ import { effectivePin, loadPin, pinSpec, } from "./browser-pin.js";
20
+ import { FileNotFoundError } from "./exceptions.js";
21
+ import { BROWSERS_DIR, COMPAT_FLAG, CONFIG_FILE, findInstall, getDefaultChannel, installedLabel, latestPerBuild, listInstalled, loadConfig, loadRepoCache, printTree, REPO_CACHE_FILE, removeVersion, saveConfig, saveRepoCache, } from "./multiversion.js";
22
+ import { DEFAULTS_FILE, INSTALL_DIR, rprint, style } from "./paths.js";
23
+ import { AvailableVersion, CamouwolfFetcher, formatAssetDate, incompatibleMessage, installedPackageVersion, installedVerStr, interfaceSupported, listAvailableVersions, RepoConfig, resolvedPlaywrightVersionRaw, taggedVersions, upgradeMessage, Version, } from "./pkgman.js";
24
+ import { PRODUCT } from "./product.js";
25
+ // --------------------------------------------------------------------------
26
+ // click-style output + prompts
27
+ // --------------------------------------------------------------------------
28
+ /** click.secho */
29
+ function secho(text, opts = {}) {
30
+ process.stdout.write(style(text, opts) + (opts.nl === false ? "" : "\n"));
31
+ }
32
+ /** click.echo */
33
+ function echo(text = "", nl = true) {
34
+ process.stdout.write(text + (nl ? "\n" : ""));
35
+ }
36
+ let rl = null;
37
+ const pendingLines = [];
38
+ const lineWaiters = [];
39
+ let stdinClosed = false;
40
+ function readLine() {
41
+ if (!rl) {
42
+ rl = readline.createInterface({ input: process.stdin });
43
+ rl.on("line", (line) => {
44
+ const waiter = lineWaiters.shift();
45
+ if (waiter)
46
+ waiter(line);
47
+ else
48
+ pendingLines.push(line);
49
+ });
50
+ rl.on("close", () => {
51
+ stdinClosed = true;
52
+ for (const waiter of lineWaiters.splice(0))
53
+ waiter(null);
54
+ });
55
+ }
56
+ const queued = pendingLines.shift();
57
+ if (queued !== undefined)
58
+ return Promise.resolve(queued);
59
+ if (stdinClosed)
60
+ return Promise.resolve(null);
61
+ return new Promise((resolve) => lineWaiters.push(resolve));
62
+ }
63
+ function closePrompts() {
64
+ rl?.close();
65
+ rl = null;
66
+ }
67
+ /** click.confirm (default No). EOF answers No. */
68
+ async function confirm(message) {
69
+ for (;;) {
70
+ process.stdout.write(`${message} [y/N]: `);
71
+ const answer = await readLine();
72
+ if (answer === null) {
73
+ echo();
74
+ return false;
75
+ }
76
+ const value = answer.trim().toLowerCase();
77
+ if (value === "")
78
+ return false;
79
+ if (value === "y" || value === "yes")
80
+ return true;
81
+ if (value === "n" || value === "no")
82
+ return false;
83
+ echo("Error: invalid input");
84
+ }
85
+ }
86
+ /**
87
+ * Generic selection, standing in for the Python twin's inquirer list.
88
+ * Returns the selected value, or null on cancel/EOF.
89
+ */
90
+ async function select(choices, message) {
91
+ echo(`${style("[?]", { fg: "yellow" })} ${message}:`);
92
+ choices.forEach(([label], i) => {
93
+ echo(` ${style(String(i + 1).padStart(2), { fg: "cyan" })}) ${label}`);
94
+ });
95
+ for (;;) {
96
+ process.stdout.write(`Choice [1-${choices.length}]: `);
97
+ const answer = await readLine();
98
+ if (answer === null || answer.trim() === "") {
99
+ if (answer === null)
100
+ echo();
101
+ return null;
102
+ }
103
+ const n = Number.parseInt(answer.trim(), 10);
104
+ if (Number.isInteger(n) && n >= 1 && n <= choices.length) {
105
+ return choices[n - 1][1];
106
+ }
107
+ echo(`Error: enter a number between 1 and ${choices.length}`);
108
+ }
109
+ }
110
+ // --------------------------------------------------------------------------
111
+ // helpers
112
+ // --------------------------------------------------------------------------
113
+ /** Find an installed version by channel path, build, or full version string. */
114
+ function findInstalled(specifier) {
115
+ const spec = specifier.toLowerCase();
116
+ const installed = listInstalled();
117
+ const parts = spec.split("/");
118
+ for (const v of installed) {
119
+ if (v.channelPath.toLowerCase() === spec ||
120
+ v.relativePath.toLowerCase() === spec ||
121
+ v.version.build.toLowerCase() === spec ||
122
+ v.version.fullString.toLowerCase() === spec) {
123
+ return v;
124
+ }
125
+ // Match repo/version without channel, for example official/134.0.2-beta.20
126
+ if (parts.length === 2) {
127
+ const [repo, ver] = parts;
128
+ if (v.repoName === repo && v.version.fullString.toLowerCase() === ver) {
129
+ return v;
130
+ }
131
+ }
132
+ }
133
+ // Match repo/channel, for example official/stable gets the latest installed
134
+ // for that channel
135
+ if (parts.length === 2) {
136
+ const [repo, ctype] = parts;
137
+ if (ctype === "stable" || ctype === "prerelease") {
138
+ const isPre = ctype === "prerelease";
139
+ for (const v of installed) {
140
+ if (v.repoName === repo && v.isPrerelease === isPre)
141
+ return v;
142
+ }
143
+ }
144
+ }
145
+ return null;
146
+ }
147
+ /** Name of the active GeoIP source. */
148
+ function getGeoIPSourceName() {
149
+ try {
150
+ return loadGeoipConfig().name ?? "Default";
151
+ }
152
+ catch {
153
+ return "Default";
154
+ }
155
+ }
156
+ /**
157
+ * Sync available versions from the remote repositories. Returns true on success.
158
+ */
159
+ async function doSync(spoofOs, spoofArch) {
160
+ rprint("Syncing repositories...", "yellow");
161
+ const cache = {
162
+ repos: [],
163
+ incompatible: [],
164
+ spoof_os: spoofOs ?? null,
165
+ spoof_arch: spoofArch ?? null,
166
+ };
167
+ for (const repoConfig of RepoConfig.loadRepos()) {
168
+ rprint(` ${repoConfig.name}...`, "cyan", false);
169
+ try {
170
+ const listed = await listAvailableVersions(repoConfig, true, spoofOs, spoofArch, true);
171
+ const versions = listed.filter((v) => interfaceSupported(v.interface));
172
+ for (const v of listed) {
173
+ if (interfaceSupported(v.interface))
174
+ continue;
175
+ cache.incompatible.push({
176
+ repo: repoConfig.name,
177
+ version: v.version.version ?? "",
178
+ build: v.version.build,
179
+ interface: v.interface,
180
+ });
181
+ }
182
+ cache.repos.push({
183
+ name: repoConfig.name,
184
+ repo: repoConfig.repo,
185
+ versions: versions.map((v) => ({
186
+ version: v.version.version ?? null,
187
+ build: v.version.build,
188
+ url: v.url,
189
+ is_prerelease: v.isPrerelease,
190
+ asset_id: v.assetId ?? null,
191
+ asset_size: v.assetSize ?? null,
192
+ asset_updated_at: v.assetUpdatedAt ?? null,
193
+ sha256: v.sha256 ?? null,
194
+ created_at: v.assetCreatedAt ?? null,
195
+ interface: v.interface,
196
+ })),
197
+ });
198
+ rprint(` ${versions.length} versions`, "green");
199
+ }
200
+ catch (e) {
201
+ rprint(` Error: ${errorMessage(e)}`, "red");
202
+ }
203
+ }
204
+ saveRepoCache(cache);
205
+ if (cache.incompatible.length) {
206
+ const versionOf = (v) => new Version(v.build, v.version);
207
+ const newest = cache.incompatible.reduce((a, b) => versionOf(b).compare(versionOf(a)) > 0 ? b : a);
208
+ rprint(upgradeMessage(versionOf(newest), newest.interface), "yellow");
209
+ }
210
+ const total = cache.repos.reduce((sum, r) => sum + r.versions.length, 0);
211
+ const platformStr = spoofOs ? ` (${spoofOs}/${spoofArch})` : "";
212
+ rprint(`\nSynced ${total} versions from ${cache.repos.length} repos${platformStr}.`, "green");
213
+ return true;
214
+ }
215
+ function errorMessage(e) {
216
+ return e instanceof Error ? e.message : String(e);
217
+ }
218
+ /** Ensure a repo cache exists. Returns true if synced. */
219
+ function ensureSynced() {
220
+ if (!fs.existsSync(REPO_CACHE_FILE)) {
221
+ rprint("No repo cache found. Run 'camouwolf sync' first.", "red");
222
+ return false;
223
+ }
224
+ return true;
225
+ }
226
+ /** Cache block for a repo by name. */
227
+ function repoData(cache, repoName) {
228
+ return ((cache.repos ?? []).find((r) => r.name.toLowerCase() === repoName.toLowerCase()) ?? null);
229
+ }
230
+ /**
231
+ * Resolve a version-build or version-build-sha8 spec against cache entries.
232
+ * Returns [asset, sha] for a specific date, [latest, null] to follow the
233
+ * latest, or [null, null] when the spec is unknown.
234
+ */
235
+ function resolveSpec(repo, spec) {
236
+ const versions = repo.versions ?? [];
237
+ for (const v of versions) {
238
+ const sha = v.sha256 || "";
239
+ if (sha && spec === `${v.version}-${v.build}-${sha.slice(0, 8)}`) {
240
+ return [v, sha];
241
+ }
242
+ }
243
+ for (const v of latestPerBuild(versions)) {
244
+ if (spec === `${v.version}-${v.build}`)
245
+ return [v, null];
246
+ }
247
+ return [null, null];
248
+ }
249
+ /** Cache entry a pin resolves to: the specific sha asset or the build's latest. */
250
+ function pinTarget(repo, pinned, pinnedSha) {
251
+ const versions = repo.versions ?? [];
252
+ if (pinnedSha) {
253
+ return versions.find((v) => v.sha256 === pinnedSha) ?? null;
254
+ }
255
+ return (latestPerBuild(versions).find((v) => `${v.version}-${v.build}` === pinned) ?? null);
256
+ }
257
+ /** Set to track a channel (fetches the latest on fetch). */
258
+ function setChannel(repoName, channelType) {
259
+ const config = loadConfig();
260
+ config.channel = `${repoName}/${channelType}`;
261
+ delete config.pinned;
262
+ delete config.pinned_sha;
263
+ // Check if the latest for this channel is already installed
264
+ const isPre = channelType === "prerelease";
265
+ const cache = loadRepoCache();
266
+ for (const repo of cache.repos ?? []) {
267
+ if (repo.name.toLowerCase() !== repoName.toLowerCase())
268
+ continue;
269
+ const candidates = (repo.versions ?? []).filter((v) => (v.is_prerelease ?? false) === isPre);
270
+ if (candidates.length) {
271
+ const latestBuild = candidates[0].build;
272
+ for (const inst of listInstalled()) {
273
+ if (inst.version.build === latestBuild &&
274
+ inst.repoName === repoName.toLowerCase()) {
275
+ config.active_version = inst.relativePath;
276
+ saveConfig(config);
277
+ secho(`Channel: ${repoName.toLowerCase()}/${channelType}`, {
278
+ fg: "cyan",
279
+ bold: true,
280
+ });
281
+ secho(`Using latest: ${inst.channelPath} (installed)`, {
282
+ fg: "green",
283
+ });
284
+ return;
285
+ }
286
+ }
287
+ }
288
+ break;
289
+ }
290
+ delete config.active_version;
291
+ saveConfig(config);
292
+ secho(`Channel: ${repoName.toLowerCase()}/${channelType}`, {
293
+ fg: "cyan",
294
+ bold: true,
295
+ });
296
+ secho("Run 'camouwolf fetch' to install latest.", { fg: "yellow" });
297
+ }
298
+ /** Pin a version-build, optionally to a specific dated asset by sha. */
299
+ function setPinned(repoName, channelType, verData, inst, sha) {
300
+ const config = loadConfig();
301
+ config.channel = `${repoName.toLowerCase()}/${channelType}`;
302
+ config.pinned = `${verData.version}-${verData.build}`;
303
+ if (sha) {
304
+ config.pinned_sha = sha;
305
+ }
306
+ else {
307
+ delete config.pinned_sha;
308
+ }
309
+ const tag = sha ? ` (${sha.slice(0, 8)})` : "";
310
+ const display = `${repoName.toLowerCase()}/${channelType}/${verData.version}-${verData.build}${tag}`;
311
+ if (inst) {
312
+ config.active_version = inst.relativePath;
313
+ saveConfig(config);
314
+ secho(`Pinned: ${display} (installed)`, { fg: "green" });
315
+ }
316
+ else {
317
+ delete config.active_version;
318
+ saveConfig(config);
319
+ secho(`Pinned: ${display}`, { fg: "cyan", bold: true });
320
+ secho("Run 'camouwolf fetch' to install.", { fg: "yellow" });
321
+ }
322
+ }
323
+ /** A command's failure, printed as its message, with exit code 1. */
324
+ class CommandFailed extends Error {
325
+ }
326
+ /** Stop the command with an error, so a script or CI step stops here. */
327
+ function fail(message) {
328
+ throw new CommandFailed(message);
329
+ }
330
+ /**
331
+ * The build `spec` names, read from its own release with one API call. Null
332
+ * when the source has no such tag: early builds were published under others.
333
+ */
334
+ async function taggedBuild(repoName, tag, spec) {
335
+ const repoConfig = RepoConfig.findByName(repoName);
336
+ if (!repoConfig)
337
+ return null;
338
+ const match = (await taggedVersions(repoConfig, tag)).find((v) => v.version.fullString === spec);
339
+ return match ? [repoConfig, match] : null;
340
+ }
341
+ /**
342
+ * Sync every source, then resolve against the cache the build fetch was asked
343
+ * for: `spec`, the release's pin, or the user's pin or channel.
344
+ */
345
+ async function syncedBuild(config, repoName, spec, pin) {
346
+ await doSync();
347
+ const cache = loadRepoCache();
348
+ let repo = null;
349
+ let verData = null;
350
+ if (pin && repoName && spec) {
351
+ repo = repoData(cache, repoName);
352
+ if (repo)
353
+ verData = pinTarget(repo, spec, undefined);
354
+ if (!verData) {
355
+ fail(`${pin.tag}, the browser this camouwolf release pairs with, is not in ` +
356
+ `${repoName}'s releases. Run 'camouwolf sync' and try again.`);
357
+ }
358
+ }
359
+ else if (repoName && spec) {
360
+ repo = repoData(cache, repoName);
361
+ if (repo)
362
+ [verData] = resolveSpec(repo, spec);
363
+ }
364
+ else if (config.pinned) {
365
+ const channel = config.channel ?? "";
366
+ repoName = channel.includes("/") ? channel.split("/")[0] : channel;
367
+ repo = repoData(cache, repoName);
368
+ if (repo)
369
+ verData = pinTarget(repo, config.pinned, config.pinned_sha);
370
+ }
371
+ else {
372
+ const channel = config.channel || getDefaultChannel();
373
+ const slash = channel.indexOf("/");
374
+ const name = slash === -1 ? channel : channel.slice(0, slash);
375
+ const ctype = slash === -1 ? "stable" : channel.slice(slash + 1);
376
+ repoName = name;
377
+ repo = repoData(cache, repoName);
378
+ if (repo) {
379
+ const isPre = ctype === "prerelease";
380
+ const latest = latestPerBuild(repo.versions ?? []).filter((v) => (v.is_prerelease ?? false) === isPre);
381
+ verData = latest[0] ?? null;
382
+ }
383
+ }
384
+ if (!verData || !repo) {
385
+ const incompatible = (cache.incompatible ?? []).find((v) => spec &&
386
+ v.repo.toLowerCase() === (repoName ?? "").toLowerCase() &&
387
+ `${v.version}-${v.build}` === spec);
388
+ if (incompatible) {
389
+ fail(incompatibleMessage(new Version(incompatible.build, incompatible.version), incompatible.interface));
390
+ }
391
+ fail(`Version '${spec || repoName}' not found in cache. Run 'camouwolf sync'.`);
392
+ }
393
+ const selected = new AvailableVersion({
394
+ version: new Version(verData.build, verData.version),
395
+ url: verData.url,
396
+ isPrerelease: verData.is_prerelease ?? false,
397
+ sha256: verData.sha256 ?? undefined,
398
+ assetCreatedAt: verData.created_at ?? undefined,
399
+ interface: verData.interface ?? 1,
400
+ });
401
+ return [RepoConfig.findByName(repo.name), selected];
402
+ }
403
+ /**
404
+ * Checks & updates Camouwolf.
405
+ */
406
+ class CamouwolfUpdate extends CamouwolfFetcher {
407
+ currentVerStr = null;
408
+ async init() {
409
+ await super.init();
410
+ try {
411
+ this.currentVerStr = installedVerStr();
412
+ }
413
+ catch (error) {
414
+ if (!(error instanceof FileNotFoundError))
415
+ throw error;
416
+ this.currentVerStr = null;
417
+ }
418
+ return this;
419
+ }
420
+ isUpdatedNeeded() {
421
+ return this.currentVerStr === null || this.currentVerStr !== this.verstr;
422
+ }
423
+ async update(replace = false, iKnowWhatImDoing = false) {
424
+ if (!this.isUpdatedNeeded() && !replace) {
425
+ rprint("Camouwolf binaries up to date!", "green");
426
+ rprint(`Current version: v${this.currentVerStr}`, "green");
427
+ return;
428
+ }
429
+ if (this.isPrerelease && !iKnowWhatImDoing) {
430
+ rprint(`Warning: v${this.verstr} is a prerelease version!`, "yellow");
431
+ if (!(await confirm("Continue with prerelease installation?"))) {
432
+ fail("Installation cancelled.");
433
+ }
434
+ }
435
+ const action = this.currentVerStr ? "Installing" : "Fetching";
436
+ rprint(`${action} Camouwolf v${this.verstr}...`, "yellow");
437
+ await this.install(replace);
438
+ }
439
+ }
440
+ // --------------------------------------------------------------------------
441
+ // commands
442
+ // --------------------------------------------------------------------------
443
+ const program = new Command();
444
+ program.name("camouwolf").version(LIBRARY_VERSION);
445
+ program
446
+ .command("sync")
447
+ .description("Sync available versions from remote repositories")
448
+ .addOption(new Option("--spoof-os <os>", "Spoof OS (auto = native)").choices([
449
+ "auto",
450
+ "mac",
451
+ "win",
452
+ "lin",
453
+ ]))
454
+ .addOption(new Option("--spoof-arch <arch>", "Spoof architecture (auto = native)").choices(["auto", "x86_64", "i686", "arm64"]))
455
+ .action(async ({ spoofOs, spoofArch }) => {
456
+ await doSync(spoofOs === "auto" ? undefined : spoofOs, spoofArch === "auto" ? undefined : spoofArch);
457
+ });
458
+ program
459
+ .command("fetch")
460
+ .description("Install the active version, or a specific version")
461
+ .argument("[version]", "e.g. official/152.0.7977.42-alpha.1")
462
+ .action(async (version) => {
463
+ // Clean up an incompatible old data directory
464
+ if (fs.existsSync(INSTALL_DIR) &&
465
+ fs.readdirSync(INSTALL_DIR).length > 0 &&
466
+ !fs.existsSync(COMPAT_FLAG)) {
467
+ rprint("Cleaning old data...", "yellow");
468
+ fs.rmSync(INSTALL_DIR, { recursive: true, force: true });
469
+ }
470
+ const config = loadConfig();
471
+ const pin = version ? null : effectivePin(config);
472
+ let repoName = null;
473
+ let spec = null;
474
+ let tag = null;
475
+ if (version) {
476
+ const parts = version.toLowerCase().split("/");
477
+ if (parts.length === 1) {
478
+ repoName = RepoConfig.getDefaultName();
479
+ spec = parts[0];
480
+ }
481
+ else if (parts.length === 2 || parts.length === 3) {
482
+ repoName = parts[0];
483
+ spec = parts[parts.length - 1];
484
+ }
485
+ else {
486
+ fail("Format: version-build, repo/version-build, or repo/channel/version-build");
487
+ }
488
+ spec = spec.replace(/^v+/, "");
489
+ tag = `v${spec}`;
490
+ }
491
+ else if (pin) {
492
+ // This library release pairs with exactly one browser build.
493
+ repoName = pin.repoName;
494
+ spec = pinSpec(pin);
495
+ tag = pin.tag;
496
+ }
497
+ const [repoConfig, selected] = (repoName && spec && tag && (await taggedBuild(repoName, tag, spec))) ||
498
+ (await syncedBuild(config, repoName, spec, pin));
499
+ try {
500
+ const updater = await new CamouwolfUpdate(repoConfig, selected).init();
501
+ // The paired build is what this release was tested with; installing
502
+ // it needs no "this is a prerelease" confirmation even when it is one.
503
+ await updater.update(false, pin !== null);
504
+ }
505
+ catch (e) {
506
+ if (e instanceof CommandFailed)
507
+ throw e;
508
+ const msg = errorMessage(e);
509
+ if (msg.includes("404") || msg.includes("Not Found")) {
510
+ rprint("Release not found (404). Asset may have been removed.", "red");
511
+ fail("Run 'camouwolf sync' to refresh available versions.");
512
+ }
513
+ fail(`Error: ${msg}`);
514
+ }
515
+ if (allowGeoip()) {
516
+ await downloadMmdb();
517
+ }
518
+ // Fetch the pinned fpgen model now rather than on the first launch.
519
+ await ensureModel();
520
+ // The default addons are not part of the browser bundle: each is
521
+ // downloaded from the release pinned in data/, and verified against its
522
+ // sha256.
523
+ try {
524
+ const { fetchDefaultAddons } = await import("./addons.js");
525
+ await fetchDefaultAddons();
526
+ }
527
+ catch (e) {
528
+ fail(`Error installing the default addons: ${errorMessage(e)}`);
529
+ }
530
+ });
531
+ program
532
+ .command("set")
533
+ .description("Set the active Camouwolf version to use & fetch.\n" +
534
+ "By default, this opens an interactive selector for versions and settings.\n" +
535
+ "You can also pass a specifier to activate directly:\n" +
536
+ "Pin version:\n" +
537
+ " camouwolf set official/stable/134.0.2-beta.20\n" +
538
+ "Automatically find latest in a channel source:\n" +
539
+ " camouwolf set official/stable")
540
+ .argument("[specifier]")
541
+ .option("--geoip", "Select GeoIP source instead")
542
+ .option("--release", "Forget any explicit choice and use the browser this camouwolf release pairs with")
543
+ .action(async (specifier, { geoip, release }) => {
544
+ if (geoip) {
545
+ await selectGeoIPSource();
546
+ return;
547
+ }
548
+ if (release) {
549
+ const releasePin = loadPin();
550
+ if (!releasePin) {
551
+ rprint("This camouwolf is a development copy; it pairs with no particular browser.", "yellow");
552
+ return;
553
+ }
554
+ const config = loadConfig();
555
+ delete config.channel;
556
+ delete config.pinned;
557
+ delete config.pinned_sha;
558
+ delete config.active_version;
559
+ saveConfig(config);
560
+ rprint(`Using the paired browser: ${releasePin.repoName} ${pinSpec(releasePin)} (${releasePin.tag})`, "green");
561
+ rprint("Run 'camouwolf fetch' if it is not installed.", "yellow");
562
+ return;
563
+ }
564
+ if (specifier) {
565
+ const parts = specifier.toLowerCase().split("/");
566
+ // 2-part sets a channel like official/stable
567
+ if (parts.length === 2) {
568
+ const [repoName, ctype] = parts;
569
+ if (ctype !== "stable" && ctype !== "prerelease") {
570
+ rprint(`Unknown channel type '${ctype}'. Use 'stable' or 'prerelease'.`, "red");
571
+ return;
572
+ }
573
+ setChannel(repoName, ctype);
574
+ return;
575
+ }
576
+ // 1-part pins in the default repo, 3-part names the repo and channel
577
+ let repoName;
578
+ let spec;
579
+ if (parts.length === 1) {
580
+ repoName = RepoConfig.getDefaultName();
581
+ spec = parts[0];
582
+ }
583
+ else if (parts.length === 3) {
584
+ const ctype = parts[1];
585
+ [repoName, , spec] = parts;
586
+ if (ctype !== "stable" && ctype !== "prerelease") {
587
+ rprint(`Unknown channel type '${ctype}'. Use 'stable' or 'prerelease'.`, "red");
588
+ return;
589
+ }
590
+ }
591
+ else {
592
+ rprint(`Invalid specifier '${specifier}'.`, "red");
593
+ rprint("Use: version-build, repo/channel, or repo/channel/version-build", "yellow");
594
+ return;
595
+ }
596
+ if (!ensureSynced())
597
+ return;
598
+ const repo = repoData(loadRepoCache(), repoName);
599
+ if (!repo) {
600
+ rprint(`Repo '${repoName.toLowerCase()}' not in cache. Run 'camouwolf sync'.`, "red");
601
+ return;
602
+ }
603
+ const [verData, sha] = resolveSpec(repo, spec.replace(/^v+/, ""));
604
+ if (!verData) {
605
+ rprint(`Version '${spec}' not found in ${repoName.toLowerCase()}.`, "red");
606
+ return;
607
+ }
608
+ const ctype = verData.is_prerelease ? "prerelease" : "stable";
609
+ const vb = `${verData.version}-${verData.build}`;
610
+ const count = (repo.versions ?? []).filter((x) => `${x.version}-${x.build}` === vb).length;
611
+ const inst = findInstall(vb, verData.sha256, listInstalled(), count);
612
+ setPinned(repo.name, ctype, verData, inst, sha);
613
+ return;
614
+ }
615
+ if (!ensureSynced())
616
+ return;
617
+ await interactiveSet();
618
+ });
619
+ async function interactiveSet() {
620
+ const cache = loadRepoCache();
621
+ const installedList = listInstalled();
622
+ if (!cache.repos?.length) {
623
+ rprint("No versions in cache. Run 'camouwolf sync' first.", "red");
624
+ return;
625
+ }
626
+ const channels = [];
627
+ for (const repo of cache.repos) {
628
+ const versions = repo.versions ?? [];
629
+ const stable = latestPerBuild(versions.filter((v) => !v.is_prerelease));
630
+ const prereleases = latestPerBuild(versions.filter((v) => v.is_prerelease));
631
+ if (stable.length)
632
+ channels.push([repo.name, "stable", stable[0]]);
633
+ if (prereleases.length) {
634
+ channels.push([repo.name, "prerelease", prereleases[0]]);
635
+ }
636
+ }
637
+ const config = loadConfig();
638
+ const channel = config.channel || getDefaultChannel();
639
+ const pinned = config.pinned;
640
+ const pinnedSha = config.pinned_sha;
641
+ if (pinned) {
642
+ secho(`Pinned: ${channel.toLowerCase()}/${pinned}`, { fg: "cyan" });
643
+ }
644
+ else {
645
+ secho(`Channel: ${channel.toLowerCase()}`, { fg: "cyan" });
646
+ }
647
+ echo();
648
+ // Full dated lists so the pin picker can show every date, not just the latest
649
+ const channelVersions = [];
650
+ for (const repo of cache.repos) {
651
+ const versions = repo.versions ?? [];
652
+ const stable = versions.filter((v) => !v.is_prerelease);
653
+ const prereleases = versions.filter((v) => v.is_prerelease);
654
+ if (stable.length)
655
+ channelVersions.push([repo.name, "stable", stable]);
656
+ if (prereleases.length) {
657
+ channelVersions.push([repo.name, "prerelease", prereleases]);
658
+ }
659
+ }
660
+ for (;;) {
661
+ const choices = [["Set channel", "channel"]];
662
+ for (const [name, ctype, versions] of channelVersions) {
663
+ const label = `Pin version: ${style(`${name.toLowerCase()}/${ctype}`, { fg: "cyan", bold: true })}`;
664
+ choices.push([label, ["pin", name, ctype, versions]]);
665
+ }
666
+ choices.push([style("Exit", { fg: "bright_black" }), "exit"]);
667
+ const action = await select(choices, "Select");
668
+ if (action === null || action === "exit")
669
+ return;
670
+ if (action === "channel") {
671
+ const chChoices = [];
672
+ for (const [name, ctype, latest] of channels) {
673
+ const verStr = `v${latest.version}-${latest.build}`;
674
+ const isCurrent = channel === `${name}/${ctype}`;
675
+ let label = `${name.toLowerCase()}/${ctype} (latest: ${verStr})`;
676
+ if (isCurrent) {
677
+ label = `${style(label, { fg: "green", bold: true })} (current)`;
678
+ }
679
+ chChoices.push([label, [name, ctype]]);
680
+ }
681
+ chChoices.push([style("Back", { fg: "bright_black" }), null]);
682
+ const chAnswer = await select(chChoices, "Set channel");
683
+ if (!chAnswer)
684
+ continue;
685
+ setChannel(chAnswer[0], chAnswer[1]);
686
+ return;
687
+ }
688
+ const [, rname, ctype, versions] = action;
689
+ const vbCounts = new Map();
690
+ for (const x of versions) {
691
+ const key = `${x.version}-${x.build}`;
692
+ vbCounts.set(key, (vbCounts.get(key) ?? 0) + 1);
693
+ }
694
+ const vChoices = [];
695
+ for (const v of versions) {
696
+ const vb = `${v.version}-${v.build}`;
697
+ const sha = v.sha256 || "";
698
+ const date = formatAssetDate(v.created_at ?? undefined);
699
+ const inst = findInstall(vb, v.sha256 ?? undefined, installedList, vbCounts.get(vb) ?? 0);
700
+ const isPinned = pinned === vb && (pinnedSha ?? null) === (sha || null);
701
+ let color;
702
+ let bold;
703
+ let status;
704
+ if (isPinned) {
705
+ [color, bold, status] = ["green", true, "(pinned)"];
706
+ }
707
+ else if (inst) {
708
+ [color, bold, status] = [null, false, "(installed)"];
709
+ }
710
+ else {
711
+ [color, bold, status] = ["bright_black", false, ""];
712
+ }
713
+ const cells = [date, sha ? `(${sha.slice(0, 8)})` : "", status].filter(Boolean);
714
+ const meta = cells.length ? ` ${cells.join(" ")}` : "";
715
+ vChoices.push([style(`v${vb}`, { fg: color, bold }) + meta, v]);
716
+ }
717
+ vChoices.push([style("Back", { fg: "bright_black" }), null]);
718
+ const verData = await select(vChoices, `Pin version (${rname.toLowerCase()}/${ctype})`);
719
+ if (!verData)
720
+ continue;
721
+ const vb = `${verData.version}-${verData.build}`;
722
+ const inst = findInstall(vb, verData.sha256 ?? undefined, installedList, vbCounts.get(vb) ?? 0);
723
+ setPinned(rname, ctype, verData, inst, verData.sha256);
724
+ return;
725
+ }
726
+ }
727
+ /** Interactive selection of the GeoIP source. */
728
+ async function selectGeoIPSource() {
729
+ const [repos] = loadGeoipRepos();
730
+ if (!repos.length) {
731
+ rprint("No GeoIP sources configured.", "red");
732
+ return;
733
+ }
734
+ let current = "";
735
+ try {
736
+ current = loadGeoipConfig().name ?? "";
737
+ }
738
+ catch {
739
+ // unreadable config: nothing is marked active
740
+ }
741
+ const choices = repos.map((r) => [
742
+ r.name +
743
+ (r.deprecated ? " (deprecated)" : "") +
744
+ (r.name === current ? " [active]" : ""),
745
+ r,
746
+ ]);
747
+ const selected = await select(choices, "Select GeoIP source");
748
+ if (!selected)
749
+ return;
750
+ saveGeoipConfig(selected, true);
751
+ rprint(`GeoIP source: ${selected.name}`, "green");
752
+ warnIfDeprecated(selected);
753
+ }
754
+ program
755
+ .command("list")
756
+ .description("List Camouwolf versions\n\n" +
757
+ "installed Show installed versions (default)\n" +
758
+ "all Show all available versions from synced repos")
759
+ .addArgument(new Argument("[mode]").choices(["installed", "all"]).default("installed"))
760
+ .option("--path", "Show full paths")
761
+ .action((mode, { path: showPaths }) => {
762
+ if (mode === "all") {
763
+ listAll(Boolean(showPaths));
764
+ }
765
+ else {
766
+ listInstalledVersions(Boolean(showPaths));
767
+ }
768
+ });
769
+ function listInstalledVersions(showPaths) {
770
+ printTree(true, showPaths);
771
+ echo();
772
+ secho("geoip/", { fg: "cyan", bold: true, nl: false });
773
+ if (showPaths && fs.existsSync(GEOIP_DIR)) {
774
+ secho(` -> ${GEOIP_DIR}`, { fg: "bright_black" });
775
+ }
776
+ else {
777
+ echo();
778
+ }
779
+ if (fs.existsSync(GEOIP_DIR)) {
780
+ const mmdb = getMmdbPath();
781
+ if (fs.existsSync(mmdb)) {
782
+ echo(` └── ${path.basename(mmdb)} `, false);
783
+ secho(`(${getGeoIPSourceName()})`, { fg: "green" });
784
+ }
785
+ else {
786
+ rprint(" └── Not downloaded", "yellow");
787
+ }
788
+ }
789
+ else {
790
+ rprint(" └── Not configured", "yellow");
791
+ }
792
+ }
793
+ function listAll(showPaths) {
794
+ if (!ensureSynced())
795
+ return;
796
+ const cache = loadRepoCache();
797
+ const installed = new Map(listInstalled().map((v) => [v.version.build, v]));
798
+ rprint("Available versions:\n", "yellow");
799
+ for (const repo of cache.repos ?? []) {
800
+ const versions = latestPerBuild(repo.versions ?? []);
801
+ secho(`${repo.name}/`, { fg: "cyan", bold: true });
802
+ versions.forEach((v, i) => {
803
+ const fullVer = `${v.version}-${v.build}`;
804
+ const inst = installed.get(v.build);
805
+ const isLast = i === versions.length - 1;
806
+ const prefix = isLast ? "└── " : "├── ";
807
+ const active = Boolean(inst?.isActive);
808
+ echo(` ${prefix}`, false);
809
+ secho(`v${fullVer}`, {
810
+ fg: active ? "green" : null,
811
+ bold: active,
812
+ nl: false,
813
+ });
814
+ if (v.is_prerelease) {
815
+ secho(" (prerelease)", { fg: "yellow", nl: false });
816
+ }
817
+ else {
818
+ secho(" (stable)", { fg: "blue", nl: false });
819
+ }
820
+ if (inst) {
821
+ if (inst.isActive) {
822
+ secho(" (installed, active)", { fg: "green", bold: true, nl: false });
823
+ }
824
+ else {
825
+ secho(" (installed)", { fg: "green", nl: false });
826
+ }
827
+ if (showPaths) {
828
+ secho(` -> ${inst.path}`, { fg: "bright_black", nl: false });
829
+ }
830
+ }
831
+ echo();
832
+ });
833
+ echo();
834
+ }
835
+ }
836
+ program
837
+ .command("remove")
838
+ .description("Remove downloaded data. By default, this removes everything.\n" +
839
+ "Pass --select to pick a browser version to remove.")
840
+ .argument("[version_path]")
841
+ .option("--select", "Interactively select a version to remove")
842
+ .option("-y, --yes", "Skip confirmation prompts")
843
+ .action(async (versionPath, { select: doSelect, yes }) => {
844
+ // Select mode: interactively pick a single version
845
+ if (doSelect) {
846
+ const installed = listInstalled();
847
+ if (!installed.length) {
848
+ rprint("No browser versions installed.", "yellow");
849
+ return;
850
+ }
851
+ const choices = installed.map((v) => {
852
+ const tag = installedLabel(v);
853
+ const suffix = tag ? ` (${tag})` : "";
854
+ return [
855
+ v.channelPath + suffix + (v.isActive ? " [active]" : ""),
856
+ v,
857
+ ];
858
+ });
859
+ const target = await select(choices, "Select version to remove");
860
+ if (!target) {
861
+ rprint("Cancelled.", "yellow");
862
+ return;
863
+ }
864
+ if (yes || (await confirm(`Remove ${target.channelPath}?`))) {
865
+ removeVersion(target.path);
866
+ rprint(`Removed ${target.channelPath}`, "green");
867
+ }
868
+ return;
869
+ }
870
+ // Specific version: remove just that one
871
+ if (versionPath) {
872
+ const target = findInstalled(versionPath);
873
+ if (!target) {
874
+ rprint(`Version '${versionPath}' not found.`, "red");
875
+ return;
876
+ }
877
+ if (yes || (await confirm(`Remove ${target.channelPath}?`))) {
878
+ removeVersion(target.path);
879
+ rprint(`Removed ${target.channelPath}`, "green");
880
+ }
881
+ return;
882
+ }
883
+ // Default: remove everything
884
+ if (!fs.existsSync(INSTALL_DIR) ||
885
+ fs.readdirSync(INSTALL_DIR).length === 0) {
886
+ rprint("Nothing to remove.", "yellow");
887
+ return;
888
+ }
889
+ if (yes ||
890
+ (await confirm(`Remove the camouwolf data directory (${INSTALL_DIR})?`))) {
891
+ fs.rmSync(INSTALL_DIR, { recursive: true, force: true });
892
+ rprint("Removed camouwolf data directory.", "green");
893
+ }
894
+ });
895
+ program
896
+ .command("test")
897
+ .description("Open the Playwright inspector")
898
+ .argument("[url]")
899
+ .option("--executable-path <path>", "Path to the Camouwolf executable")
900
+ .action(async (url, { executablePath }) => {
901
+ const { Camouwolf } = await import("./sync_api.js");
902
+ const browser = await Camouwolf({
903
+ headless: false,
904
+ env: process.env,
905
+ executable_path: executablePath,
906
+ });
907
+ try {
908
+ const page = await browser.newPage();
909
+ if (url) {
910
+ await page.goto(url);
911
+ }
912
+ await page.pause();
913
+ }
914
+ finally {
915
+ await browser.close();
916
+ }
917
+ });
918
+ program
919
+ .command("server")
920
+ .description("Launch a Playwright server")
921
+ .action(async () => {
922
+ // The Python twin hands launch options to launchServer.js, which logs
923
+ // exactly this; the server runs until the process is told to stop.
924
+ const { launchServer } = await import("./server.js");
925
+ const started = performance.now();
926
+ console.info("Launching server...");
927
+ const server = await launchServer();
928
+ console.log(`Server launched: ${(performance.now() - started).toFixed(3)}ms`);
929
+ console.log("Websocket endpoint:\x1b[93m", server.wsEndpoint(), "\x1b[0m");
930
+ await new Promise((resolve) => {
931
+ const stop = () => resolve();
932
+ process.once("SIGINT", stop);
933
+ process.once("SIGTERM", stop);
934
+ });
935
+ await server.close();
936
+ });
937
+ // --------------------------------------------------------------------------
938
+ // version
939
+ // --------------------------------------------------------------------------
940
+ class VersionInfo {
941
+ rows = [];
942
+ row(label, value, fg = "green") {
943
+ this.rows.push([
944
+ style(` ${label}`, { dim: true }),
945
+ value,
946
+ fg === "dim" ? { dim: true } : { fg },
947
+ ]);
948
+ }
949
+ header(title) {
950
+ this.rows.push([style(title, { bold: true }), "", {}]);
951
+ }
952
+ pkg(label, version) {
953
+ if (version)
954
+ this.row(label, `v${version}`);
955
+ else
956
+ this.row(label, "?", "dim");
957
+ }
958
+ packages() {
959
+ this.header("Packages");
960
+ this.pkg("Camouwolf", LIBRARY_VERSION);
961
+ this.pkg("fpgen", installedPackageVersion("fpgen-js"));
962
+ this.pkg("Playwright", resolvedPlaywrightVersionRaw());
963
+ }
964
+ browser() {
965
+ this.header("Browser");
966
+ const config = loadConfig();
967
+ const pinned = config.pinned;
968
+ const channel = config.channel || getDefaultChannel();
969
+ // Active: what was set (channel or pinned version)
970
+ if (pinned) {
971
+ this.row("Active", `${channel.toLowerCase()}/${pinned}`);
972
+ }
973
+ else {
974
+ this.row("Active", channel.toLowerCase());
975
+ }
976
+ // Find the active installed version
977
+ const activeV = listInstalled().find((v) => v.isActive) ?? null;
978
+ if (activeV) {
979
+ this.row("Current browser", `v${activeV.version.fullString}`);
980
+ }
981
+ else {
982
+ this.row("Current browser", "Not installed", "dim");
983
+ }
984
+ if (activeV?.createdAt) {
985
+ this.row("Build date", formatAssetDate(activeV.createdAt), "dim");
986
+ }
987
+ if (activeV?.sha256) {
988
+ this.row("SHA256", activeV.sha256.slice(0, 12), "dim");
989
+ }
990
+ if (activeV) {
991
+ this.row("Installed", "Yes", "green");
992
+ }
993
+ else {
994
+ this.row("Installed", "No", "red");
995
+ }
996
+ // Check if the installed version is the latest in its own channel
997
+ if (activeV) {
998
+ const ctype = activeV.isPrerelease ? "prerelease" : "stable";
999
+ const repoCh = `${activeV.repoName}/${ctype}`;
1000
+ let isLatest = false;
1001
+ for (const repo of loadRepoCache().repos ?? []) {
1002
+ if (repo.name.toLowerCase() !== activeV.repoName.toLowerCase()) {
1003
+ continue;
1004
+ }
1005
+ const candidates = (repo.versions ?? []).filter((v) => (v.is_prerelease ?? false) === activeV.isPrerelease);
1006
+ if (candidates.length &&
1007
+ activeV.version.build === candidates[0].build) {
1008
+ isLatest = true;
1009
+ }
1010
+ break;
1011
+ }
1012
+ this.row(`Latest in ${repoCh}?`, isLatest ? "Yes" : "No", isLatest ? "green" : "red");
1013
+ }
1014
+ // Last repo sync time from the cache file mtime
1015
+ if (fs.existsSync(REPO_CACHE_FILE)) {
1016
+ this.row("Last Sync", localTimestamp(fs.statSync(REPO_CACHE_FILE).mtime), "dim");
1017
+ }
1018
+ else {
1019
+ this.row("Last Sync", "Never", "red");
1020
+ }
1021
+ }
1022
+ geoip() {
1023
+ this.header("GeoIP");
1024
+ if (!allowGeoip()) {
1025
+ this.row("Status", "Not supported (install camouwolf[geoip])", "dim");
1026
+ return;
1027
+ }
1028
+ const mmdbPath = getMmdbPath();
1029
+ if (fs.existsSync(mmdbPath)) {
1030
+ this.row("Database", loadGeoipConfig().name ?? "Unknown");
1031
+ this.row("Updated", localTimestamp(fs.statSync(mmdbPath).mtime), "dim");
1032
+ }
1033
+ else {
1034
+ this.row("Database", "Not installed", "dim");
1035
+ }
1036
+ }
1037
+ storage() {
1038
+ this.header("Storage");
1039
+ this.row("Install path", INSTALL_DIR, "cyan");
1040
+ this.row("Browser(s) directory size", dirSize(BROWSERS_DIR), "dim");
1041
+ if (allowGeoip()) {
1042
+ this.row("GeoIP database size", dirSize(GEOIP_DIR), "dim");
1043
+ }
1044
+ this.row("Config file", CONFIG_FILE, "cyan");
1045
+ this.row("Repo cache", REPO_CACHE_FILE, "cyan");
1046
+ }
1047
+ async printAll() {
1048
+ this.packages();
1049
+ this.browser();
1050
+ this.geoip();
1051
+ this.storage();
1052
+ // rich's Table.grid(padding=(0, 2)): the first column padded to its
1053
+ // widest cell, then two spaces.
1054
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: strips ANSI codes to measure
1055
+ const visible = (s) => s.replace(/\x1b\[[0-9;]*m/g, "").length;
1056
+ const width = Math.max(...this.rows.map(([label]) => visible(label)));
1057
+ for (const [label, value, st] of this.rows) {
1058
+ const pad = " ".repeat(width - visible(label));
1059
+ echo(value ? `${label}${pad} ${style(value, st)}` : label);
1060
+ }
1061
+ }
1062
+ }
1063
+ /** "%Y-%m-%d %H:%M" in local time. */
1064
+ function localTimestamp(d) {
1065
+ const p = (n) => String(n).padStart(2, "0");
1066
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
1067
+ }
1068
+ function dirSize(dir) {
1069
+ if (!fs.existsSync(dir))
1070
+ return "Nothing here";
1071
+ let total = 0;
1072
+ const walk = (current) => {
1073
+ for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
1074
+ const full = path.join(current, entry.name);
1075
+ if (entry.isDirectory())
1076
+ walk(full);
1077
+ else if (entry.isFile())
1078
+ total += fs.statSync(full).size;
1079
+ }
1080
+ };
1081
+ walk(dir);
1082
+ let size = total;
1083
+ for (const unit of ["B", "KB", "MB"]) {
1084
+ if (size < 1024) {
1085
+ return unit === "B" ? `${size} B` : `${size.toFixed(1)} ${unit}`;
1086
+ }
1087
+ size /= 1024;
1088
+ }
1089
+ return `${size.toFixed(1)} GB`;
1090
+ }
1091
+ program
1092
+ .command("gpu-xorg-config")
1093
+ .description('Print the Xorg config headless="virtual-gpu" needs for GPU')
1094
+ .argument("[gpu]")
1095
+ .action(async (gpu) => {
1096
+ const { selectGpu, xorgConfig } = await import("./gpudisplay.js");
1097
+ process.stdout.write(xorgConfig(selectGpu(gpu)));
1098
+ });
1099
+ program
1100
+ .command("gpu-setup")
1101
+ .description('Print a root script that sets this machine up for headless="virtual-gpu" on GPU')
1102
+ .argument("[gpu]")
1103
+ .action(async (gpu) => {
1104
+ const { selectGpu, setupScript } = await import("./gpudisplay.js");
1105
+ process.stdout.write(setupScript(selectGpu(gpu)));
1106
+ });
1107
+ program
1108
+ .command("version")
1109
+ .description("Display version, package, browser, and storage info")
1110
+ .action(async () => {
1111
+ await new VersionInfo().printAll();
1112
+ });
1113
+ program
1114
+ .command("active")
1115
+ .description("Print the current active version")
1116
+ .action(() => {
1117
+ const config = loadConfig();
1118
+ const pinned = config.pinned;
1119
+ const channel = config.channel || getDefaultChannel();
1120
+ const installed = listInstalled();
1121
+ const label = (v) => {
1122
+ const sha8 = (v.sha256 ?? "").slice(0, 8);
1123
+ return sha8 ? `${v.channelPath} (${sha8})` : v.channelPath;
1124
+ };
1125
+ const pin = effectivePin(config);
1126
+ if (pin) {
1127
+ const target = findInstalled(`${pin.repoName}/${pinSpec(pin)}`);
1128
+ if (target) {
1129
+ echo(`${label(target)} (paired with this release)`);
1130
+ }
1131
+ else {
1132
+ echo(`${pin.repoName}/${pinSpec(pin)} (paired with this release) `, false);
1133
+ rprint("(not fetched)", "yellow");
1134
+ }
1135
+ return;
1136
+ }
1137
+ if (pinned) {
1138
+ const pinnedSha = config.pinned_sha;
1139
+ const target = pinnedSha
1140
+ ? (installed.find((v) => v.sha256 === pinnedSha) ?? null)
1141
+ : findInstalled(`${channel.toLowerCase()}/${pinned}`);
1142
+ if (target) {
1143
+ echo(label(target));
1144
+ }
1145
+ else {
1146
+ echo(`${channel.toLowerCase()}/${pinned} `, false);
1147
+ rprint("(not fetched)", "yellow");
1148
+ }
1149
+ return;
1150
+ }
1151
+ for (const v of installed) {
1152
+ if (v.isActive) {
1153
+ echo(label(v));
1154
+ return;
1155
+ }
1156
+ }
1157
+ echo(`${channel.toLowerCase()} `, false);
1158
+ rprint("(not fetched)", "yellow");
1159
+ });
1160
+ program
1161
+ .command("path")
1162
+ .description("Print the install directory path")
1163
+ .action(() => {
1164
+ echo(INSTALL_DIR);
1165
+ });
1166
+ program
1167
+ .command("defaults")
1168
+ .description("Copy the launch defaults to your own defaults file, if you have none yet, and print its path")
1169
+ .action(() => {
1170
+ echo(writeUserDefaults(PRODUCT, DEFAULTS_FILE));
1171
+ });
1172
+ program
1173
+ .parseAsync(process.argv)
1174
+ .catch((error) => {
1175
+ rprint(error instanceof CommandFailed
1176
+ ? error.message
1177
+ : `Error: ${errorMessage(error)}`, "red");
1178
+ process.exitCode = 1;
1179
+ })
1180
+ .finally(closePrompts);