Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.
Rust chatgptclaudeclidesktopdesktop-appelectron-alternativegeminilinuxmacosnativefierno-electronrusttauriweb-to-desktopwebsite-to-appwebviewwindowsyoutube
#!/usr/bin/env node
import log from 'loglevel';
import chalk from 'chalk';
import updateNotifier from 'update-notifier';
import path from 'path';
import os from 'os';
import fsExtra from 'fs-extra';
import prompts from 'prompts';
import { execa, execaSync } from 'execa';
import crypto from 'crypto';
import ora from 'ora';
import fs from 'fs';
import { fileURLToPath } from 'url';
import { setTimeout as setTimeout$1 } from 'timers/promises';
import fs$1 from 'fs/promises';
import { InvalidArgumentError, program as program$1, Option } from 'commander';
import * as psl from 'psl';
import { dir } from 'tmp-promise';
import { fileTypeFromBuffer } from 'file-type';
var name = "pake-cli";
var version = "3.21.0";
var description = "Turn any website into a lightweight desktop app with one command. 一键把网站打包成轻量桌面应用。";
var homepage = "https://pake.run";
var engines = {
node: ">=22.12.0"
};
var packageManager = "[email protected]";
var bin = {
pake: "dist/cli.js"
};
var repository = {
type: "git",
url: "git+https://github.com/tw93/Pake.git"
};
var author = {
name: "Tw93",
email: "[email protected]"
};
var keywords = [
"pake",
"pake-cli",
"rust",
"tauri",
"no-electron",
"electron-alternative",
"desktop-app",
"webview",
"website-to-app",
"productivity"
];
var files = [
"LICENSE-EXCEPTION",
"llms.txt",
"dist/cli.js",
"src-tauri"
];
var scripts = {
start: "pnpm run dev",
dev: "pnpm run tauri dev",
build: "tauri build",
"build:debug": "tauri build --debug",
"build:mac": "tauri build --target universal-apple-darwin",
analyze: "cd src-tauri && cargo bloat --release --crates",
tauri: "tauri",
cli: "cross-env NODE_ENV=development rollup -c -w",
"cli:dev": "cross-env NODE_ENV=development rollup -c -w",
"cli:build": "cross-env NODE_ENV=production rollup -c",
test: "pnpm run cli:build && cross-env PAKE_CREATE_APP=1 node tests/index.js",
format: "prettier --write . --ignore-unknown && find tests -name '*.js' -exec sed -i '' 's/[[:space:]]*$//' {} \\; && cd src-tauri && cargo fmt --verbose",
"format:check": "prettier --check . --ignore-unknown",
"release:check": "node scripts/check-release-version.mjs && pnpm run format:check && npx vitest run && pnpm run cli:build && npm pack --dry-run --ignore-scripts",
update: "pnpm update --verbose && cd src-tauri && cargo update",
prepublishOnly: "pnpm run cli:build"
};
var type = "module";
var exports$1 = "./dist/cli.js";
var license = "GPL-3.0-or-later";
var dependencies = {
"@tauri-apps/cli": "^2.12.6",
chalk: "^6.0.1",
commander: "^15.1.0",
execa: "^10.2.1",
"file-type": "^22.3.0",
"fs-extra": "^11.4.1",
loglevel: "^1.9.2",
ora: "^10.0.0",
prompts: "^2.4.2",
psl: "^1.15.0",
sharp: "^0.35.5",
"tmp-promise": "^3.0.3",
"update-notifier": "^7.3.1"
};
var devDependencies = {
"@rollup/plugin-alias": "^6.0.1",
"@rollup/plugin-commonjs": "^29.0.3",
"@rollup/plugin-json": "^6.1.0",
"@rollup/plugin-replace": "^6.0.3",
"@types/fs-extra": "^11.0.4",
"@types/node": "^26.6.6",
"@types/prompts": "^2.4.9",
"@types/tmp": "^0.2.6",
"@types/update-notifier": "^6.0.9",
"cross-env": "^10.1.0",
prettier: "^3.10.1",
rollup: "^4.68.8",
"rollup-plugin-typescript2": "^0.37.0",
tslib: "^2.9.1",
typescript: "^6.0.3",
vite: "^8.3.8",
vitest: "^5.1.1"
};
var pnpm = {
overrides: {
sharp: "^0.35.5",
"@img/sharp-libvips-darwin-arm64": "1.3.4",
tmp: "0.2.7"
},
onlyBuiltDependencies: [
"esbuild",
"sharp"
]
};
var packageJson = {
name: name,
version: version,
description: description,
homepage: homepage,
engines: engines,
packageManager: packageManager,
bin: bin,
repository: repository,
author: author,
keywords: keywords,
files: files,
scripts: scripts,
type: type,
exports: exports$1,
license: license,
dependencies: dependencies,
devDependencies: devDependencies,
pnpm: pnpm
};
// Stable exit-code contract: 0 success, 2 invalid input, 3 build/network
// failure, 4 missing environment, 1 unexpected. Documented in cli-usage docs.
const ERROR_EXIT_CODES = {
INVALID_INPUT: 2,
BUILD_FAILED: 3,
NETWORK: 3,
ENV_MISSING: 4,
UNEXPECTED: 1,
};
let machineMode = false;
const capturedWarnings = [];
/**
* Route all loglevel output to stderr, capture warnings for the final JSON
* result, and strip ANSI colors. Must be called before any logging happens.
*/
function enableMachineMode() {
if (machineMode)
return;
machineMode = true;
chalk.level = 0;
log.methodFactory = (methodName) => {
return (...args) => {
if (methodName === 'warn') {
capturedWarnings.push(args.map(String).join(' '));
}
console.error(...args);
};
};
// Rebuild logging methods with the new factory.
log.setLevel(log.getLevel());
}
function isMachineMode() {
return machineMode;
}
function getCapturedWarnings() {
return [...capturedWarnings];
}
/**
* Whether Pake may prompt the user. False in machine mode, without a TTY,
* or inside CI, where prompts would hang or produce garbage.
*/
function isInteractive() {
return (!machineMode &&
Boolean(process.stdin.isTTY) &&
Boolean(process.stdout.isTTY) &&
!process.env.CI &&
!process.env.GITHUB_ACTIONS);
}
function printJsonResult(result) {
process.stdout.write(`${JSON.stringify(result)}\n`);
}
// Generates a stable identifier based on the app URL (and optionally name).
// When name is provided it is included in the hash so two apps wrapping
// the same URL can coexist. Omitting name preserves backward compatibility
// with identifiers generated before V3.10.1.
function getIdentifier(url, name) {
const hashInput = name ? `${url}::${name}` : url;
const postFixHash = crypto
.createHash('md5')
.update(hashInput)
.digest('hex')
.substring(0, 6);
return `com.pake.a${postFixHash}`;
}
function resolveIdentifier(url, explicitName, customIdentifier) {
const trimmedIdentifier = customIdentifier?.trim();
if (trimmedIdentifier) {
if (!/^[a-zA-Z][a-zA-Z0-9.-]*[a-zA-Z0-9]$/.test(trimmedIdentifier)) {
throw new Error(`Invalid identifier "${trimmedIdentifier}". Must start with a letter, ` +
`contain only letters, digits, hyphens, and dots, and end with a letter or digit.`);
}
return trimmedIdentifier;
}
return getIdentifier(url, explicitName);
}
async function promptText(message, initial) {
const response = await prompts({
type: 'text',
name: 'content',
message,
initial,
});
return response.content;
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function getSpinner(text) {
const loadingType = {
interval: 80,
frames: ['✦', '✶', '✺', '✵', '✸', '✹', '✺'],
};
return ora({
text: `${chalk.cyan(text)}\n`,
spinner: loadingType,
color: 'cyan',
// In machine mode stdout must stay parseable and stderr low-noise.
isSilent: isMachineMode(),
}).start();
}
const TRUE_VALUES = new Set(['1', 'true', 'yes', 'on']);
const CN_MIRROR_ENV = 'PAKE_USE_CN_MIRROR';
function isCnMirrorEnabled(value = process.env[CN_MIRROR_ENV]) {
return TRUE_VALUES.has((value ?? '').trim().toLowerCase());
}
const { platform: platform$2 } = process;
const IS_MAC = platform$2 === 'darwin';
const IS_WIN = platform$2 === 'win32';
const IS_LINUX = platform$2 === 'linux';
// Distro IDs / ID_LIKE families that ship an RPM-based package manager.
const RPM_FAMILY_IDS = new Set([
'rhel',
'fedora',
'centos',
'rocky',
'almalinux',
'ol', // Oracle Linux
'oracle',
'amzn', // Amazon Linux
'mariner',
'azurelinux',
'suse',
'opensuse',
'opensuse-leap',
'opensuse-tumbleweed',
'sles',
]);
// Distro IDs / ID_LIKE families that ship a DEB-based package manager.
const DEB_FAMILY_IDS = new Set([
'debian',
'ubuntu',
'linuxmint',
'pop',
'elementary',
'kali',
'raspbian',
'devuan',
]);
// Parse the shell-style key=value pairs of an /etc/os-release file, stripping
// the optional surrounding quotes around values.
function parseOsRelease(content) {
const fields = {};
for (const rawLine of content.split('\n')) {
const line = rawLine.trim();
if (!line || line.startsWith('#'))
continue;
const separator = line.indexOf('=');
if (separator === -1)
continue;
const key = line.slice(0, separator).trim();
let value = line.slice(separator + 1).trim();
if (value.length >= 2 &&
((value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'")))) {
value = value.slice(1, -1);
}
if (key)
fields[key] = value;
}
return fields;
}
// Detect the package family from /etc/os-release. The distro's own ID wins over
// ID_LIKE hints, and an unknown distro falls back to 'deb' to preserve Pake's
// historical default. Accepts content directly so the decision is unit-testable
// without a real /etc/os-release.
function detectLinuxPackageFamily(osReleaseContent) {
let content = osReleaseContent;
if (content === undefined) {
try {
content = fs.readFileSync('/etc/os-release', 'utf-8');
}
catch {
return 'deb';
}
}
const fields = parseOsRelease(content);
const id = (fields.ID ?? '').toLowerCase().trim();
const idLike = (fields.ID_LIKE ?? '')
.toLowerCase()
.split(/\s+/)
.filter(Boolean);
for (const token of [id, ...idLike]) {
if (DEB_FAMILY_IDS.has(token))
return 'deb';
if (RPM_FAMILY_IDS.has(token))
return 'rpm';
}
return 'deb';
}
// Default Linux bundle targets, chosen by the host distro's package family so
// RPM-based distros (Fedora/RHEL/Oracle/Rocky/Alma/openSUSE) get a native .rpm
// instead of a .deb their package manager cannot install. AppImage stays as a
// universal fallback in both cases.
function getDefaultLinuxTargets() {
return detectLinuxPackageFamily() === 'rpm' ? 'rpm,appimage' : 'deb,appimage';
}
// Convert the current module URL to a file path
const currentModulePath = fileURLToPath(import.meta.url);
// Resolve the parent directory of the current module
const packageDirectory = path.join(path.dirname(currentModulePath), '..');
let npmDirectory = packageDirectory;
let tauriConfigDirectory = path.join(npmDirectory, 'src-tauri', '.pake');
// A CLI invocation owns one build workspace. Keep template resolution separate
// from generated paths so packaging never rewrites the installed package.
function setBuildDirectory(directory) {
npmDirectory = directory;
tauriConfigDirectory = path.join(directory, 'src-tauri', '.pake');
}
const logger = {
info(...msg) {
log.info(...msg.map((m) => chalk.white(m)));
},
debug(...msg) {
log.debug(...msg);
},
error(...msg) {
log.error(...msg.map((m) => chalk.red(m)));
},
warn(...msg) {
log.warn(...msg.map((m) => chalk.yellow(m)));
},
success(...msg) {
log.info(...msg.map((m) => chalk.green(m)));
},
};
/**
* Error class used for user-facing CLI errors.
*
* The top-level catch in `bin/cli.ts` prints `message` directly without a
* stack trace and exits with the code mapped from `code` (see
* ERROR_EXIT_CODES in utils/output.ts). Use this for predictable failures
* (invalid names, missing files, etc.) so users see a clean message instead
* of a Node.js stack dump. `code` and `hint` also feed the `--json` result.
*/
class PakeError extends Error {
constructor(message, options) {
super(message);
this.isUserError = true;
this.name = 'PakeError';
this.code = options?.code;
this.hint = options?.hint;
}
}
function isPakeError(error) {
return (error instanceof PakeError ||
(typeof error === 'object' &&
error !== null &&
error.isUserError === true));
}
/** Check the local launcher and native binding, not just an installed manifest. */
async function hasReadyTauriCli(directory) {
const modules = path.join(directory, 'node_modules');
const launcher = path.join(modules, '.bin', process.platform === 'win32' ? 'tauri.cmd' : 'tauri');
const entry = path.join(modules, '@tauri-apps', 'cli', 'tauri.js');
try {
await fsExtra.access(launcher, process.platform === 'win32' ? fsExtra.constants.F_OK : fsExtra.constants.X_OK);
await execa(process.execPath, [entry, '--version'], {
cwd: directory,
stdio: 'ignore',
timeout: 10000,
});
return true;
}
catch {
return false;
}
}
let cancellation;
function beginBuildCancellation() {
const scope = { controller: new AbortController() };
cancellation = scope;
const cancel = (signal) => scope.controller.abort(new PakeError(`Build cancelled (${signal}).`, { code: 'BUILD_FAILED' }));
const interrupt = () => cancel('SIGINT');
const terminate = () => cancel('SIGTERM');
process.on('SIGINT', interrupt);
process.on('SIGTERM', terminate);
return () => {
process.off('SIGINT', interrupt);
process.off('SIGTERM', terminate);
if (cancellation === scope)
cancellation = undefined;
};
}
function getBuildCancellationSignal() {
return cancellation?.controller.signal;
}
function preventBuildWorkspaceCleanup(reason) {
if (cancellation)
cancellation.unsafeCleanup = reason;
}
function throwIfBuildCancelled() {
getBuildCancellationSignal()?.throwIfAborted();
}
/** Copy only build inputs; cached or previously generated user content is not a template. */
async function createBuildWorkspace(sourceDirectory) {
const directory = await fsExtra.mkdtemp(path.join(os.tmpdir(), 'pake-build-'));
try {
for (const file of [
'package.json',
'pnpm-lock.yaml',
'package-lock.json',
'rust-toolchain.toml',
'rust-toolchain',
]) {
const source = path.join(sourceDirectory, file);
if (await fsExtra.pathExists(source))
await fsExtra.copy(source, path.join(directory, file));
}
const sourceTauri = path.join(sourceDirectory, 'src-tauri');
await fsExtra.copy(sourceTauri, path.join(directory, 'src-tauri'), {
filter: (source) => !['target', '.pake', 'gen'].includes(path.relative(sourceTauri, source).split(path.sep)[0]),
});
await fsExtra.ensureDir(path.join(directory, 'dist'));
// Keep the CLI runnable while local input staging replaces this workspace's dist.
await fsExtra.copy(path.join(sourceDirectory, 'dist', 'cli.js'), path.join(directory, 'dist', 'cli.js'));
const modules = path.join(sourceDirectory, 'node_modules');
if (await hasReadyTauriCli(sourceDirectory)) {
await fsExtra.symlink(modules, path.join(directory, 'node_modules'), process.platform === 'win32' ? 'junction' : 'dir');
}
return directory;
}
catch (error) {
await fsExtra.remove(directory);
throw error;
}
}
/** Hold the cache through artifact copying, beyond Cargo's own compile lock. */
async function acquireBuildCache(targetDirectory) {
await fsExtra.ensureDir(targetDirectory);
const lock = path.join(targetDirectory, '.pake-build.lock');
const started = Date.now();
let announced = false;
for (;;) {
throwIfBuildCancelled();
try {
const handle = await fsExtra.open(lock, 'wx');
try {
fsExtra.writeFileSync(handle, String(process.pid));
}
finally {
fsExtra.closeSync(handle);
}
let released = false;
return async () => {
if (!released) {
await fsExtra.remove(lock);
released = true;
}
};
}
catch (error) {
if (error.code !== 'EEXIST')
throw error;
}
try {
const owner = Number(await fsExtra.readFile(lock, 'utf8'));
if (Number.isInteger(owner) && owner > 0) {
try {
process.kill(owner, 0);
}
catch (error) {
if (error.code === 'ESRCH') {
// Read-then-unlink cannot atomically reclaim a dead owner's lock:
// another waiter may already have acquired a new one at this path.
throw new PakeError('A previous Pake process left a compilation cache lock.', {
code: 'BUILD_FAILED',
hint: `After stopping other Pake builds, remove ${lock} and retry.`,
});
}
}
}
}
catch (error) {
if (error.code === 'ENOENT')
continue;
throw error;
}
if (Date.now() - started > 900000) {
throw new PakeError('Another Pake build is still using the compilation cache.', {
code: 'BUILD_FAILED',
hint: 'Wait for that build to finish, then retry.',
});
}
if (!announced) {
logger.info('Waiting for another Pake build to finish using the compilation cache...');
announced = true;
}
await setTimeout$1(200);
}
}
async function enterBuildWorkspace() {
const previousTarget = process.env.CARGO_TARGET_DIR;
const targetDirectory = path.resolve(packageDirectory, previousTarget || 'src-tauri/target');
const directory = await createBuildWorkspace(packageDirectory);
let release;
setBuildDirectory(directory);
process.env.CARGO_TARGET_DIR = targetDirectory;
const leave = async () => {
setBuildDirectory(packageDirectory);
if (previousTarget === undefined)
delete process.env.CARGO_TARGET_DIR;
else
process.env.CARGO_TARGET_DIR = previousTarget;
if (cancellation?.unsafeCleanup) {
logger.warn(`Build processes could not be confirmed stopped; keeping workspace ${directory} and its cache lock: ${cancellation.unsafeCleanup}`);
return;
}
try {
await fsExtra.remove(directory);
}
catch (error) {
logger.warn(`Could not remove the temporary build workspace ${directory}: ${String(error)}`);
}
finally {
try {
await release?.();
}
catch (error) {
logger.warn(`Could not release the compilation cache lock: ${String(error)}`);
}
}
};
if (getBuildCancellationSignal()?.aborted) {
await leave();
throwIfBuildCancelled();
}
return Object.assign(leave, {
async lockCache() {
release = await acquireBuildCache(targetDirectory);
},
});
}
async function terminateBuildTree(pid) {
if (process.platform === 'win32') {
try {
await execa('taskkill', ['/pid', String(pid), '/T', '/F'], {
timeout: 5000,
windowsHide: true,
});
}
catch (error) {
// 128 is "process not found": a failed build has usually exited before
// it rejects. Treating that as unconfirmed kept the cache lock, and
// every later build refused to start until it was deleted by hand.
if (error.exitCode !== 128)
throw error;
}
return;
}
const killGroup = (signal) => {
try {
process.kill(-pid, signal);
}
catch (error) {
if (error.code !== 'ESRCH')
throw error;
}
};
killGroup('SIGTERM');
const started = Date.now();
for (;;) {
// The package manager can exit before its compiler descendants. Only
// release the cache once no live member of their process group remains.
// Zombies have already exited and cannot write artifacts.
const { stdout } = await execa('ps', ['-axo', 'pgid=,stat='], {
timeout: 1000,
});
const alive = stdout.split('\n').some((line) => {
const [group, state] = line.trim().split(/\s+/);
return Number(group) === pid && state && !state.startsWith('Z');
});
if (!alive)
return;
if (Date.now() - started > 5000)
throw new Error('Build process group did not stop.');
if (Date.now() - started >= 250)
killGroup('SIGKILL');
await setTimeout$1(25);
}
}
async function shellExec(command, timeout = 300000, env) {
const signal = getBuildCancellationSignal();
signal?.throwIfAborted();
try {
const subprocess = execa(command.executable, command.args, {
cwd: command.cwd ?? npmDirectory,
// Use 'inherit' to show all output directly to user in real-time.
// This ensures linuxdeploy and other tool outputs are visible during builds.
// In machine mode (--json) stdout is reserved for the final JSON result,
// so subprocess stdout is rerouted to stderr instead.
stdin: 'inherit',
stdout: isMachineMode() ? process.stderr : 'inherit',
stderr: 'inherit',
shell: false,
detached: Boolean(signal) && process.platform !== 'win32',
timeout,
env: env ? { ...process.env, ...env } : process.env,
});
let termination;
const cancel = () => {
if (termination || subprocess.pid === undefined)
return;
termination = terminateBuildTree(subprocess.pid).catch((error) => {
preventBuildWorkspaceCleanup(String(error));
subprocess.kill('SIGKILL');
});
};
signal?.addEventListener('abort', cancel, { once: true });
if (signal?.aborted)
cancel();
try {
const { exitCode } = await subprocess;
return exitCode;
}
catch (error) {
// A timed-out or failed package manager can leave compiler descendants.
// Use the same tree barrier before the caller releases its cache lock.
if (signal)
cancel();
throw error;
}
finally {
signal?.removeEventListener('abort', cancel);
await termination;
signal?.throwIfAborted();
}
}
catch (error) {
if (signal?.aborted)
throw signal.reason;
const description = JSON.stringify([command.executable, ...command.args]);
const exitCode = error.exitCode ?? 'unknown';
const errorMessage = error.message || 'Unknown error occurred';
if (error.timedOut) {
throw new Error(`Command timed out after ${timeout}ms: ${description}. Try increasing timeout or check network connectivity.`);
}
// AppImage/linuxdeploy guidance is added by the caller (BaseBuilder), which
// knows the build target. We only have the command line here (the tool's
// diagnostics stream to the terminal via stdio:inherit, not into the error).
throw new Error(`Error occurred while executing command ${description}. Exit code: ${exitCode}. Details: ${errorMessage}`);
}
}
function normalizePathForComparison(targetPath) {
const normalized = path.normalize(targetPath);
return IS_WIN ? normalized.toLowerCase() : normalized;
}
function getCargoHomeCandidates() {
const candidates = new Set();
if (process.env.CARGO_HOME) {
candidates.add(process.env.CARGO_HOME);
}
const homeDir = os.homedir();
if (homeDir) {
candidates.add(path.join(homeDir, '.cargo'));
}
if (IS_WIN && process.env.USERPROFILE) {
candidates.add(path.join(process.env.USERPROFILE, '.cargo'));
}
return Array.from(candidates).filter(Boolean);
}
function ensureCargoBinOnPath() {
const currentPath = process.env.PATH || '';
const segments = currentPath.split(path.delimiter).filter(Boolean);
const normalizedSegments = new Set(segments.map((segment) => normalizePathForComparison(segment)));
const additions = [];
let cargoHomeSet = Boolean(process.env.CARGO_HOME);
for (const cargoHome of getCargoHomeCandidates()) {
const binDir = path.join(cargoHome, 'bin');
if (fsExtra.pathExistsSync(binDir) &&
!normalizedSegments.has(normalizePathForComparison(binDir))) {
additions.push(binDir);
normalizedSegments.add(normalizePathForComparison(binDir));
}
if (!cargoHomeSet && fsExtra.pathExistsSync(cargoHome)) {
process.env.CARGO_HOME = cargoHome;
cargoHomeSet = true;
}
}
if (additions.length) {
const prefix = additions.join(path.delimiter);
process.env.PATH = segments.length
? `${prefix}${path.delimiter}${segments.join(path.delimiter)}`
: prefix;
}
}
function ensureRustEnv() {
ensureCargoBinOnPath();
}
async function installRust() {
const spinner = getSpinner('Downloading Rust...');
try {
if (IS_WIN) {
await shellExec({
executable: 'winget',
args: ['install', '--id', 'Rustlang.Rustup'],
});
}
else {
const useCnMirror = isCnMirrorEnabled();
const tempDir = await fsExtra.mkdtemp(path.join(os.tmpdir(), 'pake-rustup-'));
try {
const scriptPath = path.join(tempDir, 'rustup-init.sh');
await shellExec({
executable: 'curl',
args: [
'--proto',
'=https',
'--tlsv1.2',
'-sSf',
'-o',
scriptPath,
useCnMirror
? 'https://rsproxy.cn/rustup-init.sh'
: 'https://sh.rustup.rs',
],
});
await shellExec({
executable: 'sh',
args: useCnMirror ? [scriptPath] : [scriptPath, '-y'],
}, 300000, useCnMirror
? {
RUSTUP_DIST_SERVER: 'https://rsproxy.cn',
RUSTUP_UPDATE_ROOT: 'https://rsproxy.cn/rustup',
}
: undefined);
}
finally {
await fsExtra.remove(tempDir);
}
}
spinner.succeed(chalk.green('✔ Rust installed successfully!'));
ensureRustEnv();
}
catch (error) {
spinner.fail(chalk.red('✕ Rust installation failed!'));
// The CLI owns error reporting and workspace/cache cleanup.
throw error;
}
}
function checkRustInstalled() {
ensureCargoBinOnPath();
try {
execaSync('rustc', ['--version']);
return true;
}
catch {
return false;
}
}
function getVsWherePath() {
const programFilesX86 = process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)';
return path.join(programFilesX86, 'Microsoft Visual Studio', 'Installer', 'vswhere.exe');
}
/**
* Detects Visual Studio Build Tools the way rustc itself does: via the VS
* installer's vswhere.exe, not PATH. cl.exe/link.exe are normally absent
* from PATH even on a fully working MSVC setup (rustc locates them through
* the same registry vswhere reads), so checking PATH directly would warn on
* most MSVC machines.
*/
function hasWindowsMsvcBuildTools(arch = process.arch) {
const vswhere = getVsWherePath();
if (!fsExtra.pathExistsSync(vswhere))
return false;
const component = arch === 'arm64'
? 'Microsoft.VisualStudio.Component.VC.Tools.ARM64'
: 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64';
try {
const { stdout } = execaSync(vswhere, [
'-products',
'*',
'-requires',
component,
'-property',
'installationPath',
]);
return stdout.trim().length > 0;
}
catch {
return false;
}
}
/**
* MinGW/MSYS2's gcc drives the GNU Windows target directly off PATH (no
* registry lookup involved), so a PATH check is the correct signal here.
*/
function hasWindowsGnuToolchain() {
try {
execaSync('gcc', ['--version'], { stdio: 'ignore' });
return true;
}
catch {
return false;
}
}
async function combineFiles(files, output) {
const contents = await Promise.all(files.map(async (file) => {
if (file.toLowerCase().endsWith('.css')) {
const fileContent = await fs$1.readFile(file, 'utf-8');
return `window.addEventListener('DOMContentLoaded', (_event) => {
const css = ${JSON.stringify(fileContent)};
if (typeof window.__PAKE_INJECT_STYLE__ === 'function') {
window.__PAKE_INJECT_STYLE__(css);
} else {
const style = document.createElement('style');
style.textContent = css;
document.head.appendChild(style);
}
});`;
}
const fileContent = await fs$1.readFile(file);
// Keep the closing `});` on its own line. If the injected file ends in a
// line comment without a trailing newline, appending ` });` on the same
// line would comment it out and break the wrapper (mirrors the .css
// branch above, which already closes on a separate line).
return ("window.addEventListener('DOMContentLoaded', (_event) => {\n" +
fileContent +
'\n});');
}));
await fs$1.writeFile(output, contents.join('\n'));
return files;
}
function generateSafeFilename(name) {
return name
.replace(/[<>:"/\\|?*]/g, '_')
.replace(/\s+/g, '_')
.replace(/\.+$/g, '')
.slice(0, 255);
}
function getSafeAppName(name) {
return generateSafeFilename(name).toLowerCase();
}
function generateLinuxPackageName(name) {
return name
.toLowerCase()
.replace(/[^a-z0-9\u4e00-\u9fff]+/g, '-')
.replace(/^-+|-+$/g, '')
.replace(/-+/g, '-');
}
function generateIdentifierSafeName(name) {
const cleaned = name.replace(/[^a-zA-Z0-9\u4e00-\u9fff]/g, '').toLowerCase();
if (cleaned === '') {
const fallback = Array.from(name)
.map((char) => {
const code = char.charCodeAt(0);
if ((code >= 48 && code <= 57) ||
(code >= 65 && code <= 90) ||
(code >= 97 && code <= 122)) {
return char.toLowerCase();
}
return code.toString(16);
})
.join('')
.slice(0, 50);
return fallback || 'pake-app';
}
return cleaned;
}
const LINUX_TARGET_TYPES = ['deb', 'appimage', 'rpm', 'zst'];
// Returns the valid Linux build targets from a comma-separated targets
// string, preserving LINUX_TARGET_TYPES order. Unknown entries are dropped.
function filterLinuxTargets(targets) {
const requested = targets.split(',').map((target) => target.trim());
return LINUX_TARGET_TYPES.filter((target) => requested.includes(target));
}
function needsTemporaryDebForZst(targets) {
return targets.includes('zst') && !targets.includes('deb');
}
// Resolves the Tauri `bundle.targets` list for a Linux build from a
// comma-separated --targets string (e.g. the distro-aware default
// "deb,appimage"). zst is repacked from the deb payload, so it maps to a deb
// bundle. hasValidTarget is false only when no known target is present, which
// is the single case that should warn and fall back to the default.
function resolveLinuxBundleTargets(targets) {
const requested = filterLinuxTargets(targets);
const bundleTargets = [
...new Set(requested.map((target) => (target === 'zst' ? 'deb' : target))),
];
return { bundleTargets, hasValidTarget: requested.length > 0 };
}
// Extracts the domain from a given URL.
function getDomain(inputUrl) {
try {
const url = new URL(inputUrl);
// Use PSL to parse domain names.
const parsed = psl.parse(url.hostname);
// If domain is available, split it and return the SLD.
if ('domain' in parsed && parsed.domain) {
return parsed.domain.split('.')[0];
}
else {
return null;
}
}
catch (error) {
return null;
}
}
// Appends 'https://' protocol to the URL if not present.
function appendProtocol(inputUrl) {
// URL accepts a bare host:port as an opaque scheme. Recognize dotted
// hosts and localhost without reinterpreting other schemes like tel:.
if (/^(?:localhost|[a-z0-9-]+(?:\.[a-z0-9-]+)+\.?):\d+(?:[/?#]|$)/i.test(inputUrl)) {
return `https://${inputUrl}`;
}
try {
new URL(inputUrl);
return inputUrl;
}
catch {
return `https://${inputUrl}`;
}
}
// Normalizes the URL by ensuring it has a protocol and is valid.
function normalizeUrl(urlToNormalize) {
const urlWithProtocol = appendProtocol(urlToNormalize);
try {
new URL(urlWithProtocol);
return urlWithProtocol;
}
catch (err) {
throw new Error(`Your url "${urlWithProtocol}" is invalid: ${err.message}`);
}
}
// Compiles a comma-separated domain list into a regex source for
// internal_url_regex. Each domain is escaped and matched against the URL host
// and its subdomains so path or query text cannot accidentally opt a link in.
// Returns '' for empty input.
function safeDomainsToRegex(domains) {
const escaped = domains
.split(',')
.map((domain) => domain.trim().toLowerCase())
.filter(Boolean)
.map((domain) => domain.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
return escaped.length
? `^https?:\\/\\/(?:[^/?#@]+\\.)*(?:${escaped.join('|')})(?::\\d+)?(?:[/?#]|$)`
: '';
}
function validateNumberInput(value) {
if (value.trim() === '') {
throw new InvalidArgumentError('Not a number.');
}
const parsedValue = Number(value);
if (!Number.isFinite(parsedValue)) {
throw new InvalidArgumentError('Not a number.');
}
if (parsedValue < 0) {
throw new InvalidArgumentError('Must not be negative.');
}
return parsedValue;
}
// Path-shaped input (./x, ../x, /x, ~/x, C:\x). A missing path must fail
// loudly: appending https:// to "./typo" would otherwise produce a valid URL
// like https://./typo and a silently broken app (worst case for agents).
const PATH_LIKE_PATTERN = /^(\.{1,2}[\\/]|[\\/]|~[\\/]|[a-zA-Z]:[\\/])/;
function validateUrlInput(url) {
const isFile = fs.existsSync(url);
if (!isFile) {
if (PATH_LIKE_PATTERN.test(url)) {
throw new InvalidArgumentError(`Local path "${url}" does not exist. Check the path, or pass a web URL instead.`);
}
try {
return normalizeUrl(url);
}
catch (error) {
if (error instanceof Error) {
throw new InvalidArgumentError(error.message);
}
throw error;
}
}
return url;
}
function validateDownloadDirInput(value) {
if (value === '')
return value;
const homeRelative = value.startsWith('~/') ? value.slice(2) : null;
const invalidHomePath = homeRelative !== null &&
(path.isAbsolute(homeRelative) ||
(process.platform === 'win32' &&
/^(?:[a-zA-Z]:|[\\/])/.test(homeRelative)));
if (invalidHomePath ||
value.includes('\0') ||
!(path.isAbsolute(value) || value === '~' || value.startsWith('~/')) ||
(process.platform === 'win32' &&
value !== '~' &&
!value.startsWith('~/') &&
!/^(?:[a-zA-Z]:[\\/]|[\\/]{2}[^\\/]+[\\/][^\\/]+)/.test(value))) {
throw new PakeError('Invalid download directory.', {
code: 'INVALID_INPUT',
hint: 'Use an absolute path or a quoted ~/path; relative paths are not supported.',
});
}
return value;
}
// The injected link policy compiles this with `new RegExp` and, when that
// throws, only logs it and falls back to same-root-domain matching, so a typo
// would ship an app that silently ignores the option.
function validateInternalUrlRegexInput(value) {
if (value === '')
return value;
try {
new RegExp(value);
}
catch (error) {
const detail = error instanceof Error ? error.message : String(error);
throw new PakeError(`Invalid internal URL regex: ${detail}`, {
code: 'INVALID_INPUT',
hint: 'Pass a JavaScript regular expression to --internal-url-regex, or list domains with --safe-domain.',
});
}
return value;
}
const INJECT_EXTENSIONS = new Set(['.css', '.js']);
// Shared by --inject and the config "inject" field, so a bad file fails before
// anything is built. The flag has split its value on commas already; a config
// entry is one path and may hold a comma.
function validateInjectInput(inject, cwd = process.cwd()) {
if (!Array.isArray(inject))
return [];
const files = inject
.map((item) => item.trim())
.filter((item) => item.length > 0);
for (const file of files) {
if (!INJECT_EXTENSIONS.has(path.extname(file).toLowerCase())) {
throw new PakeError(`Injected file "${file}" is not a .css or .js file.`, {
code: 'INVALID_INPUT',
hint: 'Pass local CSS or JS files to --inject, separated by commas.',
});
}
const resolved = path.isAbsolute(file) ? file : path.join(cwd, file);
if (!fs.statSync(resolved, { throwIfNoEntry: false })?.isFile()) {
throw new PakeError(`Injected file not found: ${file}`, {
code: 'INVALID_INPUT',
hint: 'Relative --inject paths resolve against the current directory.',
});
}
}
return files;
}
const ACTOOL_VERSION_ARGS = [
'--version',
'--output-format=human-readable-text',
];
const ACTOOL_TIMEOUT_MS = {
version: 20000,
compile: 120000,
};
function iconPathExtension(iconPath) {
return path.extname(iconPath.replace(/[/\\]+$/, '')).toLowerCase();
}
function isIconComposerUrl(iconUrl) {
try {
const pathname = new URL(iconUrl).pathname
.replace(/\/+$/, '')
.toLowerCase();
return pathname.endsWith('.icon');
}
catch {
return iconUrl.replace(/\/+$/, '').toLowerCase().endsWith('.icon');
}
}
async function isMacOSIconComposerPackage(iconPath) {
try {
const stat = await fsExtra.stat(iconPath);
if (!stat.isDirectory()) {
return false;
}
return await fsExtra.pathExists(path.join(iconPath, 'icon.json'));
}
catch {
return false;
}
}
/** Parse `actool --version --output-format=human-readable-text`, matching Tauri. */
function parseActoolVersion(output) {
for (const rawLine of output.split('\n')) {
const line = rawLine.trim();
if (line.startsWith('short-bundle-version:')) {
const version = line.slice('short-bundle-version:'.length).trim();
return version || null;
}
}
return null;
}
function actoolMajorVersion(version) {
const major = Number.parseInt(version.split('.')[0] ?? '', 10);
return Number.isFinite(major) ? major : null;
}
function isCommandMissing(error) {
if (!error || typeof error !== 'object') {
return false;
}
const execaError = error;
return (execaError.code === 'ENOENT' ||
execaError.exitCode === 127 ||
(typeof execaError.stderr === 'string' &&
/not found|No such file/i.test(execaError.stderr)));
}
async function runActool(args, timeout) {
const options = { stdin: 'ignore', reject: false, timeout };
const attempts = [
{ file: 'xcrun', argv: ['actool', ...args] },
{ file: 'actool', argv: args },
];
for (const attempt of attempts) {
try {
const result = await execa(attempt.file, attempt.argv, options);
if (isCommandMissing(result)) {
continue;
}
return result;
}
catch (error) {
if (isCommandMissing(error)) {
continue;
}
throw error;
}
}
return null;
}
async function getActoolMajorVersion() {
const result = await runActool(ACTOOL_VERSION_ARGS, ACTOOL_TIMEOUT_MS.version);
if (!result) {
return null;
}
const version = parseActoolVersion(`${result.stdout}\n${result.stderr}`);
return version ? actoolMajorVersion(version) : null;
}
async function warnIfActoolUnavailable() {
const major = await getActoolMajorVersion();
if (major === null) {
logger.warn('✼ Could not find actool (needs Xcode 26+). Liquid Glass icons will not be compiled; the .icns fallback will be used.');
return null;
}
if (major < 26) {
logger.warn(`✼ actool ${major} is too old for Icon Composer .icon packages (need 26+ / Xcode 26). The .icns fallback will be used.`);
}
return major;
}
async function compileAssetsCar(iconPackagePath, destPath) {
const { path: tempRoot, cleanup } = await dir({ unsafeCleanup: true });
try {
const iconDest = path.join(tempRoot, 'Icon.icon');
const outputPath = path.join(tempRoot, 'out');
await fsExtra.copy(iconPackagePath, iconDest);
await fsExtra.ensureDir(outputPath);
// Flags match tauri-bundler 2.12.4 (crates/tauri-bundler/src/bundle/macos/icon.rs).
// stdin is closed so we do not inherit Node's fd 0 (tauri-apps/tauri#15315, #15991).
const args = [
iconDest,
'--compile',
outputPath,
'--output-format',
'human-readable-text',
'--notices',
'--warnings',
'--output-partial-info-plist',
path.join(outputPath, 'assetcatalog_generated_info.plist'),
'--app-icon',
'Icon',
'--include-all-app-icons',
'--accent-color',
'AccentColor',
'--enable-on-demand-resources',
'NO',
'--development-region',
'en',
'--target-device',
'mac',
'--minimum-deployment-target',
'26.0',
'--platform',
'macosx',
];
await runActool(args, ACTOOL_TIMEOUT_MS.compile);
const assetsCar = path.join(outputPath, 'Assets.car');
if (!(await fsExtra.pathExists(assetsCar))) {
return false;
}
// Copy out before the temp directory is removed in `finally`.
await fsExtra.ensureDir(path.dirname(destPath));
await fsExtra.copy(assetsCar, destPath);
return true;
}
finally {
await cleanup();
}
}
/**
* Precompile an Icon Composer package to Assets.car so Tauri's bundler
* does not have to spawn actool itself (a known hang/crash on Xcode 27).
* Returns the destination path of Assets.car, or null if compilation failed.
*/
async function precompileIconComposerAssets(iconPackagePath, destIconsDir) {
const major = await getActoolMajorVersion();
if (major === null || major < 26) {
return null;
}
await fsExtra.ensureDir(destIconsDir);
const dest = path.join(destIconsDir, 'Assets.car');
if (await compileAssetsCar(iconPackagePath, dest)) {
return dest;
}
logger.warn('✼ actool could not compile the .icon package (tauri-apps/tauri#15315, #16386). The app will use the .icns icon instead.');
return null;
}
/**
* Copy a valid .icon package (and an .icns fallback) into src-tauri/icons
* and return the paths to set on tauriConf.bundle.icon.
*/
async function applyDarwinIconComposerPackage(options) {
const { sourceIconPath, destIconsDir, safeAppName, defaultIcnsPath } = options;
await fsExtra.ensureDir(destIconsDir);
const destIconPackage = path.join(destIconsDir, `${safeAppName}.icon`);
if (path.resolve(sourceIconPath) !== path.resolve(destIconPackage)) {
await fsExtra.copy(sourceIconPath, destIconPackage);
}
const normalizedSource = sourceIconPath.replace(/[/\\]+$/, '');
const siblingIcns = path.join(path.dirname(normalizedSource), `${path.parse(normalizedSource).name}.icns`);
const destIcns = path.join(destIconsDir, `${safeAppName}.icns`);
let fallbackSource = null;
if (await fsExtra.pathExists(siblingIcns)) {
const stat = await fsExtra.stat(siblingIcns);
if (stat.isFile()) {
fallbackSource = siblingIcns;
}
}
if (!fallbackSource && (await fsExtra.pathExists(defaultIcnsPath))) {
fallbackSource = defaultIcnsPath;
}
let hasIcns = false;
if (fallbackSource) {
if (path.resolve(fallbackSource) !== path.resolve(destIcns)) {
await fsExtra.copy(fallbackSource, destIcns);
}
hasIcns = await fsExtra.pathExists(destIcns);
}
if (!hasIcns) {
logger.warn('✼ No .icns fallback found next to the .icon package, and Pake default icon.icns is missing. Older macOS will not have a static icon.');
}
await warnIfActoolUnavailable();
const compiledCar = await precompileIconComposerAssets(destIconPackage, destIconsDir);
// Tauri runs actool itself for a .icon in bundle.icon and fails the whole
// build when actool errors, so only a precompiled Assets.car goes in; when
// that could not be built, the app ships with the .icns alone.
const bundleIcon = [];
if (compiledCar) {
logger.info('✼ Precompiled Assets.car from the Icon Composer package.');
bundleIcon.push('icons/Assets.car');
}
if (hasIcns) {
bundleIcon.push(`icons/${safeAppName}.icns`);
}
if (bundleIcon.length === 0) {
bundleIcon.push(`icons/${safeAppName}.icon`);
}
return { bundleIcon };
}
/**
* Pure transform from CLI options to the window-config slice that gets
* merged into pake.json. Exposed for snapshot testing so option drift
* (e.g. a new flag added in cli-program.ts but forgotten here) is caught.
*
* Keep this function side-effect free.
*/
function buildWindowConfigOverrides(options, platform = asSupportedPlatform(process.platform)) {
const platformHideOnClose = options.hideOnClose ?? platform === 'darwin';
const platformHideTitleBar = platform === 'darwin' ? options.hideTitleBar : false;
const platformNavigationButtons = platform === 'darwin' ? Boolean(options.navigationButtons) : false;
const platformHideWindowDecorations = platform !== 'darwin' ? options.hideWindowDecorations : false;
return {
width: options.width,
height: options.height,
fullscreen: options.fullscreen,
maximize: options.maximize,
resizable: options.resizable ?? true,
hide_title_bar: platformHideTitleBar,
navigation_buttons: platformNavigationButtons,
hide_window_decorations: platformHideWindowDecorations,
activation_shortcut: options.activationShortcut,
always_on_top: options.alwaysOnTop,
dark_mode: options.darkMode,
disabled_web_shortcuts: options.disabledWebShortcuts,
hide_on_close: platformHideOnClose,
incognito: options.incognito,
restore_last_url: options.restoreLastUrl,
password_autosave: options.passwordAutosave,
title: options.title,
enable_wasm: options.wasm,
start_to_tray: options.startToTray && options.showSystemTray,
force_internal_navigation: options.forceInternalNavigation,
internal_url_regex: options.internalUrlRegex,
enable_find: options.enableFind,
zoom: options.zoom,
min_width: options.minWidth,
min_height: options.minHeight,
ignore_certificate_errors: options.ignoreCertificateErrors,
new_window: options.newWindow,
};
}
function asSupportedPlatform(platform) {
if (platform !== 'win32' && platform !== 'darwin' && platform !== 'linux') {
throw new Error(`Pake only supports win32, darwin, and linux; detected '${platform}'.`);
}
return platform;
}
async function copyTemplateConfigs() {
const srcTauriDir = path.join(npmDirectory, 'src-tauri');
await fsExtra.ensureDir(tauriConfigDirectory);
const sourceFiles = [
'tauri.conf.json',
'tauri.macos.conf.json',
'tauri.windows.conf.json',
'tauri.linux.conf.json',
'pake.json',
];
await Promise.all(sourceFiles.map(async (file) => {
const sourcePath = path.join(srcTauriDir, file);
const destPath = path.join(tauriConfigDirectory, file);
if ((await fsExtra.pathExists(sourcePath)) &&
!(await fsExtra.pathExists(destPath))) {
await fsExtra.copy(sourcePath, destPath);
}
}));
}
// Replace the CLI's own dist/ with the user's static files while keeping the
// build artifacts (cli.js) the packaged app does not need but the CLI does.
// dist_bak always holds the ORIGINAL package dist: once it exists, later
// stagings must not overwrite it with a previous user tree, or the original
// files would be unrecoverable across repeated local builds.
async function stageLocalTree(sourceDir) {
const distDir = path.join(npmDirectory, 'dist');
const distBakDir = path.join(npmDirectory, 'dist_bak');
// Resolve symlinked input up front: staging must produce a real copy, or
// the cli.js copy-back below would write through the link into the user's
// own directory.
const resolvedSource = await fsExtra.realpath(sourceDir);
const resolvedPackage = await fsExtra
.realpath(npmDirectory)
.catch(() => path.resolve(npmDirectory));
const installedPackage = await fsExtra.realpath(packageDirectory);
const packageDist = path.join(resolvedPackage, 'dist');
if (resolvedSource === installedPackage ||
installedPackage.startsWith(resolvedSource + path.sep) ||
resolvedSource === resolvedPackage ||
resolvedPackage.startsWith(resolvedSource + path.sep) ||
resolvedSource === packageDist ||
resolvedSource.startsWith(packageDist + path.sep)) {
throw new PakeError(`Local input "${sourceDir}" contains the Pake CLI installation itself.`, {
code: 'INVALID_INPUT',
hint: 'Point Pake at your built output directory, not at a directory containing pake-cli.',
});
}
try {
if (await fsExtra.pathExists(distBakDir)) {
fsExtra.removeSync(distDir);
}
else {
fsExtra.moveSync(distDir, distBakDir);
}
fsExtra.copySync(resolvedSource, distDir, {
overwrite: true,
dereference: true,
});
const filesToCopyBack = ['cli.js'];
await Promise.all(filesToCopyBack.map((file) => fsExtra.copy(path.join(distBakDir, file), path.join(distDir, file))));
}
catch (error) {
// Never leave the package without its own dist/: cli.js lives there and
// every later `pake` invocation would fail until a manual reinstall.
restoreLocalTree();
throw error;
}
}
// Put the package's original dist/ back once a local-input run is over (or
// failed). Tauri bakes `frontendDist: ../dist` into every binary, so a stale
// staged tree would leak this user's files into the next app built from the
// same install. Safe to call on any run: a present dist_bak always holds the
// original package dist, including one stranded by an older crashed run.
function restoreLocalTree() {
const distDir = path.join(npmDirectory, 'dist');
const distBakDir = path.join(npmDirectory, 'dist_bak');
if (!fsExtra.pathExistsSync(distBakDir)) {
return;
}
try {
fsExtra.removeSync(distDir);
fsExtra.moveSync(distBakDir, distDir);
}
catch (error) {
const detail = error instanceof Error ? error.message : String(error);
logger.warn(`Failed to restore the CLI's original dist/ from dist_bak: ${detail}`);
}
}
// Exported for unit tests (web fallback and directory entry guard).
async function handleLocalFile(url, useLocalFile, tauriConf) {
const pathExists = await fsExtra.pathExists(url);
if (!pathExists) {
tauriConf.pake.windows[0].url_type = 'web';
return;
}
const stat = await fsExtra.stat(url);
if (stat.isDirectory()) {
// A directory of static web assets (e.g. a generated dist/): the whole
// tree is packaged and the app entry is its root index.html.
const entryFile = 'index.html';
if (!(await fsExtra.pathExists(path.join(url, entryFile)))) {
throw new PakeError(`Local directory "${url}" has no ${entryFile} at its root.`, {
code: 'INVALID_INPUT',
hint: 'Point Pake at the built output directory that contains index.html.',
});
}
logger.info(`✺ Packaging local directory: ${url}`);
await stageLocalTree(url);
tauriConf.pake.windows[0].url = entryFile;
tauriConf.pake.windows[0].url_type = 'local';
return;
}
logger.info(`✺ Packaging local file: ${url}`);
const fileName = path.basename(url);
const distDir = path.join(npmDirectory, 'dist');
if (!useLocalFile) {
// Back up the original dist first, as stageLocalTree does, so
// restoreLocalTree can take this file out again after the run.
const distBakDir = path.join(npmDirectory, 'dist_bak');
if (!(await fsExtra.pathExists(distBakDir))) {
await fsExtra.copy(distDir, distBakDir);
}
await fsExtra.copy(url, path.join(distDir, fileName));
}
else {
await stageLocalTree(path.dirname(url));
}
tauriConf.pake.windows[0].url = fileName;
tauriConf.pake.windows[0].url_type = 'local';
}
function buildLinuxDesktopContent(name, title, linuxBinaryName) {
const chineseName = title && /[\u4e00-\u9fa5]/.test(title) ? title : null;
return `[Desktop Entry]
Version=1.0
Type=Application
Name=${name}
${chineseName ? `Name[zh_CN]=${chineseName}` : ''}
Comment=${name}
Exec=${linuxBinaryName}
Icon=${linuxBinaryName}
Categories=Network;WebBrowser;Utility;
MimeType=text/html;text/xml;application/xhtml_xml;
StartupNotify=true
StartupWMClass=${linuxBinaryName}
Terminal=false
`;
}
// Tauri always writes its own desktop entry into deb and rpm payloads, so
// shipping Pake's entry as an extra file left two launchers in the app menu.
// Rendering Pake's content through that single entry keeps exactly one.
function applyLinuxDesktopTemplate(linuxBundle, templatePath) {
linuxBundle.deb.desktopTemplate = templatePath;
if (!linuxBundle.rpm) {
linuxBundle.rpm = {};
}
linuxBundle.rpm.desktopTemplate = templatePath;
}
async function mergeLinuxConfig(options, name, tauriConf, linuxBinaryName) {
const linuxBundle = tauriConf.bundle.linux;
if (!linuxBundle) {
throw new Error('Linux bundle configuration is missing from tauri.linux.conf.json; cannot build Linux target.');
}
delete linuxBundle.deb.files;
const linuxName = generateLinuxPackageName(name);
const desktopFileName = `com.pake.${linuxName}.desktop`;
const desktopContent = buildLinuxDesktopContent(name, options.title, linuxBinaryName);
const srcAssetsDir = path.join(npmDirectory, 'src-tauri/assets');
const srcDesktopFilePath = path.join(srcAssetsDir, desktopFileName);
await fsExtra.ensureDir(srcAssetsDir);
await fsExtra.writeFile(srcDesktopFilePath, desktopContent);
applyLinuxDesktopTemplate(linuxBundle, `assets/${desktopFileName}`);
// options.targets reaches here already stripped of any -arm64 suffix by the
// LinuxBuilder constructor, and may carry several comma-separated formats
// (e.g. the distro-aware default "deb,appimage"). Validate the parsed list
// rather than string-matching the whole value, so a valid multi-target
// default no longer trips the "must be one of ..." warning on every build.
const { bundleTargets, hasValidTarget } = resolveLinuxBundleTargets(options.targets);
if (hasValidTarget) {
tauriConf.bundle.targets = bundleTargets;
}
else {
logger.warn(`✼ The target must be one of ${LINUX_TARGET_TYPES.join(', ')}, the default 'deb' will be used.`);
}
}
async function resolveSystemTrayIconPath(systemTrayIcon, defaultTrayIconPath, safeAppName, iconOutputDir = path.join(npmDirectory, 'src-tauri/png')) {
if (systemTrayIcon.length === 0) {
return defaultTrayIconPath;
}
try {
const iconExt = path.extname(systemTrayIcon).toLowerCase();
if (iconExt !== '.png' && iconExt !== '.ico') {
logger.warn(`✼ System tray icon must be .ico or .png, but you provided ${iconExt}.`);
logger.warn(`✼ Default system tray icon will be used.`);
return defaultTrayIconPath;
}
if (!(await fsExtra.pathExists(systemTrayIcon))) {
logger.warn(`✼ System tray icon "${systemTrayIcon}" was not found.`);
logger.warn(`✼ Default system tray icon will be used.`);
return defaultTrayIconPath;
}
const trayIconPath = `png/${safeAppName}${iconExt}`;
const trayIcoPath = path.join(iconOutputDir, `${safeAppName}${iconExt}`);
await fsExtra.copy(systemTrayIcon, trayIcoPath);
return trayIconPath;
}
catch (err) {
logger.warn(`✼ Failed to apply system tray icon "${systemTrayIcon}": ${err instanceof Error ? err.message : String(err)}`);
logger.warn(`✼ Default system tray icon will remain unchanged.`);
return defaultTrayIconPath;
}
}
async function mergeIcons(options, name, tauriConf, platform, safeAppName) {
const platformIconMap = {
win32: {
fileExt: '.ico',
path: `png/${safeAppName}_256.ico`,
defaultIcon: 'png/icon_256.ico',
message: 'Windows icon must be .ico and 256x256px.',
},
linux: {
fileExt: '.png',
path: `png/${generateLinuxPackageName(name)}_512.png`,
defaultIcon: 'png/icon_512.png',
message: 'Linux icon must be .png and 512x512px.',
},
darwin: {
fileExt: '.icns',
path: `icons/${safeAppName}.icns`,
defaultIcon: 'icons/icon.icns',
message: 'macOS icon must be .icns or an Icon Composer .icon package.',
},
};
const iconInfo = platformIconMap[platform];
const resolvedIconPath = options.icon ? path.resolve(options.icon) : null;
const exists = resolvedIconPath && (await fsExtra.pathExists(resolvedIconPath));
if (exists) {
let updateIconPath = true;
let composerIconApplied = false;
const customIconExt = iconPathExtension(resolvedIconPath);
if (platform === 'darwin' && customIconExt === '.icon') {
if (!(await isMacOSIconComposerPackage(resolvedIconPath))) {
updateIconPath = false;
logger.warn(`✼ macOS .icon must be an Icon Composer package (a directory containing icon.json), but you gave ${resolvedIconPath}`);
tauriConf.bundle.icon = [iconInfo.defaultIcon];
}
else {
const destIconsDir = path.join(npmDirectory, 'src-tauri/icons');
const defaultIcnsPath = path.join(npmDirectory, 'src-tauri', iconInfo.defaultIcon);
const { bundleIcon } = await applyDarwinIconComposerPackage({
sourceIconPath: resolvedIconPath,
destIconsDir,
safeAppName,
defaultIcnsPath,
});
tauriConf.bundle.icon = bundleIcon;
// Assets.car is read from bundle.icon; copying it into resources too
// would store it twice. Keep the .icns resource the plain path ships.
tauriConf.bundle.resources = bundleIcon.filter((icon) => icon.endsWith('.icns'));
composerIconApplied = true;
}
}
else if (customIconExt !== iconInfo.fileExt) {
updateIconPath = false;
logger.warn(`✼ ${iconInfo.message}, but you give ${customIconExt}`);
tauriConf.bundle.icon = [iconInfo.defaultIcon];
}
else {
const iconPath = path.join(npmDirectory, 'src-tauri/', iconInfo.path);
tauriConf.bundle.resources = [iconInfo.path];
const absoluteDestPath = path.resolve(iconPath);
if (resolvedIconPath !== absoluteDestPath) {
try {
await fsExtra.copy(resolvedIconPath, iconPath);
}
catch (error) {
if (!(error instanceof Error &&
error.message.includes('Source and destination must not be the same'))) {
throw error;
}
}
}
}
if (!composerIconApplied) {
if (updateIconPath) {
tauriConf.bundle.icon = [iconInfo.path];
}
else {
logger.warn(`✼ Icon will remain as default.`);
}
}
}
else {
logger.warn('✼ Custom icon path may be invalid, default icon will be used instead.');
tauriConf.bundle.icon = [iconInfo.defaultIcon];
}
// Set tray icon path.
const defaultTrayIconPath = platform === 'darwin' ? 'png/icon_512.png' : tauriConf.bundle.icon[0];
const trayIconPath = await resolveSystemTrayIconPath(options.systemTrayIcon, defaultTrayIconPath, safeAppName);
tauriConf.pake.system_tray_path = trayIconPath;
delete tauriConf.app.trayIcon;
}
async function injectCustomCode(options, tauriConf) {
const { inject, proxyUrl, basicAuth, multiInstance, multiWindow, wasm } = options;
const injectFilePath = path.join(npmDirectory, 'src-tauri/src/inject/custom.js');
if (inject?.length > 0) {
const injectArray = validateInjectInput(Array.isArray(inject) ? inject : [inject]);
const files = injectArray.map((filepath) => path.isAbsolute(filepath) ? filepath : path.join(process.cwd(), filepath));
tauriConf.pake.inject = files;
await combineFiles(files, injectFilePath);
}
else {
tauriConf.pake.inject = [];
await fsExtra.writeFile(injectFilePath, '');
}
tauriConf.pake.proxy_url = proxyUrl || '';
tauriConf.pake.download_dir = options.downloadDir || '';
tauriConf.pake.basic_auth = basicAuth;
tauriConf.pake.multi_instance = multiInstance;
tauriConf.pake.multi_window = multiWindow;
if (wasm) {
tauriConf.app.security = {
headers: {
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'require-corp',
},
};
}
}
async function generateMacEntitlements(camera, microphone) {
const entitlementEntries = [];
if (camera) {
entitlementEntries.push(' <key>com.apple.security.device.camera</key>\n <true/>');
}
if (microphone) {
entitlementEntries.push(' <key>com.apple.security.device.audio-input</key>\n <true/>');
}
const entitlementsContent = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
${entitlementEntries.join('\n')}
</dict>
</plist>
`;
const entitlementsPath = path.join(npmDirectory, 'src-tauri', 'entitlements.plist');
await fsExtra.writeFile(entitlementsPath, entitlementsContent);
}
async function writeAllConfigs(tauriConf, platform) {
const platformConfigPaths = {
win32: 'tauri.windows.conf.json',
darwin: 'tauri.macos.conf.json',
linux: 'tauri.linux.conf.json',
};
const configPath = path.join(tauriConfigDirectory, platformConfigPaths[platform]);
const bundleConf = { bundle: tauriConf.bundle };
await fsExtra.outputJSON(configPath, bundleConf, { spaces: 4 });
const pakeConfigPath = path.join(tauriConfigDirectory, 'pake.json');
await fsExtra.outputJSON(pakeConfigPath, tauriConf.pake, { spaces: 4 });
const tauriConf2 = JSON.parse(JSON.stringify(tauriConf));
delete tauriConf2.pake;
const configJsonPath = path.join(tauriConfigDirectory, 'tauri.conf.json');
await fsExtra.outputJSON(configJsonPath, tauriConf2, { spaces: 4 });
}
async function mergeConfig(url, options, tauriConf) {
await copyTemplateConfigs();
const { appVersion, userAgent, showSystemTray, useLocalFile, identifier, name = 'pake-app', installerLanguage, camera, microphone, } = options;
const platform = asSupportedPlatform(process.platform);
if (options.hideTitleBar && platform !== 'darwin') {
logger.warn('✼ --hide-title-bar is only supported on macOS and will be ignored on this platform.');
}
if (options.navigationButtons && platform !== 'darwin') {
logger.warn('✼ --navigation-buttons is only supported on macOS and will be ignored on this platform.');
}
if (options.hideWindowDecorations && platform === 'darwin') {
logger.warn('✼ --hide-window-decorations is only supported on Windows and Linux and will be ignored on this platform.');
}
const tauriConfWindowOptions = buildWindowConfigOverrides(options, platform);
Object.assign(tauriConf.pake.windows[0], { url, ...tauriConfWindowOptions });
tauriConf.productName = name;
tauriConf.identifier = identifier;
tauriConf.version = appVersion;
const linuxBinaryName = `pake-${generateLinuxPackageName(name)}`;
tauriConf.mainBinaryName =
platform === 'linux'
? linuxBinaryName
: `pake-${generateIdentifierSafeName(name)}`;
if (platform === 'win32') {
const windowsBundle = tauriConf.bundle.windows;
if (!windowsBundle) {
throw new Error('Windows bundle configuration is missing from tauri.windows.conf.json; cannot build Windows target.');
}
windowsBundle.wix.language[0] = installerLanguage;
}
await handleLocalFile(url, useLocalFile, tauriConf);
const platformMap = {
win32: 'windows',
linux: 'linux',
darwin: 'macos',
};
const currentPlatform = platformMap[platform];
if (userAgent.length > 0) {
tauriConf.pake.user_agent[currentPlatform] = userAgent;
}
tauriConf.pake.system_tray[currentPlatform] = showSystemTray;
if (platform === 'linux') {
await mergeLinuxConfig(options, name, tauriConf, linuxBinaryName);
}
if (platform === 'darwin') {
const validMacTargets = ['app', 'dmg'];
if (validMacTargets.includes(options.targets)) {
tauriConf.bundle.targets = [options.targets];
}
}
const safeAppName = getSafeAppName(name);
await mergeIcons(options, name, tauriConf, platform, safeAppName);
await injectCustomCode(options, tauriConf);
if (platform === 'darwin') {
await generateMacEntitlements(camera, microphone);
}
await writeAllConfigs(tauriConf, platform);
}
// Load configs from npm package directory, not from project source
const tauriSrcDir = path.join(npmDirectory, 'src-tauri');
const pakeConf = fsExtra.readJSONSync(path.join(tauriSrcDir, 'pake.json'));
const CommonConf = fsExtra.readJSONSync(path.join(tauriSrcDir, 'tauri.conf.json'));
const WinConf = fsExtra.readJSONSync(path.join(tauriSrcDir, 'tauri.windows.conf.json'));
const MacConf = fsExtra.readJSONSync(path.join(tauriSrcDir, 'tauri.macos.conf.json'));
const LinuxConf = fsExtra.readJSONSync(path.join(tauriSrcDir, 'tauri.linux.conf.json'));
const platformConfigs = {
win32: WinConf,
darwin: MacConf,
linux: LinuxConf,
};
const { platform: platform$1 } = process;
// @ts-ignore
const platformConfig = platformConfigs[platform$1];
let tauriConfig = {
...CommonConf,
bundle: platformConfig.bundle,
app: {
...CommonConf.app,
},
build: CommonConf.build,
pake: pakeConf,
};
/**
* Returns build environment variables overrides for macOS, where Rust crates
* sometimes need explicit C/C++ flags and a deterministic SDK target. Other
* platforms inherit `process.env` unchanged.
*/
function getBuildEnvironment() {
if (!IS_MAC) {
return undefined;
}
const currentPath = process.env.PATH || '';
const systemToolsPath = '/usr/bin';
const buildPath = currentPath.startsWith(`${systemToolsPath}:`)
? currentPath
: `${systemToolsPath}:${currentPath}`;
return {
CFLAGS: '-fno-modules',
CXXFLAGS: '-fno-modules',
MACOSX_DEPLOYMENT_TARGET: '14.0',
PATH: buildPath,
};
}
/**
* The release profile unwinds for macOS's sake: there Wry has to catch an
* exception WebKit raises for an answer to a request a closing or leaving page
* still had out, and it cannot under `panic = "abort"`, so the app quit.
* Windows and Linux have no such exception to hold, and unwinding made the
* Windows x64 binary 4.5 MB larger (11.9 to 16.4 MB), so their release builds
* keep abort. A value the user already set wins.
*/
function getPanicStrategyEnvironment(platform = process.platform) {
if (platform === 'darwin' || process.env.CARGO_PROFILE_RELEASE_PANIC) {
return {};
}
return { CARGO_PROFILE_RELEASE_PANIC: 'abort' };
}
/**
* Build scripts and proc-macros compile for the rustup *host* toolchain, not
* the `--target` triple, even when cross-compiling. Pake's own
* rust-toolchain.toml pins a bare channel (no host), which rustup resolves
* against the machine's configured default host, msvc on most Windows
* installs, regardless of whether MSVC is actually present. Without this,
* a gnu `--target` build still shells out to the (possibly missing) MSVC
* `link.exe` for every build script. RUSTUP_TOOLCHAIN is rustup's documented
* per-invocation override (read by the cargo/rustc proxies it installs) and
* only affects this build subprocess. Left alone if the user already set it.
*/
function getWindowsGnuBuildEnvironment() {
const excludeAllSymbols = ['-C', 'link-args=-Wl,--exclude-all-symbols'];
const existingRustflags = process.env.RUSTFLAGS;
const existingEncodedRustflags = process.env.CARGO_ENCODED_RUSTFLAGS;
// Cargo prefers encoded flags over RUSTFLAGS, even when set to an empty value.
const flags = existingEncodedRustflags !== undefined
? {
CARGO_ENCODED_RUSTFLAGS: [
...(existingEncodedRustflags ? [existingEncodedRustflags] : []),
...excludeAllSymbols,
].join('\x1f'),
}
: {
RUSTFLAGS: [
...(existingRustflags ? [existingRustflags] : []),
...excludeAllSymbols,
].join(' '),
};
return {
...flags,
RUSTUP_TOOLCHAIN: process.env.RUSTUP_TOOLCHAIN || 'stable-x86_64-pc-windows-gnu',
};
}
/**
* Windows needs more time due to native compilation and antivirus scanning.
*/
function getInstallTimeout() {
return process.platform === 'win32' ? 900000 : 600000;
}
function getBuildTimeout() {
return 900000;
}
let packageManagerCache = null;
function parseMajorVersion(version) {
const match = version.match(/^v?(\d+)/);
return match ? Number(match[1]) : null;
}
function getPinnedPnpmMajorVersion() {
const packageManager = packageJson.packageManager;
const match = packageManager?.match(/^pnpm@(\d+)/);
return match ? Number(match[1]) : null;
}
async function detectNpm(execa) {
try {
await execa('npm', ['--version'], { stdio: 'ignore' });
return true;
}
catch {
return false;
}
}
/**
* Returns 'pnpm' when available, otherwise 'npm'. Throws if neither is found.
* Cached after the first successful detection so tests can call repeatedly.
*/
async function detectPackageManager() {
if (packageManagerCache) {
return packageManagerCache;
}
const { execa } = await import('execa');
let pnpmVersion;
try {
const { stdout } = await execa('pnpm', ['--version']);
pnpmVersion = stdout.trim();
}
catch {
if (await detectNpm(execa)) {
logger.info('✺ pnpm not available, using npm for package management.');
packageManagerCache = 'npm';
return 'npm';
}
throw new Error('Neither pnpm nor npm is available. Please install a package manager.');
}
const normalizedPnpmVersion = pnpmVersion.startsWith('v')
? pnpmVersion
: `v${pnpmVersion}`;
const pnpmMajor = parseMajorVersion(pnpmVersion);
const pinnedPnpmMajor = getPinnedPnpmMajorVersion();
if (pnpmMajor !== null &&
pinnedPnpmMajor !== null &&
pnpmMajor !== pinnedPnpmMajor) {
if (!(await detectNpm(execa))) {
throw new Error(`Detected pnpm ${normalizedPnpmVersion}, but Pake is pinned to ${packageJson.packageManager}. Install npm so Pake can fall back, or use pnpm ${pinnedPnpmMajor}.x to match the project pin.`);
}
logger.warn(`✼ Detected pnpm ${normalizedPnpmVersion}, but Pake is pinned to ${packageJson.packageManager}; using npm for package management instead.`);
packageManagerCache = 'npm';
return 'npm';
}
logger.info('✺ Using pnpm for package management.');
packageManagerCache = 'pnpm';
return 'pnpm';
}
function getInstallCommand(packageManager, useCnMirror) {
const args = ['install'];
if (useCnMirror)
args.push('--registry=https://registry.npmmirror.com');
if (packageManager === 'npm')
args.push('--legacy-peer-deps');
return { executable: packageManager, args };
}
async function copyFileWithSamePathGuard(sourcePath, destinationPath) {
if (path.resolve(sourcePath) === path.resolve(destinationPath)) {
return;
}
try {
await fsExtra.copy(sourcePath, destinationPath, { overwrite: true });
}
catch (error) {
if (error instanceof Error &&
error.message.includes('Source and destination must not be the same')) {
return;
}
throw error;
}
}
function isGeneratedCnMirrorConfig(projectConfig, cnMirrorConfig) {
return projectConfig.trim() === cnMirrorConfig.trim();
}
/**
* Toggles `.cargo/config.toml` to point at rsproxy.cn when the user opts in
* via `PAKE_USE_CN_MIRROR=1`, and removes the auto-generated mirror config
* (or warns about a manual one) when they opt out.
*/
async function configureCargoRegistry(tauriSrcPath, useCnMirror) {
const rustProjectDir = path.join(tauriSrcPath, '.cargo');
const projectConf = path.join(rustProjectDir, 'config.toml');
const projectCnConf = path.join(tauriSrcPath, 'rust_proxy.toml');
if (useCnMirror) {
await fsExtra.ensureDir(rustProjectDir);
await copyFileWithSamePathGuard(projectCnConf, projectConf);
return;
}
if (!(await fsExtra.pathExists(projectConf))) {
return;
}
const [projectConfig, cnMirrorConfig] = await Promise.all([
fsExtra.readFile(projectConf, 'utf8'),
fsExtra.readFile(projectCnConf, 'utf8'),
]);
if (isGeneratedCnMirrorConfig(projectConfig, cnMirrorConfig)) {
await fsExtra.remove(projectConf);
return;
}
if (projectConfig.includes('rsproxy.cn')) {
logger.warn(`✼ ${projectConf} still references rsproxy.cn. Remove it or set ${CN_MIRROR_ENV}=1 if you want to use the CN mirror.`);
}
}
// Appended to the error when a Linux AppImage build fails for good. linuxdeploy's
// diagnostics stream to the terminal (stdio: 'inherit') and never reach
// error.message, so we cannot name the exact cause. We only reach here after
// NO_STRIP=1 has been applied and still failed, so strip is shown as ruled out.
const APPIMAGE_BAR = '━'.repeat(56);
const APPIMAGE_FAILURE_GUIDANCE = `\n\n${APPIMAGE_BAR}\n` +
'Linux AppImage Build Failed\n' +
`${APPIMAGE_BAR}\n\n` +
'The AppImage bundler (linuxdeploy) failed. Common causes and fixes:\n\n' +
' • Strip incompatibility (glibc 2.38+): NO_STRIP=1 was already applied and\n' +
' the build still failed, so strip is likely not the cause.\n' +
' • Missing gdk-pixbuf loaders (e.g. "cannot stat\n' +
" '/usr/lib/gdk-pixbuf-2.0/...'\"): install them, then rebuild:\n" +
' Arch: sudo pacman -S gdk-pixbuf2 librsvg\n' +
' Debian: sudo apt install librsvg2-common gdk-pixbuf2.0-bin\n' +
' Fedora: sudo dnf install gdk-pixbuf2-modules librsvg2\n' +
' then: sudo gdk-pixbuf-query-loaders --update-cache\n' +
' (Arch refreshes the cache automatically via a pacman hook)\n' +
' • Running in Docker/container: AppImage needs /dev/fuse:\n' +
' --privileged --device /dev/fuse --security-opt apparmor=unconfined\n\n' +
'Still stuck? Build a DEB instead: pake <url> --targets deb\n' +
'Detailed guide: https://github.com/tw93/Pake/blob/main/docs/faq.md\n' +
APPIMAGE_BAR;
class BaseBuilder {
constructor(options) {
this.artifacts = [];
this.options = options;
}
/** Final artifacts produced by this build, for the `--json` result. */
getArtifacts() {
return [...this.artifacts];
}
/** Architecture reported in the `--json` result. */
getReportArch() {
return this.options.multiArch ? 'universal' : process.arch;
}
// Drop a recorded artifact whose file was later removed (e.g. the
// temporary .deb consumed by zst repacking), so --json never lists a
// path that no longer exists.
removeArtifact(artifactPath) {
const resolved = path.resolve(artifactPath);
this.artifacts = this.artifacts.filter((artifact) => artifact.path !== resolved);
}
async recordArtifact(artifactPath, format) {
try {
const stat = await fsExtra.stat(artifactPath);
let sizeBytes = stat.size;
if (stat.isDirectory()) {
sizeBytes = await this.getPathSize(artifactPath);
}
this.artifacts.push({
path: path.resolve(artifactPath),
sizeBytes,
format,
});
}
catch {
// Never fail a finished build over size bookkeeping.
this.artifacts.push({
path: path.resolve(artifactPath),
sizeBytes: 0,
format,
});
}
}
async getPathSize(directory) {
let size = 0;
for (const entry of await fsExtra.readdir(directory, {
withFileTypes: true,
})) {
const entryPath = path.join(directory, entry.name);
if (entry.isDirectory()) {
size += await this.getPathSize(entryPath);
}
else if (entry.isFile()) {
size += (await fsExtra.stat(entryPath)).size;
}
}
return size;
}
async prepare() {
const tauriSrcPath = path.join(npmDirectory, 'src-tauri');
const tauriTargetPath = this.getCargoTargetDir();
const tauriTargetPathExists = await fsExtra.pathExists(tauriTargetPath);
if (!IS_MAC && !tauriTargetPathExists) {
logger.warn('✼ The first use requires installing system dependencies.');
logger.warn('✼ See more in https://tauri.app/start/prerequisites/.');
}
ensureRustEnv();
if (IS_WIN &&
this.options.targets !== 'arm64' &&
this.options.windowsToolchain !== 'gnu' &&
!hasWindowsMsvcBuildTools() &&
hasWindowsGnuToolchain()) {
logger.warn('✼ No Visual Studio Build Tools detected, but a MinGW/GNU toolchain (gcc) is available.');
logger.warn('✼ If the build fails to link, retry with --windows-toolchain gnu.');
}
if (!checkRustInstalled()) {
if (!isInteractive()) {
throw new PakeError('Rust required to package your webapp.', {
code: 'ENV_MISSING',
hint: 'Install Rust via https://rustup.rs, then rerun the same command.',
});
}
const res = await prompts({
type: 'confirm',
message: 'Rust not detected. Install now?',
name: 'value',
});
if (res.value) {
await installRust();
}
else {
throw new PakeError('Rust required to package your webapp.', {
code: 'ENV_MISSING',
hint: 'Install Rust via https://rustup.rs, then rerun the same command.',
});
}
}
const useCnMirror = isCnMirrorEnabled();
await configureCargoRegistry(tauriSrcPath, useCnMirror);
// Workspaces reuse installed dependencies. Reinstalling through their
// node_modules link would mutate the shared CLI installation.
if (await hasReadyTauriCli(npmDirectory)) {
return;
}
// Dependencies may disappear after the workspace linked them. Reinstall
// privately even in that case, without writing through to the source tree.
const modules = path.join(npmDirectory, 'node_modules');
if (npmDirectory !== packageDirectory &&
(await fsExtra.lstat(modules).catch(() => null))?.isSymbolicLink()) {
await fsExtra.unlink(modules);
}
const spinner = getSpinner('Installing package...');
const packageManager = await detectPackageManager();
const timeout = getInstallTimeout();
const buildEnv = getBuildEnvironment();
// Show helpful message for first-time users
if (!tauriTargetPathExists) {
logger.info(process.platform === 'win32'
? '✺ First-time setup may take 10-15 minutes on Windows (compiling dependencies)...'
: '✺ First-time setup may take 5-10 minutes (installing dependencies)...');
}
if (useCnMirror) {
logger.info(`✺ ${CN_MIRROR_ENV}=1 detected, using ${packageManager}/rsProxy CN mirror.`);
}
try {
await shellExec(getInstallCommand(packageManager, useCnMirror), timeout, {
...buildEnv,
CI: 'true',
});
spinner.succeed(chalk.green('Package installed!'));
}
catch (error) {
spinner.fail(chalk.red('Installation failed'));
if (!useCnMirror) {
logger.info(`✺ If downloads are slow in China, retry with ${CN_MIRROR_ENV}=1 to use CN mirrors.`);
}
throw error;
}
if (!tauriTargetPathExists) {
logger.warn('✼ The first packaging may be slow, please be patient and wait, it will be faster afterwards.');
}
}
async build(url) {
await this.buildAndCopy(url, this.options.targets);
}
async start(url) {
logger.info('Pake dev server starting...');
await mergeConfig(url, this.options, structuredClone(tauriConfig));
const packageManager = await detectPackageManager();
const configPath = path.join(npmDirectory, 'src-tauri', '.pake', 'tauri.conf.json');
const features = this.getBuildFeatures();
const args = ['run', 'tauri'];
if (packageManager === 'npm')
args.push('--');
args.push('dev', '--config', configPath);
if (features.length > 0)
args.push('--features', features.join(','));
await shellExec({ executable: packageManager, args });
}
async buildAndCopy(url, target, logSuccess = true) {
await this.prepareBuild(url);
await this.runBuildCommand(this.getBuildCommand(await detectPackageManager()), target);
await this.copyBuildArtifacts(target, logSuccess);
}
async prepareBuild(url) {
await mergeConfig(url, this.options, structuredClone(tauriConfig));
}
async runBuildCommand(buildCommand, target) {
// Build app
const buildSpinner = getSpinner('Building app...');
buildSpinner.stop();
// Show static message to keep the status visible. Info, not warn: warn
// entries feed the --json warnings array and this is a status line.
logger.info('✸ Building app...');
const baseEnv = getBuildEnvironment();
const isWindowsGnuBuild = process.platform === 'win32' && this.options.windowsToolchain === 'gnu';
let buildEnv = {
...(baseEnv ?? {}),
...getPanicStrategyEnvironment(),
...(isWindowsGnuBuild ? getWindowsGnuBuildEnvironment() : {}),
...(process.env.NO_STRIP ? { NO_STRIP: process.env.NO_STRIP } : {}),
};
const resolveExecEnv = () => Object.keys(buildEnv).length > 0 ? buildEnv : undefined;
const isLinuxAppImage = process.platform === 'linux' && target === 'appimage';
// AppImage builds can fail at the linuxdeploy strip step on glibc 2.38+.
// A real failure now prints full guidance, so only hint in debug mode.
if (isLinuxAppImage && !buildEnv.NO_STRIP && this.options.debug) {
logger.warn('⚠ AppImage strip step can fail on glibc 2.38+; Pake will auto-retry with NO_STRIP=1.');
}
const buildTimeout = getBuildTimeout();
try {
await shellExec(buildCommand, buildTimeout, resolveExecEnv());
}
catch (error) {
if (!isLinuxAppImage) {
throw error;
}
// linuxdeploy's diagnostics stream to the terminal (stdio: 'inherit') and
// never reach error.message, so we cannot classify the cause. strip is the
// most common AppImage failure, so retry once with NO_STRIP=1; if that
// (or an already-NO_STRIP run) still fails, surface all known causes.
if (buildEnv.NO_STRIP) {
error.message += APPIMAGE_FAILURE_GUIDANCE;
throw error;
}
logger.warn('⚠ AppImage build failed, retrying once with NO_STRIP=1 (common glibc 2.38+ strip issue).');
buildEnv = { ...buildEnv, NO_STRIP: '1' };
try {
await shellExec(buildCommand, buildTimeout, resolveExecEnv());
}
catch (retryError) {
retryError.message += APPIMAGE_FAILURE_GUIDANCE;
throw retryError;
}
}
}
async copyBuildArtifacts(target, logSuccess = true) {
const { name = 'pake-app' } = this.options;
// With --no-bundle there is no installer to copy; surface the raw
// executable the build produced instead.
if (this.options.bundle === false) {
await this.copyRawBinary(npmDirectory, name);
await this.recordArtifact(this.getRawBinaryPath(name), 'binary');
if (logSuccess) {
logger.success('✔ Build success!');
logger.success('✔ Raw binary located in', path.resolve(this.getRawBinaryPath(name)));
}
return;
}
// Copy app
const fileName = this.getFileName();
const fileType = this.getFileType(target);
const appPath = this.getBuildAppPath(npmDirectory, fileName, fileType);
const distPath = path.resolve(`${name}.${fileType}`);
await fsExtra.copy(appPath, distPath);
await this.recordArtifact(distPath, fileType);
// Copy raw binary if requested
if (this.options.keepBinary) {
await this.copyRawBinary(npmDirectory, name);
await this.recordArtifact(this.getRawBinaryPath(name), 'binary');
}
await fsExtra.remove(appPath);
if (logSuccess) {
logger.success('✔ Build success!');
logger.success('✔ App installer located in', distPath);
}
// Log binary location if preserved
if (this.options.keepBinary) {
const binaryPath = this.getRawBinaryPath(name);
logger.success('✔ Raw binary located in', path.resolve(binaryPath));
}
if (IS_MAC && fileType === 'app' && this.options.install) {
await this.installAppToApplications(distPath, name);
}
}
async installAppToApplications(appBundlePath, appName) {
try {
logger.info(`- Installing ${appName} to /Applications...`);
const appBundleName = path.basename(appBundlePath);
const appDest = path.join('/Applications', appBundleName);
if (await fsExtra.pathExists(appDest)) {
logger.warn(` Existing ${appBundleName} in /Applications will be replaced.`);
}
// fsExtra.move uses fs.rename (atomic on same filesystem) and falls back
// to copy+remove only when moving across volumes.
await fsExtra.move(appBundlePath, appDest, { overwrite: true });
// Keep the JSON result pointing at where the artifact actually lives.
const movedFrom = path.resolve(appBundlePath);
for (const artifact of this.artifacts) {
if (artifact.path === movedFrom) {
artifact.path = appDest;
}
}
logger.success(`✔ ${appBundleName.replace(/\.app$/, '')} installed to /Applications`);
}
catch (error) {
logger.error(`✕ Failed to install ${appName}: ${error}`);
logger.info(` App bundle still available at: ${appBundlePath}`);
}
}
getFileType(target) {
return target;
}
resolveTargetArch(requestedArch) {
if (requestedArch === 'auto' || !requestedArch) {
return process.arch;
}
return requestedArch;
}
getTauriTarget(arch, platform = process.platform) {
const platformMappings = BaseBuilder.ARCH_MAPPINGS[platform];
if (!platformMappings)
return null;
return platformMappings[arch] || null;
}
getArchDisplayName(arch) {
return BaseBuilder.ARCH_DISPLAY_NAMES[arch] || arch;
}
buildBaseCommand(packageManager, configPath, target) {
const args = ['run', this.options.debug ? 'build:debug' : 'build'];
if (packageManager === 'npm')
args.push('--');
args.push('-c', configPath);
if (target) {
args.push('--target', target);
}
// Enable verbose output in debug mode to help diagnose build issues.
// This provides detailed logs from Tauri CLI and bundler tools.
if (this.options.debug) {
args.push('--verbose');
}
const features = this.getBuildFeatures();
if (features.length > 0) {
args.push('--features', features.join(','));
}
return { executable: packageManager, args };
}
getBuildFeatures() {
const features = ['cli-build'];
// Add macos-proxy feature for modern macOS (Darwin 23+ = macOS 14+)
if (IS_MAC) {
const macOSVersion = this.getMacOSMajorVersion();
if (macOSVersion >= 23) {
features.push('macos-proxy');
}
}
return features;
}
getBuildCommand(packageManager = 'pnpm') {
// Use temporary config directory to avoid modifying source files
const configPath = path.join(npmDirectory, 'src-tauri', '.pake', 'tauri.conf.json');
const fullCommand = this.buildBaseCommand(packageManager, configPath);
// For macOS, use app bundles by default unless DMG is explicitly requested
if (IS_MAC && this.options.targets === 'app') {
fullCommand.args.push('--bundles', 'app');
}
return fullCommand;
}
getMacOSMajorVersion() {
try {
const release = os.release();
const majorVersion = parseInt(release.split('.')[0], 10);
return Number.isNaN(majorVersion) ? 0 : majorVersion;
}
catch {
return 0; // Disable proxy feature if version detection fails
}
}
getCargoTargetDir() {
return process.env.CARGO_TARGET_DIR || path.join('src-tauri', 'target');
}
resolveBuildPath(npmDirectory, buildPath) {
return path.isAbsolute(buildPath)
? buildPath
: path.join(npmDirectory, buildPath);
}
getBasePath() {
const basePath = this.options.debug ? 'debug' : 'release';
return path.join(this.getCargoTargetDir(), basePath, 'bundle');
}
getBuildAppPath(npmDirectory, fileName, fileType) {
// For app bundles on macOS, the directory is 'macos', not 'app'
const bundleDir = fileType.toLowerCase() === 'app' ? 'macos' : fileType.toLowerCase();
return path.join(this.resolveBuildPath(npmDirectory, this.getBasePath()), bundleDir, `${fileName}.${fileType}`);
}
/**
* Copy raw binary file to output directory
*/
async copyRawBinary(npmDirectory, appName) {
const binaryPath = this.getRawBinarySourcePath(npmDirectory, appName);
const outputPath = this.getRawBinaryPath(appName);
if (await fsExtra.pathExists(binaryPath)) {
await fsExtra.copy(binaryPath, outputPath);
// Make binary executable on Unix-like systems
if (process.platform !== 'win32') {
await fsExtra.chmod(outputPath, 0o755);
}
}
else {
logger.warn(`✼ Raw binary not found at ${binaryPath}, skipping...`);
}
}
/**
* Get the source path of the raw binary file in the build directory
*/
getRawBinarySourcePath(npmDirectory, appName) {
const basePath = this.options.debug ? 'debug' : 'release';
const binaryName = this.getBinaryName(appName);
// Handle cross-platform builds
if (this.options.multiArch || this.hasArchSpecificTarget()) {
return path.join(this.resolveBuildPath(npmDirectory, this.getArchSpecificPath()), basePath, binaryName);
}
return path.join(this.resolveBuildPath(npmDirectory, this.getCargoTargetDir()), basePath, binaryName);
}
/**
* Get the output path for the raw binary file
*/
getRawBinaryPath(appName) {
const extension = process.platform === 'win32' ? '.exe' : '';
const suffix = process.platform === 'win32' ? '' : '-binary';
return `${appName}${suffix}${extension}`;
}
/**
* Get the binary name based on app name and platform
*/
getBinaryName(appName) {
const extension = process.platform === 'win32' ? '.exe' : '';
// Use unique binary name for all platforms to avoid conflicts
const nameToUse = process.platform === 'linux'
? generateLinuxPackageName(appName)
: generateIdentifierSafeName(appName);
return `pake-${nameToUse}${extension}`;
}
/**
* Check if this build has architecture-specific target
*/
hasArchSpecificTarget() {
return false; // Override in subclasses if needed
}
/**
* Get architecture-specific path for binary
*/
getArchSpecificPath() {
return this.getCargoTargetDir(); // Override in subclasses if needed
}
}
BaseBuilder.ARCH_MAPPINGS = {
darwin: {
arm64: 'aarch64-apple-darwin',
x64: 'x86_64-apple-darwin',
universal: 'universal-apple-darwin',
},
win32: {
arm64: 'aarch64-pc-windows-msvc',
x64: 'x86_64-pc-windows-msvc',
},
linux: {
arm64: 'aarch64-unknown-linux-gnu',
x64: 'x86_64-unknown-linux-gnu',
},
};
BaseBuilder.ARCH_DISPLAY_NAMES = {
arm64: 'aarch64',
x64: 'x64',
universal: 'universal',
};
class MacBuilder extends BaseBuilder {
constructor(options) {
super(options);
const validArchs = ['intel', 'apple', 'universal', 'auto', 'x64', 'arm64'];
this.buildArch = validArchs.includes(options.targets || '')
? options.targets
: 'auto';
// `app` is a valid macOS bundle target (see merge.ts); honour it explicitly.
if (options.targets === 'app' ||
options.iterativeBuild ||
options.install ||
process.env.PAKE_CREATE_APP === '1') {
this.buildFormat = 'app';
}
else {
this.buildFormat = 'dmg';
}
this.options.targets = this.buildFormat;
}
getFileName() {
const { name = 'pake-app' } = this.options;
if (this.buildFormat === 'app') {
return name;
}
let arch;
if (this.buildArch === 'universal' || this.options.multiArch) {
arch = 'universal';
}
else if (this.buildArch === 'apple') {
arch = 'aarch64';
}
else if (this.buildArch === 'intel') {
arch = 'x64';
}
else {
arch = this.getArchDisplayName(this.resolveTargetArch(this.buildArch));
}
return `${name}_${this.options.appVersion}_${arch}`;
}
getReportArch() {
return this.getActualArch();
}
getActualArch() {
if (this.buildArch === 'universal' || this.options.multiArch) {
return 'universal';
}
else if (this.buildArch === 'apple') {
return 'arm64';
}
else if (this.buildArch === 'intel') {
return 'x64';
}
return this.resolveTargetArch(this.buildArch);
}
getBuildCommand(packageManager = 'pnpm') {
const configPath = path.join('src-tauri', '.pake', 'tauri.conf.json');
const actualArch = this.getActualArch();
const buildTarget = this.getTauriTarget(actualArch, 'darwin');
if (!buildTarget) {
throw new Error(`Unsupported architecture: ${actualArch} for macOS`);
}
return this.buildBaseCommand(packageManager, configPath, buildTarget);
}
getBasePath() {
const basePath = this.options.debug ? 'debug' : 'release';
const actualArch = this.getActualArch();
const target = this.getTauriTarget(actualArch, 'darwin');
if (!target) {
throw new Error(`Unsupported architecture: ${actualArch} for macOS`);
}
return path.join(this.getCargoTargetDir(), target, basePath, 'bundle');
}
hasArchSpecificTarget() {
return true;
}
getArchSpecificPath() {
const actualArch = this.getActualArch();
const target = this.getTauriTarget(actualArch, 'darwin');
if (!target) {
throw new Error(`Unsupported architecture: ${actualArch} for macOS`);
}
return path.join(this.getCargoTargetDir(), target);
}
}
const WEBVIEW2_LOADER_DLL = 'WebView2Loader.dll';
class WinBuilder extends BaseBuilder {
constructor(options) {
super(options);
this.buildFormat = 'msi';
this.keptLoaderDllPath = null;
const validArchs = ['x64', 'arm64', 'auto'];
this.buildArch = validArchs.includes(options.targets || '')
? this.resolveTargetArch(options.targets)
: this.resolveTargetArch('auto');
this.toolchain = options.windowsToolchain === 'gnu' ? 'gnu' : 'msvc';
this.options.targets = this.buildFormat;
}
getReportArch() {
return this.buildArch;
}
getTauriTarget(arch, platform = 'win32') {
if (this.toolchain === 'gnu') {
return WinBuilder.GNU_ARCH_MAPPINGS[arch] || null;
}
return super.getTauriTarget(arch, platform);
}
getFileName() {
const { name } = this.options;
const language = this.options.installerLanguage;
// WiX names the MSI after the arch itself (x64/arm64), not the macOS-style aarch64.
const targetArch = this.buildArch;
return `${name}_${this.options.appVersion}_${targetArch}_${language}`;
}
getBuildCommand(packageManager = 'pnpm') {
const configPath = path.join('src-tauri', '.pake', 'tauri.conf.json');
const buildTarget = this.getTauriTarget(this.buildArch, 'win32');
if (!buildTarget) {
throw new Error(`Unsupported architecture: ${this.buildArch} for Windows`);
}
return this.buildBaseCommand(packageManager, configPath, buildTarget);
}
getBasePath() {
const basePath = this.options.debug ? 'debug' : 'release';
const target = this.getTauriTarget(this.buildArch, 'win32');
if (!target) {
throw new Error(`Unsupported architecture: ${this.buildArch} for Windows`);
}
return path.join(this.getCargoTargetDir(), target, basePath, 'bundle');
}
hasArchSpecificTarget() {
return true;
}
getArchSpecificPath() {
const target = this.getTauriTarget(this.buildArch, 'win32');
if (!target) {
throw new Error(`Unsupported architecture: ${this.buildArch} for Windows`);
}
return path.join(this.getCargoTargetDir(), target);
}
getRawBinaryPath(appName) {
return `${appName}.exe`;
}
getBinaryName(appName) {
return `pake-${generateIdentifierSafeName(appName)}.exe`;
}
async copyRawBinary(npmDirectory, appName) {
await super.copyRawBinary(npmDirectory, appName);
if (this.toolchain !== 'gnu')
return;
// GNU builds import WebView2Loader.dll at runtime (MSVC links
// WebView2LoaderStatic); tauri-build places it beside the binary and the
// MSI bundles it, so the kept .exe needs it beside it too.
const src = path.join(path.dirname(this.getRawBinarySourcePath(npmDirectory, appName)), WEBVIEW2_LOADER_DLL);
const dest = path.join(path.dirname(path.resolve(this.getRawBinaryPath(appName))), WEBVIEW2_LOADER_DLL);
if (await fsExtra.pathExists(src)) {
await fsExtra.copy(src, dest);
this.keptLoaderDllPath = dest;
}
else {
logger.warn(`✼ ${WEBVIEW2_LOADER_DLL} not found at ${src}; the raw binary will not start without it.`);
}
}
async copyBuildArtifacts(target, logSuccess = true) {
await super.copyBuildArtifacts(target, logSuccess);
if (!this.keptLoaderDllPath)
return;
await this.recordArtifact(this.keptLoaderDllPath, 'dll');
if (logSuccess) {
logger.success(`✔ ${WEBVIEW2_LOADER_DLL} copied beside it, keep them together`);
}
}
}
// MSYS2/MinGW only ships an x86_64 GCC toolchain, so gnu is x64-only;
// arm64 falls through to getTauriTarget returning null, which the
// existing call sites already turn into "Unsupported architecture".
WinBuilder.GNU_ARCH_MAPPINGS = {
x64: 'x86_64-pc-windows-gnu',
};
class LinuxBuilder extends BaseBuilder {
constructor(options) {
super(options);
this.currentBuildType = '';
this.compiled = false;
const target = options.targets || 'deb';
if (target.includes('-arm64')) {
this.buildFormat = target.replace('-arm64', '');
this.buildArch = 'arm64';
}
else {
this.buildFormat = target;
this.buildArch = this.resolveTargetArch('auto');
}
this.options.targets = this.buildFormat;
}
getReportArch() {
return this.buildArch;
}
getFileName() {
const { name = 'pake-app', targets } = this.options;
const version = this.options.appVersion;
const buildType = this.currentBuildType || targets.split(',').map((t) => t.trim())[0];
let arch;
if (this.buildArch === 'arm64') {
arch =
buildType === 'rpm' || buildType === 'appimage' ? 'aarch64' : 'arm64';
}
else if (this.buildArch === 'x64') {
arch = buildType === 'rpm' ? 'x86_64' : 'amd64';
}
else {
arch = this.buildArch;
}
if (this.currentBuildType === 'rpm') {
return `${name}-${version}-1.${arch}`;
}
return `${name}_${version}_${arch}`;
}
async build(url) {
this.compiled = false;
this.currentBuildType = '';
// --no-bundle: build the executable once with no per-format packaging loop.
if (this.options.bundle === false) {
await this.buildAndCopy(url, 'deb');
return;
}
const targets = filterLinuxTargets(this.options.targets);
if (targets.length === 0) {
throw new Error(`No valid Linux target in "${this.options.targets}". Valid targets: ${LINUX_TARGET_TYPES.join(', ')}.`);
}
const useTemporaryDebForZst = needsTemporaryDebForZst(targets);
if (targets.length > 1) {
await this.prepareBuild(url);
const command = this.getBuildCommand(await detectPackageManager());
command.args.push('--no-bundle');
await this.runBuildCommand(command, 'compile');
this.compiled = true;
}
// With a single explicit target, fail fast. With multiple targets (the
// distro-aware default, or an explicit comma list) keep building the rest
// when one fails, so a usable installer is still produced, e.g. AppImage
// survives a .deb bundler abort on RPM-based distros.
const isolateFailures = targets.length > 1;
const failed = [];
let firstError = null;
for (const target of targets) {
this.currentBuildType = target;
try {
if (target === 'zst') {
if (useTemporaryDebForZst) {
await this.buildAndCopy(url, 'deb', false);
}
await this.createArchPackageFromDeb({
removeSourceDeb: useTemporaryDebForZst,
});
}
else {
await this.buildAndCopy(url, target);
}
}
catch (error) {
const err = error instanceof Error ? error : new Error(String(error));
if (!isolateFailures) {
throw err;
}
if (!firstError) {
firstError = err;
}
failed.push(target);
logger.warn(`✼ Failed to build "${target}" target: ${err.message.split('\n')[0]}`);
}
}
// Every requested target failed: surface the first real error.
if (firstError && failed.length === targets.length) {
throw firstError;
}
if (failed.length > 0) {
logger.warn(`✼ Skipped failed Linux targets: ${failed.join(', ')}. Other formats built successfully.`);
}
}
async ensureArchPackagingTools() {
const requiredTools = [
{ tool: 'ar', pacmanPackage: 'binutils' },
{ tool: 'bsdtar', pacmanPackage: 'libarchive' },
];
for (const { tool, pacmanPackage } of requiredTools) {
try {
await execa(tool, ['--version'], { stdio: 'ignore' });
}
catch {
throw new Error(`Building a zst package requires "${tool}". Install it first, e.g. "sudo pacman -S ${pacmanPackage}".`);
}
}
}
async createArchPackageFromDeb({ removeSourceDeb, }) {
const { name = 'pake-app' } = this.options;
const packageName = generateLinuxPackageName(name);
const version = this.options.appVersion;
const arch = this.buildArch === 'arm64' ? 'aarch64' : 'x86_64';
const debPath = path.resolve(`${name}.deb`);
const packagePath = path.resolve(`${name}-${version}-1-${arch}.pkg.tar.zst`);
await this.ensureArchPackagingTools();
const workDir = await fsExtra.mkdtemp(path.join(os.tmpdir(), 'pake-arch-'));
const dataDir = path.join(workDir, 'data');
const controlDir = path.join(workDir, 'control');
try {
await fsExtra.ensureDir(dataDir);
await fsExtra.ensureDir(controlDir);
await shellExec({
executable: 'ar',
args: ['x', debPath],
cwd: controlDir,
});
const dataArchive = (await fsExtra.readdir(controlDir)).find((file) => file.startsWith('data.tar'));
if (!dataArchive) {
throw new Error(`Could not find data.tar payload in ${debPath}`);
}
await shellExec({
executable: 'tar',
args: ['-xf', path.join(controlDir, dataArchive), '-C', dataDir],
});
const installedSize = await this.getPathSize(dataDir);
const pkgInfo = `pkgname = ${packageName}
pkgbase = ${packageName}
pkgver = ${version}-1
pkgdesc = ${name} Pake app
url = https://github.com/tw93/Pake
builddate = ${Math.floor(Date.now() / 1000)}
packager = Pake
size = ${installedSize}
arch = ${arch}
license = custom
depend = cairo
depend = desktop-file-utils
depend = gdk-pixbuf2
depend = glib2
depend = gtk3
depend = hicolor-icon-theme
depend = libsoup3
depend = pango
depend = webkit2gtk-4.1
`;
await fsExtra.writeFile(path.join(dataDir, '.PKGINFO'), pkgInfo);
await fsExtra.writeFile(path.join(dataDir, '.INSTALL'), `post_install() {
gtk-update-icon-cache -q -t -f usr/share/icons/hicolor
update-desktop-database -q usr/share/applications
}
post_upgrade() {
post_install
}
post_remove() {
gtk-update-icon-cache -q -t -f usr/share/icons/hicolor
update-desktop-database -q usr/share/applications
}
`);
await shellExec({
executable: 'bsdtar',
args: [
'--zstd',
'-cf',
packagePath,
'-C',
dataDir,
'.PKGINFO',
'.INSTALL',
'usr',
],
});
await this.recordArtifact(packagePath, 'zst');
logger.success('✔ Build success!');
logger.success('✔ App installer located in', packagePath);
}
finally {
if (removeSourceDeb) {
await fsExtra.remove(debPath);
this.removeArtifact(debPath);
}
await fsExtra.remove(workDir);
}
}
// Override buildAndCopy to ensure currentBuildType is synced if called directly, though the loop above handles it most of the time.
async buildAndCopy(url, target, logSuccess = true) {
this.currentBuildType = target;
if (!this.compiled) {
await super.buildAndCopy(url, target, logSuccess);
return;
}
const packageManager = await detectPackageManager();
const args = ['run', 'tauri'];
if (packageManager === 'npm')
args.push('--');
args.push('bundle', '--config', path.join('src-tauri', '.pake', 'tauri.conf.json'));
args.push('--bundles', target, '--features', this.getBuildFeatures().join(','));
if (this.options.debug)
args.push('--debug');
if (this.options.debug || target === 'appimage' || process.env.PAKE_VERBOSE)
args.push('--verbose');
if (this.buildArch === 'arm64')
args.push('--target', this.getTauriTarget('arm64', 'linux'));
await this.runBuildCommand({ executable: packageManager, args }, target);
await this.copyBuildArtifacts(target, logSuccess);
}
getBuildCommand(packageManager = 'pnpm') {
const configPath = path.join('src-tauri', '.pake', 'tauri.conf.json');
const buildTarget = this.buildArch === 'arm64'
? (this.getTauriTarget(this.buildArch, 'linux') ?? undefined)
: undefined;
const fullCommand = this.buildBaseCommand(packageManager, configPath, buildTarget);
// --no-bundle: build the executable only, skipping .deb/.rpm/.appimage
// packaging entirely (e.g. RPM-based distros where the bundler aborts).
if (this.options.bundle === false) {
fullCommand.args.push('--no-bundle');
return fullCommand;
}
if (this.currentBuildType) {
fullCommand.args.push('--bundles', this.currentBuildType);
}
// Enable verbose output for AppImage builds when debugging or PAKE_VERBOSE is set.
// AppImage builds often fail with minimal error messages from linuxdeploy,
// so verbose mode helps diagnose issues like strip failures and missing dependencies.
if (this.currentBuildType === 'appimage' &&
(this.options.targets.includes('appimage') ||
this.options.debug ||
process.env.PAKE_VERBOSE)) {
fullCommand.args.push('--verbose');
}
return fullCommand;
}
getBasePath() {
const basePath = this.options.debug ? 'debug' : 'release';
if (this.buildArch === 'arm64') {
const target = this.getTauriTarget(this.buildArch, 'linux');
if (!target) {
throw new Error(`Unsupported architecture: ${this.buildArch} for Linux`);
}
return path.join(this.getCargoTargetDir(), target, basePath, 'bundle');
}
return super.getBasePath();
}
getFileType(target) {
if (target === 'appimage') {
return 'AppImage';
}
return super.getFileType(target);
}
hasArchSpecificTarget() {
return this.buildArch === 'arm64';
}
getArchSpecificPath() {
if (this.buildArch === 'arm64') {
const target = this.getTauriTarget(this.buildArch, 'linux');
if (!target) {
throw new Error(`Unsupported architecture: ${this.buildArch} for Linux`);
}
return path.join(this.getCargoTargetDir(), target);
}
return super.getArchSpecificPath();
}
}
const { platform } = process;
const buildersMap = {
darwin: MacBuilder,
win32: WinBuilder,
linux: LinuxBuilder,
};
class BuilderProvider {
static create(options) {
const Builder = buildersMap[platform];
if (!Builder) {
throw new Error('The current system is not supported!');
}
return new Builder(options);
}
}
const LOCAL_HOST_SUFFIXES = [
'.local',
'.lan',
'.internal',
'.home',
'.localdomain',
];
const IPV4_ADDRESS_PATTERN = /^(\d{1,3}\.){3}\d{1,3}$/;
function normalize(value) {
return value.trim().toLowerCase();
}
function simplify(value) {
return normalize(value).replace(/[\s._-]+/g, '');
}
function generateDashboardIconSlugs(appName) {
const normalizedName = normalize(appName);
if (!normalizedName) {
return [];
}
const slugs = new Set([
normalizedName,
normalizedName.replace(/\s+/g, '-'),
]);
return [...slugs].filter(Boolean);
}
function isLikelyLocalHostname(hostname) {
const normalizedHostname = normalize(hostname);
if (!normalizedHostname) {
return false;
}
return (normalizedHostname === 'localhost' ||
IPV4_ADDRESS_PATTERN.test(normalizedHostname) ||
normalizedHostname.includes(':') ||
!normalizedHostname.includes('.') ||
LOCAL_HOST_SUFFIXES.some((suffix) => normalizedHostname.endsWith(suffix)));
}
function shouldPreferDashboardIcons(url, appName) {
if (!appName) {
return false;
}
try {
const hostname = new URL(url).hostname.toLowerCase();
if (!hostname) {
return false;
}
if (isLikelyLocalHostname(hostname)) {
return true;
}
const parsed = psl.parse(hostname);
if (!('domain' in parsed) || !parsed.domain) {
return true;
}
const registrableDomain = parsed.domain.toLowerCase();
if (hostname === registrableDomain) {
return false;
}
const subdomain = 'subdomain' in parsed && typeof parsed.subdomain === 'string'
? parsed.subdomain
: '';
if (!subdomain) {
return false;
}
const productLabel = subdomain.split('.').pop() || '';
const rootLabel = registrableDomain.split('.')[0] || '';
const normalizedAppName = simplify(appName);
return (normalizedAppName.length > 0 &&
simplify(productLabel) === normalizedAppName &&
simplify(rootLabel) !== normalizedAppName);
}
catch {
return false;
}
}
function getIconSourcePriority(url, appName) {
return shouldPreferDashboardIcons(url, appName)
? ['dashboard', 'domain']
: ['domain', 'dashboard'];
}
async function loadSharp$1() {
return (await import('sharp')).default;
}
const ICO_HEADER_SIZE = 6;
const ICO_DIR_ENTRY_SIZE = 16;
const ICO_TYPE_ICON = 1;
// Standard Windows icon sizes covering tray (16/24/32), taskbar (32/48),
// shell (48/256) and high-DPI (128/256). Issue #1190.
const WIN_STANDARD_ICO_SIZES = [16, 24, 32, 48, 64, 128, 256];
function decodeDimension(value) {
return value === 0 ? 256 : value;
}
function compareByPreferredSize(preferredSize) {
return (a, b) => {
const aSize = Math.max(a.width, a.height);
const bSize = Math.max(b.width, b.height);
const aExact = aSize === preferredSize ? 0 : 1;
const bExact = bSize === preferredSize ? 0 : 1;
if (aExact !== bExact)
return aExact - bExact;
const aDistance = Math.abs(aSize - preferredSize);
const bDistance = Math.abs(bSize - preferredSize);
if (aDistance !== bDistance)
return aDistance - bDistance;
const aSmaller = aSize < preferredSize ? 1 : 0;
const bSmaller = bSize < preferredSize ? 1 : 0;
if (aSmaller !== bSmaller)
return aSmaller - bSmaller;
if (a.bitCount !== b.bitCount)
return b.bitCount - a.bitCount;
if (aSize !== bSize)
return bSize - aSize;
return a.index - b.index;
};
}
function parseIcoBuffer(buffer) {
if (buffer.length < ICO_HEADER_SIZE) {
throw new Error('Invalid ICO: header too short.');
}
const reserved = buffer.readUInt16LE(0);
const type = buffer.readUInt16LE(2);
const count = buffer.readUInt16LE(4);
if (reserved !== 0 || type !== ICO_TYPE_ICON || count < 1) {
throw new Error('Invalid ICO: invalid header.');
}
const tableSize = ICO_HEADER_SIZE + count * ICO_DIR_ENTRY_SIZE;
if (buffer.length < tableSize) {
throw new Error('Invalid ICO: directory table too short.');
}
const entries = [];
for (let i = 0; i < count; i++) {
const offset = ICO_HEADER_SIZE + i * ICO_DIR_ENTRY_SIZE;
const widthByte = buffer.readUInt8(offset);
const heightByte = buffer.readUInt8(offset + 1);
const bitCount = buffer.readUInt16LE(offset + 6);
const bytesInRes = buffer.readUInt32LE(offset + 8);
const imageOffset = buffer.readUInt32LE(offset + 12);
if (bytesInRes < 1 || imageOffset + bytesInRes > buffer.length) {
throw new Error('Invalid ICO: frame out of bounds.');
}
entries.push({
index: i,
width: decodeDimension(widthByte),
height: decodeDimension(heightByte),
bitCount,
bytesInRes,
imageOffset,
directory: buffer.subarray(offset, offset + ICO_DIR_ENTRY_SIZE),
data: buffer.subarray(imageOffset, imageOffset + bytesInRes),
});
}
return entries;
}
function buildReorderedIcoBuffer(buffer, preferredSize) {
const entries = parseIcoBuffer(buffer);
const ordered = [...entries].sort(compareByPreferredSize(preferredSize));
const count = ordered.length;
const tableSize = ICO_HEADER_SIZE + count * ICO_DIR_ENTRY_SIZE;
const payloadSize = ordered.reduce((acc, entry) => acc + entry.data.length, 0);
const output = Buffer.alloc(tableSize + payloadSize);
output.writeUInt16LE(0, 0);
output.writeUInt16LE(ICO_TYPE_ICON, 2);
output.writeUInt16LE(count, 4);
let currentOffset = tableSize;
for (let i = 0; i < count; i++) {
const entry = ordered[i];
const entryOffset = ICO_HEADER_SIZE + i * ICO_DIR_ENTRY_SIZE;
entry.directory.copy(output, entryOffset, 0, 8);
output.writeUInt32LE(entry.data.length, entryOffset + 8);
output.writeUInt32LE(currentOffset, entryOffset + 12);
entry.data.copy(output, currentOffset);
currentOffset += entry.data.length;
}
return output;
}
async function writeIcoWithPreferredSize(sourcePath, outputPath, preferredSize) {
try {
const sourceBuffer = await fsExtra.readFile(sourcePath);
const reordered = buildReorderedIcoBuffer(sourceBuffer, preferredSize);
await fsExtra.ensureDir(path.dirname(outputPath));
await fsExtra.outputFile(outputPath, reordered);
return true;
}
catch {
return false;
}
}
/**
* PNG signature `\x89PNG`. ICO frames may carry either a BMP DIB or an
* embedded PNG payload (PNG-in-ICO, supported since Windows Vista).
*/
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
function frameLooksLikePng(entry) {
return (entry.data.length >= PNG_SIGNATURE.length &&
entry.data.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE));
}
async function decodeFrameToPng(entry) {
if (frameLooksLikePng(entry)) {
return Buffer.from(entry.data);
}
// BMP DIB frames need to go through sharp's ico-to-PNG path, which only
// works on the full ICO container. Fall back to letting the caller use a
// sharp pipeline against the original ICO for the missing source.
return null;
}
async function pickLargestFrameAsPng(buffer, entries) {
const largest = [...entries].sort((a, b) => Math.max(b.width, b.height) - Math.max(a.width, a.height))[0];
if (largest) {
const decoded = await decodeFrameToPng(largest);
if (decoded) {
return decoded;
}
}
// Fallback: let sharp render directly from the ICO buffer. sharp picks the
// largest embedded frame on its own.
try {
const sharp = await loadSharp$1();
return await sharp(buffer).png().toBuffer();
}
catch {
return null;
}
}
/**
* Ensures the produced ICO carries every Windows standard size so the OS
* never has to downsample a 256x256 frame to 16x16 for the tray.
* Falls back to `writeIcoWithPreferredSize` if rendering fails.
*
* Issue #1190.
*/
async function ensureMultiResolutionIco(sourcePath, outputPath, preferredSize = 256, desiredSizes = WIN_STANDARD_ICO_SIZES) {
try {
const sourceBuffer = await fsExtra.readFile(sourcePath);
const entries = parseIcoBuffer(sourceBuffer);
const sourcePng = await pickLargestFrameAsPng(sourceBuffer, entries);
if (!sourcePng) {
return await writeIcoWithPreferredSize(sourcePath, outputPath, preferredSize);
}
const sharp = await loadSharp$1();
const frames = await Promise.all(desiredSizes.map(async (size) => {
// Reuse an existing exact-size PNG frame when possible to keep any
// hand-tuned small icon (e.g. a 16x16 with deliberate pixel hinting).
const exact = entries.find((entry) => entry.width === size && entry.height === size);
if (exact && frameLooksLikePng(exact)) {
return { size, png: Buffer.from(exact.data) };
}
const png = await sharp(sourcePng)
.resize(size, size, {
fit: 'contain',
background: { r: 0, g: 0, b: 0, alpha: 0 },
})
.ensureAlpha()
.png()
.toBuffer();
return { size, png };
}));
// Order frames so the preferred size lands first (Windows shell uses the
// first-listed frame as a quality hint when choosing which to display).
frames.sort((a, b) => {
const aExact = a.size === preferredSize ? 0 : 1;
const bExact = b.size === preferredSize ? 0 : 1;
if (aExact !== bExact)
return aExact - bExact;
return b.size - a.size;
});
const icoBuffer = buildIcoFromPngBuffers(frames);
await fsExtra.ensureDir(path.dirname(outputPath));
await fsExtra.outputFile(outputPath, icoBuffer);
return true;
}
catch {
return await writeIcoWithPreferredSize(sourcePath, outputPath, preferredSize);
}
}
/**
* Builds an ICO file from an array of PNG buffers using the PNG-in-ICO format
* (supported since Windows Vista). This preserves alpha transparency.
*/
function buildIcoFromPngBuffers(frames) {
const count = frames.length;
const headerSize = ICO_HEADER_SIZE + count * ICO_DIR_ENTRY_SIZE;
const totalPayload = frames.reduce((acc, f) => acc + f.png.length, 0);
const output = Buffer.alloc(headerSize + totalPayload);
output.writeUInt16LE(0, 0);
output.writeUInt16LE(ICO_TYPE_ICON, 2);
output.writeUInt16LE(count, 4);
let currentOffset = headerSize;
for (let i = 0; i < count; i++) {
const { size, png } = frames[i];
const entryOffset = ICO_HEADER_SIZE + i * ICO_DIR_ENTRY_SIZE;
const sizeByte = size >= 256 ? 0 : size;
output.writeUInt8(sizeByte, entryOffset);
output.writeUInt8(sizeByte, entryOffset + 1);
output.writeUInt8(0, entryOffset + 2);
output.writeUInt8(0, entryOffset + 3);
output.writeUInt16LE(1, entryOffset + 4);
output.writeUInt16LE(32, entryOffset + 6);
output.writeUInt32LE(png.length, entryOffset + 8);
output.writeUInt32LE(currentOffset, entryOffset + 12);
png.copy(output, currentOffset);
currentOffset += png.length;
}
return output;
}
async function loadSharp() {
return (await import('sharp')).default;
}
const ICON_CONFIG = {
minFileSize: 100,
supportedFormats: [
'png',
'ico',
'jpeg',
'jpg',
'webp',
'icns',
'icon',
'svg',
],
transparentBackground: { r: 255, g: 255, b: 255, alpha: 0 },
downloadTimeout: {
ci: 5000,
default: 15000,
},
};
const PLATFORM_CONFIG = {
win: { format: '.ico', sizes: [...WIN_STANDARD_ICO_SIZES] },
linux: { format: '.png', size: 512 },
macos: { format: '.icns' },
};
const MACOS_ICONSET_FILES = [
['icon_16x16.png', 16],
['[email protected]', 32],
['icon_32x32.png', 32],
['[email protected]', 64],
['icon_128x128.png', 128],
['[email protected]', 256],
['icon_256x256.png', 256],
['[email protected]', 512],
['icon_512x512.png', 512],
['[email protected]', 1024],
];
const API_KEYS = {
logoDev: ['pk_JLLMUKGZRpaG5YclhXaTkg', 'pk_Ph745P8mQSeYFfW2Wk039A'],
brandfetch: ['1idqvJC0CeFSeyp3Yf7', '1idej-yhU_ThggIHFyG'],
};
/**
* Generates platform-specific icon paths and handles copying for Windows
*/
function generateIconPath(appName, isDefault = false) {
const safeName = isDefault ? 'icon' : getIconBaseName(appName);
const baseName = safeName;
if (IS_WIN) {
return path.join(npmDirectory, 'src-tauri', 'png', `${baseName}_256.ico`);
}
if (IS_LINUX) {
return path.join(npmDirectory, 'src-tauri', 'png', `${baseName}_512.png`);
}
return path.join(npmDirectory, 'src-tauri', 'icons', `${baseName}.icns`);
}
function getIconBaseName(appName) {
const baseName = IS_LINUX
? generateLinuxPackageName(appName)
: getSafeAppName(appName);
return baseName || 'pake-app';
}
async function copyWindowsIconIfNeeded(convertedPath, appName) {
if (!IS_WIN || !convertedPath.endsWith('.ico')) {
return convertedPath;
}
try {
const finalIconPath = generateIconPath(appName);
await fsExtra.ensureDir(path.dirname(finalIconPath));
// Re-render ICO so every Windows standard size is present and prefer the
// 256px frame as the leading entry; falls back to plain reordering if the
// ICO is non-decodable, then to a raw copy. (Issue #1190)
const upgraded = await ensureMultiResolutionIco(convertedPath, finalIconPath, 256);
if (!upgraded) {
const reordered = await writeIcoWithPreferredSize(convertedPath, finalIconPath, 256);
if (!reordered) {
await fsExtra.copy(convertedPath, finalIconPath);
}
}
return finalIconPath;
}
catch (error) {
logger.warn(`Failed to copy Windows icon: ${error instanceof Error ? error.message : 'Unknown error'}`);
return convertedPath;
}
}
/**
* Normalizes icon inputs to PNG while preserving alpha.
*/
async function preprocessIcon(inputPath) {
try {
const extension = path.extname(inputPath).toLowerCase();
const shouldNormalize = ['.png', '.jpeg', '.jpg', '.webp', '.svg'].includes(extension);
if (!shouldNormalize) {
return inputPath;
}
const sharp = await loadSharp();
const { path: tempDir } = await dir();
const outputPath = path.join(tempDir, 'icon-normalized.png');
await sharp(inputPath).ensureAlpha().png().toFile(outputPath);
return outputPath;
}
catch (error) {
if (error instanceof Error) {
logger.warn(`Failed to normalize icon: ${error.message}`);
}
return inputPath;
}
}
/**
* Applies macOS squircle mask to icon
*/
async function applyMacOSMask(inputPath) {
try {
const sharp = await loadSharp();
const { path: tempDir } = await dir();
const outputPath = path.join(tempDir, 'icon-macos-rounded.png');
// 1. Create a 1024x1024 rounded rect mask
// rx="224" is closer to the smooth Apple squircle look for 1024px
const mask = Buffer.from('<svg width="1024" height="1024"><rect x="0" y="0" width="1024" height="1024" rx="224" ry="224" fill="white"/></svg>');
// 2. Load input, resize to 1024, apply mask
const maskedBuffer = await sharp(inputPath)
.resize(1024, 1024, {
fit: 'contain',
background: { r: 0, g: 0, b: 0, alpha: 0 },
})
.composite([
{
input: mask,
blend: 'dest-in',
},
])
.png()
.toBuffer();
// 3. Resize to 840x840 (~18% padding) to solve "too big" visual issue
// Native MacOS icons often leave some breathing room
await sharp(maskedBuffer)
.resize(840, 840, {
fit: 'contain',
background: { r: 0, g: 0, b: 0, alpha: 0 },
})
.extend({
top: 92,
bottom: 92,
left: 92,
right: 92,
background: { r: 0, g: 0, b: 0, alpha: 0 },
})
.toFile(outputPath);
return outputPath;
}
catch (error) {
if (error instanceof Error) {
logger.warn(`Failed to apply macOS mask: ${error.message}`);
}
return inputPath;
}
}
async function generateMacOSIcns(inputPath, outputDir, iconName) {
const sharp = await loadSharp();
const iconsetPath = path.join(outputDir, `${iconName}.iconset`);
const outputPath = path.join(outputDir, `${iconName}${PLATFORM_CONFIG.macos.format}`);
await fsExtra.ensureDir(iconsetPath);
const source = sharp(inputPath);
await Promise.all(MACOS_ICONSET_FILES.map(async ([fileName, size]) => {
await source
.clone()
.resize(size, size, {
fit: 'contain',
background: ICON_CONFIG.transparentBackground,
})
.ensureAlpha()
.png()
.toFile(path.join(iconsetPath, fileName));
}));
await execa('/usr/bin/iconutil', [
'-c',
'icns',
iconsetPath,
'-o',
outputPath,
]);
return outputPath;
}
/**
* Converts icon to platform-specific format
*/
async function convertIconFormat(inputPath, appName) {
try {
if (!(await fsExtra.pathExists(inputPath)))
return null;
const { path: outputDir } = await dir();
const platformOutputDir = path.join(outputDir, 'converted-icons');
await fsExtra.ensureDir(platformOutputDir);
const processedInputPath = await preprocessIcon(inputPath);
const iconName = getIconBaseName(appName);
// Generate platform-specific format
if (IS_WIN) {
const sharp = await loadSharp();
const icoPath = path.join(platformOutputDir, `${iconName}_256${PLATFORM_CONFIG.win.format}`);
const sourceBuffer = await fsExtra.readFile(processedInputPath);
const frames = await Promise.all(PLATFORM_CONFIG.win.sizes.map(async (size) => {
const png = await sharp(sourceBuffer)
.resize(size, size, {
fit: 'contain',
background: { r: 0, g: 0, b: 0, alpha: 0 },
})
.ensureAlpha()
.png()
.toBuffer();
return { size, png };
}));
const icoBuffer = buildIcoFromPngBuffers(frames);
await fsExtra.outputFile(icoPath, icoBuffer);
return icoPath;
}
if (IS_LINUX) {
const sharp = await loadSharp();
const outputPath = path.join(platformOutputDir, `${iconName}_${PLATFORM_CONFIG.linux.size}${PLATFORM_CONFIG.linux.format}`);
// Ensure we convert to proper PNG format with correct size
await sharp(processedInputPath)
.resize(PLATFORM_CONFIG.linux.size, PLATFORM_CONFIG.linux.size, {
fit: 'contain',
background: ICON_CONFIG.transparentBackground,
})
.ensureAlpha()
.png()
.toFile(outputPath);
return outputPath;
}
// macOS
const macIconPath = await applyMacOSMask(processedInputPath);
const outputPath = await generateMacOSIcns(macIconPath, platformOutputDir, iconName);
return (await fsExtra.pathExists(outputPath)) ? outputPath : null;
}
catch (error) {
if (error instanceof Error) {
logger.warn(`Icon format conversion failed: ${error.message}`);
}
return null;
}
}
async function isLinuxBundleIconReady(iconPath) {
if (!IS_LINUX || path.extname(iconPath).toLowerCase() !== '.png') {
return false;
}
try {
const sharp = await loadSharp();
const { width, height } = await sharp(iconPath).metadata();
return (width === PLATFORM_CONFIG.linux.size &&
height === PLATFORM_CONFIG.linux.size);
}
catch {
return false;
}
}
/**
* Processes downloaded or local icon for platform-specific format
*/
async function processIcon(iconPath, appName) {
if (!iconPath || !appName)
return iconPath;
const ext = iconPathExtension(iconPath);
if (ext === '.icon') {
if (!IS_WIN && !IS_LINUX) {
if (await isMacOSIconComposerPackage(iconPath)) {
return iconPath;
}
logger.warn('✼ --icon .icon must be an Icon Composer package (a directory containing icon.json).');
return null;
}
logger.warn('✼ Icon Composer .icon packages are only used on macOS. This platform will use a converted or default icon.');
return null;
}
// Check if already in correct platform format
const isCorrectFormat = (IS_WIN && ext === '.ico') ||
(IS_LINUX && (await isLinuxBundleIconReady(iconPath))) ||
(!IS_WIN && !IS_LINUX && ext === '.icns');
if (isCorrectFormat) {
return await copyWindowsIconIfNeeded(iconPath, appName);
}
// Convert to platform format
const convertedPath = await convertIconFormat(iconPath, appName);
if (convertedPath) {
return await copyWindowsIconIfNeeded(convertedPath, appName);
}
return iconPath;
}
/**
* Gets default icon with platform-specific fallback logic
*/
async function getDefaultIcon() {
logger.info('✼ No icon provided, using default icon.');
if (IS_WIN) {
const defaultIcoPath = generateIconPath('icon', true);
const defaultPngPath = path.join(npmDirectory, 'src-tauri/png/icon_512.png');
// Try default ico first
if (await fsExtra.pathExists(defaultIcoPath)) {
return defaultIcoPath;
}
// Convert from png if ico doesn't exist
if (await fsExtra.pathExists(defaultPngPath)) {
logger.info('✼ Default ico not found, converting from png...');
try {
const convertedPath = await convertIconFormat(defaultPngPath, 'icon');
if (convertedPath && (await fsExtra.pathExists(convertedPath))) {
return await copyWindowsIconIfNeeded(convertedPath, 'icon');
}
}
catch (error) {
logger.warn(`Failed to convert default png to ico: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
// Fallback to png or empty
if (await fsExtra.pathExists(defaultPngPath)) {
logger.warn('✼ Using png as fallback for Windows (may cause issues).');
return defaultPngPath;
}
logger.warn('✼ No default icon found, will use pake default.');
return '';
}
// Linux and macOS defaults
const iconPath = IS_LINUX
? 'src-tauri/png/icon_512.png'
: 'src-tauri/icons/icon.icns';
return path.join(npmDirectory, iconPath);
}
/**
* Main icon handling function with simplified logic flow
*/
async function handleIcon(options, url) {
// Handle custom icon (local file or remote URL)
if (options.icon) {
if (options.icon.startsWith('http')) {
if (isIconComposerUrl(options.icon)) {
logger.warn('✼ Icon Composer .icon packages cannot be downloaded from a URL; pass a local path. HTTP --icon is for ordinary images and .icns files.');
return '';
}
const downloadedPath = await downloadIcon(options.icon);
if (downloadedPath) {
const result = await processIcon(downloadedPath, options.name || '');
if (result)
return result;
}
return '';
}
// Local file path
const resolvedPath = path.resolve(options.icon);
const result = await processIcon(resolvedPath, options.name || '');
if (iconPathExtension(resolvedPath) === '.icon' && !result) {
return '';
}
return result || resolvedPath;
}
// Check for existing local icon before downloading
if (options.name) {
const localIconPath = generateIconPath(options.name);
if (await fsExtra.pathExists(localIconPath)) {
logger.info(`✼ Using existing local icon: ${localIconPath}`);
return localIconPath;
}
}
// Try favicon from website; local file/directory input has no favicon.
if (url && options.name && /^https?:\/\//i.test(url)) {
const faviconPath = await tryGetFavicon(url, options.name);
if (faviconPath)
return faviconPath;
}
// Use default icon
return await getDefaultIcon();
}
/**
* Generates icon service URLs for a domain
*/
function generateIconServiceUrls(domain) {
const logoDevUrls = [...API_KEYS.logoDev]
.sort(() => Math.random() - 0.5)
.map((token) => `https://img.logo.dev/${domain}?token=${token}&format=png&size=256`);
const brandfetchUrls = [...API_KEYS.brandfetch]
.sort(() => Math.random() - 0.5)
.map((key) => `https://cdn.brandfetch.io/${domain}/w/400/h/400?c=${key}`);
return [
...logoDevUrls,
...brandfetchUrls,
`https://www.google.com/s2/favicons?domain=${domain}&sz=256`,
`https://favicon.is/${domain}`,
`https://${domain}/favicon.ico`,
`https://www.${domain}/favicon.ico`,
];
}
/**
* Generates dashboard-icons URLs for an app name.
* Uses walkxcode/dashboard-icons as a final fallback for selfhosted apps.
* Keeps matching conservative to avoid overriding valid site-specific icons.
*/
function generateDashboardIconUrls(appName) {
const baseUrl = 'https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png';
return generateDashboardIconSlugs(appName).map((slug) => `${baseUrl}/${slug}.png`);
}
function isSupportedIconFormat(extension) {
return ICON_CONFIG.supportedFormats.includes(extension);
}
function looksLikeSvg(arrayBuffer) {
const sample = Buffer.from(arrayBuffer)
.toString('utf-8', 0, Math.min(arrayBuffer.byteLength, 512))
.trimStart()
.toLowerCase();
return (sample.startsWith('<svg') ||
(sample.startsWith('<?xml') && sample.includes('<svg')));
}
function getUrlExtension(iconUrl) {
try {
return path.extname(new URL(iconUrl).pathname).slice(1).toLowerCase();
}
catch {
return path.extname(iconUrl).slice(1).toLowerCase();
}
}
async function detectDownloadedIconExtension(response, arrayBuffer, iconUrl) {
const fileDetails = await fileTypeFromBuffer(arrayBuffer);
if (fileDetails && isSupportedIconFormat(fileDetails.ext)) {
return fileDetails.ext;
}
const contentType = response.headers
.get('content-type')
?.split(';')[0]
.trim();
if (contentType === 'image/svg+xml' && looksLikeSvg(arrayBuffer)) {
return 'svg';
}
if (getUrlExtension(iconUrl) === 'svg' && looksLikeSvg(arrayBuffer)) {
return 'svg';
}
return null;
}
async function resolveIconFromUrl(iconUrl, appName, downloadTimeout) {
const iconPath = await downloadIcon(iconUrl, false, downloadTimeout);
if (!iconPath) {
return null;
}
const convertedPath = await convertIconFormat(iconPath, appName);
if (!convertedPath) {
return null;
}
return await copyWindowsIconIfNeeded(convertedPath, appName);
}
async function tryResolveIconSource(source, domain, appName, downloadTimeout) {
const iconUrls = source === 'dashboard'
? generateDashboardIconUrls(appName)
: generateIconServiceUrls(domain);
for (const iconUrl of iconUrls) {
try {
const resolvedPath = await resolveIconFromUrl(iconUrl, appName, downloadTimeout);
if (resolvedPath) {
return resolvedPath;
}
}
catch (error) {
throwIfBuildCancelled();
if (error instanceof Error) {
const label = source === 'dashboard' ? 'Dashboard icon' : 'Icon service';
logger.debug(`${label} ${iconUrl} failed: ${error.message}`);
}
}
}
return null;
}
/**
* Attempts to fetch favicon from website
*/
async function tryGetFavicon(url, appName) {
let spinner;
try {
const domain = new URL(url).hostname;
spinner = getSpinner(`Fetching icon from ${domain}...`);
const isCI = process.env.CI === 'true' || process.env.GITHUB_ACTIONS === 'true';
const downloadTimeout = isCI
? ICON_CONFIG.downloadTimeout.ci
: ICON_CONFIG.downloadTimeout.default;
const sourcePriority = getIconSourcePriority(url, appName);
for (const source of sourcePriority) {
const resolvedIconPath = await tryResolveIconSource(source, domain, appName, downloadTimeout);
if (!resolvedIconPath) {
continue;
}
spinner.succeed(chalk.green(source === 'dashboard'
? `Icon found via dashboard-icons for "${appName}"!`
: 'Icon fetched and converted successfully!'));
return resolvedIconPath;
}
spinner.warn(`No favicon found for ${domain}. Using default.`);
return null;
}
catch (error) {
throwIfBuildCancelled();
if (error instanceof Error) {
logger.warn(`Failed to fetch favicon: ${error.message}`);
}
return null;
}
finally {
spinner?.stop();
}
}
/**
* Downloads icon from URL
*/
async function downloadIcon(iconUrl, showSpinner = true, customTimeout) {
if (isIconComposerUrl(iconUrl)) {
if (showSpinner) {
logger.warn('✼ Icon Composer .icon packages cannot be downloaded from a URL; pass a local path.');
}
return null;
}
throwIfBuildCancelled();
const buildSignal = getBuildCancellationSignal();
const controller = new AbortController();
const timeoutId = setTimeout(() => {
controller.abort();
}, customTimeout || 10000);
try {
const response = await fetch(iconUrl, {
signal: buildSignal
? AbortSignal.any([controller.signal, buildSignal])
: controller.signal,
});
if (!response.ok) {
if (response.status === 404 && !showSpinner) {
return null;
}
throw new Error(`HTTP ${response.status} ${response.statusText}`);
}
const arrayBuffer = await response.arrayBuffer();
if (!arrayBuffer || arrayBuffer.byteLength < ICON_CONFIG.minFileSize)
return null;
const extension = await detectDownloadedIconExtension(response, arrayBuffer, iconUrl);
if (!extension) {
return null;
}
return await saveIconFile(arrayBuffer, extension);
}
catch (error) {
throwIfBuildCancelled();
if (showSpinner) {
if (error instanceof Error && error.name === 'AbortError') {
logger.error('Icon download timed out!');
}
else {
logger.error('Icon download failed!', error instanceof Error ? error.message : String(error));
}
}
return null;
}
finally {
clearTimeout(timeoutId);
}
}
/**
* Saves icon file to temporary location
*/
async function saveIconFile(iconData, extension) {
const buffer = Buffer.from(iconData);
const { path: tempPath } = await dir();
// Always save with the original extension first
const originalIconPath = path.join(tempPath, `icon.${extension}`);
await fsExtra.outputFile(originalIconPath, buffer);
return originalIconPath;
}
function resolveAppName(name, platform) {
const domain = getDomain(name) || 'pake';
return platform !== 'linux' ? capitalizeFirstLetter(domain) : domain;
}
function resolveLocalAppName(filePath, platform) {
const baseName = path.parse(filePath).name || 'pake-app';
if (platform === 'linux') {
return generateLinuxPackageName(baseName) || 'pake-app';
}
const normalized = baseName
.replace(/[^a-zA-Z0-9\u4e00-\u9fff .-]/g, '')
.replace(/^[ .-]+/, '')
.replace(/\s+/g, ' ')
.trim();
return normalized || 'pake-app';
}
function isValidName(name, platform) {
const reg = platform === 'linux'
? /^[a-z0-9\u4e00-\u9fff][a-z0-9\u4e00-\u9fff-]*$/
: /^[a-zA-Z0-9\u4e00-\u9fff][a-zA-Z0-9\u4e00-\u9fff .-]*$/;
return !!name && reg.test(name);
}
async function handleOptions(options, url) {
const { platform } = process;
const isActions = process.env.GITHUB_ACTIONS;
let name = options.name;
const pathExists = await fsExtra.pathExists(url);
if (!options.name) {
const defaultName = pathExists
? resolveLocalAppName(url, platform)
: resolveAppName(url, platform);
if (isInteractive()) {
const promptMessage = 'Enter your application name';
const namePrompt = await promptText(promptMessage, defaultName);
name = namePrompt?.trim() || defaultName;
}
else {
name = defaultName;
}
}
if (name && platform === 'linux') {
name = generateLinuxPackageName(name);
}
if (name && !isValidName(name, platform)) {
const LINUX_NAME_ERROR = `✕ Name should only include lowercase letters, numbers, and dashes (not leading dashes). Examples: com-123-xxx, 123pan, pan123, weread, we-read, 123.`;
const DEFAULT_NAME_ERROR = `✕ Name should only include letters, numbers, dots, dashes, and spaces (not leading dots, dashes, and spaces). Examples: 123pan, 123Pan, Pan123, weread, WeRead, WERead, we-read, We Read, Vectorizer.AI, 123.`;
const errorMsg = platform === 'linux' ? LINUX_NAME_ERROR : DEFAULT_NAME_ERROR;
if (isActions) {
logger.error(errorMsg);
name = resolveAppName(url, platform);
logger.warn(`✼ Inside github actions, use the default name: ${name}`);
}
else {
throw new PakeError(errorMsg);
}
}
const resolvedName = name || 'pake-app';
const appOptions = {
...options,
name: resolvedName,
identifier: resolveIdentifier(url, options.name, options.identifier),
};
// --safe-domain is sugar over --internal-url-regex; an explicit regex wins.
if (!options.internalUrlRegex && options.safeDomain) {
appOptions.internalUrlRegex = safeDomainsToRegex(options.safeDomain);
}
// --no-bundle is Linux-only; keep normal packaging on other platforms.
if (appOptions.bundle === false && platform !== 'linux') {
logger.warn('✼ --no-bundle is only supported on Linux; ignoring it.');
appOptions.bundle = true;
}
const iconPath = await handleIcon(appOptions, url);
appOptions.icon = iconPath || '';
return appOptions;
}
const DEFAULT_PAKE_OPTIONS = {
icon: '',
height: 780,
width: 1200,
fullscreen: false,
maximize: false,
resizable: true,
hideTitleBar: false,
navigationButtons: false,
hideWindowDecorations: false,
alwaysOnTop: false,
appVersion: '1.0.0',
darkMode: false,
disabledWebShortcuts: false,
activationShortcut: '',
userAgent: '',
showSystemTray: false,
multiArch: false,
targets: (() => {
switch (process.platform) {
case 'linux':
return getDefaultLinuxTargets();
case 'darwin':
return 'dmg';
case 'win32':
return 'msi';
default:
return 'deb';
}
})(),
useLocalFile: false,
systemTrayIcon: '',
proxyUrl: '',
downloadDir: '',
basicAuth: false,
debug: false,
json: false,
inject: [],
installerLanguage: 'en-US',
hideOnClose: undefined, // Platform-specific: true for macOS, false for others
incognito: false,
restoreLastUrl: true,
passwordAutosave: false,
wasm: false,
enableDragDrop: false,
bundle: true,
keepBinary: false,
multiInstance: false,
multiWindow: false,
startToTray: false,
forceInternalNavigation: false,
internalUrlRegex: '',
safeDomain: '',
enableFind: false,
iterativeBuild: false,
zoom: 100,
minWidth: 0,
minHeight: 0,
ignoreCertificateErrors: false,
newWindow: false,
install: false,
camera: false,
microphone: false,
};
function getCliProgram() {
const { green, yellow } = chalk;
const logo = `${chalk.green(' ____ _')}
${green('| _ \\ __ _| | _____')}
${green('| |_) / _` | |/ / _ \\')}
${green('| __/ (_| | < __/')} ${yellow('https://github.com/tw93/pake')}
${green('|_| \\__,_|_|\\_\\___| can turn any webpage into a desktop app with Rust.')}
`;
return program$1
.addHelpText('beforeAll', logo)
.usage(`[url] [options]`)
.helpOption('-h, --help', 'Show all CLI options')
.showHelpAfterError()
.argument('[url]', 'The web URL you want to package', validateUrlInput)
.option('--name <string>', 'Application name')
.addOption(new Option('--identifier <string>', 'Application identifier / bundle ID').hideHelp())
.option('--icon <string>', 'Application icon (.icns / .icon on macOS, .ico on Windows, .png on Linux)', DEFAULT_PAKE_OPTIONS.icon)
.option('--width <number>', 'Window width', validateNumberInput, DEFAULT_PAKE_OPTIONS.width)
.option('--height <number>', 'Window height', validateNumberInput, DEFAULT_PAKE_OPTIONS.height)
.option('--use-local-file', 'Use local file packaging', DEFAULT_PAKE_OPTIONS.useLocalFile)
.option('--fullscreen', 'Start in full screen', DEFAULT_PAKE_OPTIONS.fullscreen)
.option('--hide-title-bar', 'For Mac, hide title bar', DEFAULT_PAKE_OPTIONS.hideTitleBar)
.option('--navigation-buttons', 'For Mac, show Back and Forward buttons in the title bar', DEFAULT_PAKE_OPTIONS.navigationButtons)
.option('--hide-window-decorations', 'Hide native window decorations on Windows and Linux', DEFAULT_PAKE_OPTIONS.hideWindowDecorations)
.option('--multi-arch', 'For Mac, both Intel and M1', DEFAULT_PAKE_OPTIONS.multiArch)
.option('--inject <files>', 'Inject local CSS/JS files into the page', (val, previous) => {
if (!val)
return DEFAULT_PAKE_OPTIONS.inject;
// Split by comma and trim whitespace, filter out empty strings
const files = val
.split(',')
.map((item) => item.trim())
.filter((item) => item.length > 0);
// If previous values exist (from multiple --inject options), merge them
return previous ? [...previous, ...files] : files;
}, DEFAULT_PAKE_OPTIONS.inject)
.option('--download-dir <path>', 'App download directory (absolute path or ~/path; default: system Downloads)', DEFAULT_PAKE_OPTIONS.downloadDir)
.option('--debug', 'Debug build and more output', DEFAULT_PAKE_OPTIONS.debug)
.option('--json', 'Machine-readable output: logs to stderr, one JSON result on stdout', DEFAULT_PAKE_OPTIONS.json)
.option('--config <path>', 'Load options from a JSON config file (fields mirror CLI options, see schema/pake.schema.json)')
.addOption(new Option('--basic-auth', 'Prompt for HTTP Basic credentials at runtime (macOS only)')
.default(DEFAULT_PAKE_OPTIONS.basicAuth)
.hideHelp())
.addOption(new Option('--proxy-url <url>', 'Proxy URL for all network requests (http://, https://, socks5://)')
.default(DEFAULT_PAKE_OPTIONS.proxyUrl)
.hideHelp())
.addOption(new Option('--user-agent <string>', 'Custom user agent')
.default(DEFAULT_PAKE_OPTIONS.userAgent)
.hideHelp())
.addOption(new Option('--targets <string>', 'Build target format for your system').default(DEFAULT_PAKE_OPTIONS.targets))
.addOption(new Option('--windows-toolchain <toolchain>', 'Windows Rust toolchain: msvc (default, requires Visual Studio Build Tools) or gnu (MinGW/MSYS2, for machines without them)').choices(['msvc', 'gnu']))
.addOption(new Option('--app-version <string>', 'App version, the same as package.json version')
.default(DEFAULT_PAKE_OPTIONS.appVersion)
.hideHelp())
.addOption(new Option('--always-on-top', 'Always on the top level')
.default(DEFAULT_PAKE_OPTIONS.alwaysOnTop)
.hideHelp())
.addOption(new Option('--maximize', 'Start window maximized')
.default(DEFAULT_PAKE_OPTIONS.maximize)
.hideHelp())
.addOption(new Option('--dark-mode', 'Force app to use dark mode (supports macOS, Windows, and Linux)')
.default(DEFAULT_PAKE_OPTIONS.darkMode)
.hideHelp())
.addOption(new Option('--disabled-web-shortcuts', 'Disabled webPage shortcuts')
.default(DEFAULT_PAKE_OPTIONS.disabledWebShortcuts)
.hideHelp())
.addOption(new Option('--activation-shortcut <string>', 'Shortcut key to active App')
.default(DEFAULT_PAKE_OPTIONS.activationShortcut)
.hideHelp())
.addOption(new Option('--show-system-tray', 'Show system tray in app')
.default(DEFAULT_PAKE_OPTIONS.showSystemTray)
.hideHelp())
.addOption(new Option('--system-tray-icon <string>', 'Custom system tray icon')
.default(DEFAULT_PAKE_OPTIONS.systemTrayIcon)
.hideHelp())
.addOption(new Option('--hide-on-close [boolean]', 'Hide window on close instead of exiting (default: true for macOS, false for others)')
.default(DEFAULT_PAKE_OPTIONS.hideOnClose)
.argParser((value) => {
if (value === undefined)
return true; // --hide-on-close without value
if (value === 'true')
return true;
if (value === 'false')
return false;
throw new InvalidArgumentError('--hide-on-close must be true or false');
})
.hideHelp())
.addOption(new Option('--title <string>', 'Window title').hideHelp())
.addOption(new Option('--no-restore-last-url', 'Open the packaged URL on launch while keeping cookies and storage')
.default(DEFAULT_PAKE_OPTIONS.restoreLastUrl)
.hideHelp())
.addOption(new Option('--incognito', 'Launch app in incognito/private mode')
.default(DEFAULT_PAKE_OPTIONS.incognito)
.hideHelp())
.addOption(new Option('--password-autosave', 'Enable native password-save prompts on Windows')
.default(DEFAULT_PAKE_OPTIONS.passwordAutosave)
.hideHelp())
.addOption(new Option('--wasm', 'Enable WebAssembly support (Flutter Web, etc.)')
.default(DEFAULT_PAKE_OPTIONS.wasm)
.hideHelp())
.addOption(new Option('--enable-drag-drop', 'Deprecated and ignored: pages handle drag and drop by default')
.default(DEFAULT_PAKE_OPTIONS.enableDragDrop)
.hideHelp())
.addOption(new Option('--keep-binary', 'Keep raw binary file alongside installer')
.default(DEFAULT_PAKE_OPTIONS.keepBinary)
.hideHelp())
.addOption(new Option('--no-bundle', 'Skip packaging, output only the raw executable (Linux; for RPM distros where the bundler aborts)')
.default(DEFAULT_PAKE_OPTIONS.bundle)
.hideHelp())
.addOption(new Option('--multi-instance', 'Allow multiple app instances')
.default(DEFAULT_PAKE_OPTIONS.multiInstance)
.hideHelp())
.addOption(new Option('--multi-window', 'Allow opening multiple windows within one app instance')
.default(DEFAULT_PAKE_OPTIONS.multiWindow)
.hideHelp())
.addOption(new Option('--start-to-tray', 'Start app minimized to tray')
.default(DEFAULT_PAKE_OPTIONS.startToTray)
.hideHelp())
.addOption(new Option('--force-internal-navigation', 'Keep every link inside the Pake window instead of opening external handlers').default(DEFAULT_PAKE_OPTIONS.forceInternalNavigation))
.addOption(new Option('--internal-url-regex <string>', 'Regex pattern to match URLs that should be considered internal').default(DEFAULT_PAKE_OPTIONS.internalUrlRegex))
.addOption(new Option('--safe-domain <domains>', 'Comma-separated domains kept inside the app (e.g. SSO/workspace callbacks)').default(DEFAULT_PAKE_OPTIONS.safeDomain))
.addOption(new Option('--enable-find', 'Enable in-page Find UI with Cmd/Ctrl+F/G shortcuts')
.default(DEFAULT_PAKE_OPTIONS.enableFind)
.hideHelp())
.addOption(new Option('--installer-language <string>', 'Installer language')
.default(DEFAULT_PAKE_OPTIONS.installerLanguage)
.hideHelp())
.addOption(new Option('--zoom <number>', 'Initial page zoom level (50-200)')
.default(DEFAULT_PAKE_OPTIONS.zoom)
.argParser((value) => {
const zoom = Number(value);
if (!Number.isInteger(zoom) || zoom < 50 || zoom > 200) {
throw new InvalidArgumentError('--zoom must be an integer between 50 and 200');
}
return zoom;
})
.hideHelp())
.addOption(new Option('--min-width <number>', 'Minimum window width')
.default(DEFAULT_PAKE_OPTIONS.minWidth)
.argParser(validateNumberInput)
.hideHelp())
.addOption(new Option('--min-height <number>', 'Minimum window height')
.default(DEFAULT_PAKE_OPTIONS.minHeight)
.argParser(validateNumberInput)
.hideHelp())
.addOption(new Option('--ignore-certificate-errors', 'Ignore certificate errors (for self-signed certificates)')
.default(DEFAULT_PAKE_OPTIONS.ignoreCertificateErrors)
.hideHelp())
.addOption(new Option('--iterative-build', 'Turn on rapid build mode (app only, no dmg/deb/msi), good for debugging')
.default(DEFAULT_PAKE_OPTIONS.iterativeBuild)
.hideHelp())
.addOption(new Option('--new-window', 'Allow sites to open new windows (for auth flows, tabs, branches)').default(DEFAULT_PAKE_OPTIONS.newWindow))
.addOption(new Option('--install', 'Auto-install app to /Applications (macOS) after build and remove local bundle')
.default(DEFAULT_PAKE_OPTIONS.install)
.hideHelp())
.addOption(new Option('--camera', 'Request camera permission on macOS')
.default(DEFAULT_PAKE_OPTIONS.camera)
.hideHelp())
.addOption(new Option('--microphone', 'Request microphone permission on macOS')
.default(DEFAULT_PAKE_OPTIONS.microphone)
.hideHelp())
.version(packageJson.version, '-v, --version')
.configureHelp({
sortSubcommands: true,
visibleOptions: (command) => {
const options = [...command.options];
const helpOption = command
._helpOption;
if (helpOption) {
options.push(helpOption);
}
return options;
},
optionTerm: (option) => {
return option.flags;
},
optionDescription: (option) => {
return option.description;
},
});
}
// Invocation concerns, not app manifest fields; pass these as CLI flags.
const REJECTED_KEYS = new Set(['config', 'json', 'version']);
// Optional CLI options that have no entry in DEFAULT_PAKE_OPTIONS.
const EXTRA_STRING_KEYS = new Set(['name', 'title', 'identifier']);
// Numeric fields share the CLI flag ranges (see cli-program.ts validators),
// so a config file cannot smuggle a value the same flag would reject.
// Like --zoom, zoom must be an integer: pake.json stores it as a Rust u32.
const NUMBER_RANGES = {
width: { min: 0 },
height: { min: 0 },
minWidth: { min: 0 },
minHeight: { min: 0 },
zoom: { min: 50, max: 200, integer: true },
};
// Fields whose CLI flag restricts the value set (see the .choices() calls in
// cli-program.ts), so a config file cannot smuggle a value the same flag
// would reject. Without this, an unknown value falls through to the builder's
// own fallback and silently produces the default behavior.
const ENUM_VALUES = {
windowsToolchain: ['msvc', 'gnu'],
};
function expectedTypeFor(key) {
if (key === 'inject')
return 'string[]';
if (key === 'hideOnClose')
return 'boolean';
if (EXTRA_STRING_KEYS.has(key))
return 'string';
const defaultValue = DEFAULT_PAKE_OPTIONS[key];
const type = typeof defaultValue;
if (type === 'string' || type === 'number' || type === 'boolean') {
return type;
}
return null;
}
function matchesType(value, type) {
if (type === 'string[]') {
return Array.isArray(value) && value.every((v) => typeof v === 'string');
}
return typeof value === type;
}
async function loadConfigFile(configPath, validKeys) {
if (!(await fsExtra.pathExists(configPath))) {
throw new PakeError(`Config file not found: ${configPath}`, {
code: 'INVALID_INPUT',
hint: 'Pass a path to a JSON file matching schema/pake.schema.json.',
});
}
let parsed;
try {
parsed = JSON.parse(await fsExtra.readFile(configPath, 'utf8'));
}
catch (error) {
const detail = error instanceof Error ? error.message : String(error);
throw new PakeError(`Config file is not valid JSON: ${detail}`, {
code: 'INVALID_INPUT',
hint: `Fix the JSON syntax in ${configPath}.`,
});
}
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
throw new PakeError('Config file must contain a JSON object.', {
code: 'INVALID_INPUT',
hint: 'See schema/pake.schema.json for the expected shape.',
});
}
const result = { options: {} };
for (const [key, value] of Object.entries(parsed)) {
if (key === '$schema')
continue;
if (key === 'url') {
if (typeof value !== 'string') {
throw new PakeError('Config field "url" must be a string.', {
code: 'INVALID_INPUT',
hint: 'Use a web URL or a local file/directory path.',
});
}
result.url = value;
continue;
}
if (REJECTED_KEYS.has(key)) {
throw new PakeError(`Config field "${key}" is not allowed in a config file.`, {
code: 'INVALID_INPUT',
hint: `Pass --${key} on the command line instead.`,
});
}
if (!validKeys.has(key)) {
throw new PakeError(`Unknown config field "${key}".`, {
code: 'INVALID_INPUT',
hint: 'Field names are camelCase CLI option names; see schema/pake.schema.json.',
});
}
const expected = expectedTypeFor(key);
if (expected && !matchesType(value, expected)) {
throw new PakeError(`Config field "${key}" must be of type ${expected}.`, {
code: 'INVALID_INPUT',
hint: 'See schema/pake.schema.json for field types.',
});
}
const allowed = ENUM_VALUES[key];
if (allowed && !allowed.includes(value)) {
throw new PakeError(`Config field "${key}" must be one of: ${allowed.join(', ')}.`, {
code: 'INVALID_INPUT',
hint: 'See schema/pake.schema.json for allowed values.',
});
}
if (typeof value === 'number') {
const range = NUMBER_RANGES[key];
const min = range?.min ?? 0;
const max = range?.max;
const integer = range?.integer === true;
if (!Number.isFinite(value) ||
(integer && !Number.isInteger(value)) ||
value < min ||
(max !== undefined && value > max)) {
const bounds = max !== undefined ? `${min}-${max}` : `>= ${min}`;
const kind = integer ? 'an integer' : 'a finite number';
throw new PakeError(`Config field "${key}" must be ${kind} (${bounds}).`, {
code: 'INVALID_INPUT',
hint: 'See schema/pake.schema.json for field ranges.',
});
}
}
if (!expected && (typeof value === 'object' || value === null)) {
throw new PakeError(`Config field "${key}" must be a string, number, or boolean.`, {
code: 'INVALID_INPUT',
hint: 'See schema/pake.schema.json for field types.',
});
}
result.options[key] = value;
}
return result;
}
const program = getCliProgram();
// Make commander throw instead of exiting so option/argument parse errors
// honor the exit-code contract (2 = invalid input) and still emit the JSON
// result object when --json was requested.
program.exitOverride();
function isCommanderExit(error) {
return (typeof error === 'object' &&
error !== null &&
typeof error.code === 'string' &&
error.code.startsWith('commander.'));
}
const PHASE_ERROR_CODES = {
input: 'INVALID_INPUT',
prepare: 'ENV_MISSING',
build: 'BUILD_FAILED',
};
function classifyError(error, phase) {
if (isPakeError(error)) {
return {
code: error.code ?? PHASE_ERROR_CODES[phase],
message: error.message,
hint: error.hint ?? null,
};
}
if (error instanceof Error) {
return {
code: PHASE_ERROR_CODES[phase],
message: error.message,
hint: null,
};
}
return {
code: 'UNEXPECTED',
message: `Unexpected error: ${String(error)}`,
hint: null,
};
}
async function checkUpdateTips() {
updateNotifier({ pkg: packageJson, updateCheckInterval: 1000 * 60 }).notify({
isGlobal: true,
});
}
program.action(async (urlArg, options) => {
const jsonMode = Boolean(options.json);
if (jsonMode) {
enableMachineMode();
}
let phase = 'input';
let appName = null;
let url = urlArg;
let leaveWorkspace;
let endCancellation;
try {
// Heal a dist_bak stranded by an earlier crashed local-input run before
// building, or this build would embed that run's staged files.
restoreLocalTree();
if (!jsonMode) {
await checkUpdateTips();
}
// Config file fills in whatever the command line did not set explicitly:
// CLI flag > config field > built-in default.
if (options.config) {
const validKeys = new Set(program.options.map((option) => option.attributeName()));
const loaded = await loadConfigFile(options.config, validKeys);
for (const [key, value] of Object.entries(loaded.options)) {
if (program.getOptionValueSource(key) !== 'cli') {
options[key] = value;
}
}
if (!url && loaded.url) {
try {
url = validateUrlInput(loaded.url);
}
catch (error) {
const detail = error instanceof Error ? error.message : String(error);
throw new PakeError(`Invalid "url" in config file: ${detail}`, {
code: 'INVALID_INPUT',
});
}
}
}
validateDownloadDirInput(options.downloadDir);
validateInternalUrlRegexInput(options.internalUrlRegex);
options.inject = validateInjectInput(options.inject);
if (!url) {
if (jsonMode) {
throw new PakeError('No URL or local path to package.', {
code: 'INVALID_INPUT',
hint: 'Pass a URL/path argument or a config file with a "url" field.',
});
}
program.help({
error: false,
});
return;
}
log.setDefaultLevel('info');
log.setLevel('info');
if (options.debug) {
log.setLevel('debug');
}
endCancellation = beginBuildCancellation();
phase = 'prepare';
const workspace = await enterBuildWorkspace();
leaveWorkspace = workspace;
phase = 'input';
const appOptions = await handleOptions(options, url);
throwIfBuildCancelled();
appName = appOptions.name ?? null;
const builder = BuilderProvider.create(appOptions);
phase = 'prepare';
await builder.prepare();
throwIfBuildCancelled();
phase = 'build';
await workspace.lockCache();
throwIfBuildCancelled();
await builder.build(url);
throwIfBuildCancelled();
await leaveWorkspace();
leaveWorkspace = undefined;
if (jsonMode) {
printJsonResult({
ok: true,
name: appName,
platform: process.platform,
arch: builder.getReportArch(),
outputs: builder.getArtifacts(),
warnings: getCapturedWarnings(),
error: null,
});
}
}
catch (error) {
// program.help() and --help/--version throw under exitOverride with
// exitCode 0; a clean commander exit is not a failure.
if (isCommanderExit(error) && error.exitCode === 0) {
return;
}
if (leaveWorkspace) {
await leaveWorkspace();
leaveWorkspace = undefined;
}
const classified = classifyError(error, phase);
if (jsonMode) {
printJsonResult({
ok: false,
name: appName,
platform: process.platform,
arch: null,
outputs: [],
warnings: getCapturedWarnings(),
error: classified,
});
}
else if (isPakeError(error)) {
console.error(chalk.red(classified.message));
if (classified.hint) {
console.error(chalk.yellow(`✼ ${classified.hint}`));
}
}
else if (error instanceof Error) {
console.error(chalk.red(`✕ ${error.message}`));
if (options?.debug && error.stack) {
console.error(chalk.gray(error.stack));
}
}
else {
console.error(chalk.red(`✕ Unexpected error: ${String(error)}`));
}
// exitCode + natural exit instead of process.exit: lets the finally
// restore run and guarantees the JSON result is flushed on piped stdout.
process.exitCode = ERROR_EXIT_CODES[classified.code];
}
finally {
// Failed builds discard their private inputs without touching the package.
try {
if (leaveWorkspace)
await leaveWorkspace();
}
finally {
endCancellation?.();
}
}
});
program.parseAsync().catch((error) => {
if (isCommanderExit(error)) {
// --help / --version and friends exit clean; commander already printed.
if (error.exitCode === 0) {
return;
}
// Parse errors (unknown option, invalid argument, missing value) are
// invalid input. Commander already printed the message to stderr; in
// json mode also emit the machine-readable result on stdout.
//
// Excess operands are almost always an unquoted value: `--name Google
// Translate` leaves `Translate` as a second operand, and commander's
// "too many arguments" names neither --name nor quoting, so the shape
// reads as "names with spaces are unsupported" (#1378).
const excessArguments = error.code === 'commander.excessArguments';
// Name the operand rather than asserting why it is there. Unquoting is the
// usual cause, but two bare URLs produce the same error and the quoting
// advice would be wrong for them.
const extraOperand = excessArguments ? program.args.slice(1)[0] : undefined;
const hint = excessArguments
? `Unexpected extra argument${extraOperand ? ` "${extraOperand}"` : ''}. A value containing spaces must be quoted, for example --name "Google Translate".`
: 'Run pake --help for the accepted options.';
if (process.argv.includes('--json')) {
printJsonResult({
ok: false,
name: null,
platform: process.platform,
arch: null,
outputs: [],
warnings: [],
error: {
code: 'INVALID_INPUT',
message: error.message.trim(),
hint,
},
});
}
else if (excessArguments) {
// Commander has already written its message and the full help, so this
// lands last, which is where the eye goes after a wall of help text.
console.error(chalk.red(`\u2715 ${hint}`));
}
process.exitCode = ERROR_EXIT_CODES.INVALID_INPUT;
return;
}
if (error instanceof Error) {
console.error(chalk.red(`✕ ${error.message}`));
}
else {
console.error(chalk.red(`✕ Unexpected error: ${String(error)}`));
}
process.exitCode = 1;
});