Skip to content

armgit / Pake

Public Imported from GitHub
0

Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.

fix: isolate CLI builds and safely clean up compiler processes

Tw935d66c330353c
diff --git a/bin/builders/BaseBuilder.ts b/bin/builders/BaseBuilder.ts
index 26f72bed..771ea5cc 100644
--- a/bin/builders/BaseBuilder.ts
+++ b/bin/builders/BaseBuilder.ts
@@ -11,11 +11,12 @@ import {
generateIdentifierSafeName,
generateLinuxPackageName,
} from '@/utils/name';
-import { npmDirectory } from '@/utils/dir';
+import { npmDirectory, packageDirectory } from '@/utils/dir';
import { PakeError } from '@/utils/error';
import { getSpinner } from '@/utils/info';
import { BuildArtifact, isInteractive } from '@/utils/output';
-import { shellExec } from '@/utils/shell';
+import { shellExec, type ShellCommand } from '@/utils/shell';
+import { hasReadyTauriCli } from '@/utils/tauri-cli';
import { CN_MIRROR_ENV, isCnMirrorEnabled } from '@/utils/mirror';
import { IS_MAC } from '@/utils/platform';
import logger from '@/options/logger';
@@ -122,7 +123,7 @@ export default abstract class BaseBuilder {
async prepare() {
const tauriSrcPath = path.join(npmDirectory, 'src-tauri');
- const tauriTargetPath = path.join(tauriSrcPath, 'target');
+ const tauriTargetPath = this.getCargoTargetDir();
const tauriTargetPathExists = await fsExtra.pathExists(tauriTargetPath);
if (!IS_MAC && !tauriTargetPathExists) {
@@ -156,10 +157,26 @@ export default abstract class BaseBuilder {
}
}
- const spinner = getSpinner('Installing package...');
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();
@@ -208,7 +225,7 @@ export default abstract class BaseBuilder {
async start(url: string) {
logger.info('Pake dev server starting...');
- await mergeConfig(url, this.options, tauriConfig);
+ await mergeConfig(url, this.options, structuredClone(tauriConfig));
const packageManager = await detectPackageManager();
const configPath = path.join(
@@ -219,25 +236,22 @@ export default abstract class BaseBuilder {
);
const features = this.getBuildFeatures();
- const featureArgs =
- features.length > 0 ? `--features ${features.join(',')}` : '';
-
- const argSeparator = packageManager === 'npm' ? ' --' : '';
- const command = `cd "${npmDirectory}" && ${packageManager} run tauri${argSeparator} dev --config "${configPath}" ${featureArgs}`;
+ 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(command);
+ await shellExec({ executable: packageManager, args });
}
async buildAndCopy(url: string, target: string, logSuccess = true) {
const { name = 'pake-app' } = this.options;
- await mergeConfig(url, this.options, tauriConfig);
+ await mergeConfig(url, this.options, structuredClone(tauriConfig));
const packageManager = await detectPackageManager();
// Build app
const buildSpinner = getSpinner('Building app...');
- // Let spinner run for a moment so user can see it, then stop before package manager command
- await new Promise((resolve) => setTimeout(resolve, 500));
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.
@@ -263,7 +277,7 @@ export default abstract class BaseBuilder {
);
}
- const buildCommand = `cd "${npmDirectory}" && ${this.getBuildCommand(packageManager)}`;
+ const buildCommand = this.getBuildCommand(packageManager);
const buildTimeout = getBuildTimeout();
try {
@@ -432,30 +446,27 @@ export default abstract class BaseBuilder {
packageManager: string,
configPath: string,
target?: string,
- ): string {
- const baseCommand = this.options.debug
- ? `${packageManager} run build:debug`
- : `${packageManager} run build`;
-
- const argSeparator = packageManager === 'npm' ? ' --' : '';
- let fullCommand = `${baseCommand}${argSeparator} -c "${configPath}"`;
+ ): ShellCommand {
+ const args = ['run', this.options.debug ? 'build:debug' : 'build'];
+ if (packageManager === 'npm') args.push('--');
+ args.push('-c', configPath);
if (target) {
- fullCommand += ` --target ${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) {
- fullCommand += ' --verbose';
+ args.push('--verbose');
}
const features = this.getBuildFeatures();
if (features.length > 0) {
- fullCommand += ` --features ${features.join(',')}`;
+ args.push('--features', features.join(','));
}
- return fullCommand;
+ return { executable: packageManager, args };
}
protected getBuildFeatures(): string[] {
@@ -472,7 +483,7 @@ export default abstract class BaseBuilder {
return features;
}
- protected getBuildCommand(packageManager: string = 'pnpm'): string {
+ protected getBuildCommand(packageManager: string = 'pnpm'): ShellCommand {
// Use temporary config directory to avoid modifying source files
const configPath = path.join(
npmDirectory,
@@ -481,11 +492,11 @@ export default abstract class BaseBuilder {
'tauri.conf.json',
);
- let fullCommand = this.buildBaseCommand(packageManager, configPath);
+ 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 += ' --bundles app';
+ fullCommand.args.push('--bundles', 'app');
}
return fullCommand;
diff --git a/bin/builders/LinuxBuilder.ts b/bin/builders/LinuxBuilder.ts
index 1e21830f..9ec09f21 100644
--- a/bin/builders/LinuxBuilder.ts
+++ b/bin/builders/LinuxBuilder.ts
@@ -1,9 +1,10 @@
import path from 'path';
+import os from 'os';
import fsExtra from 'fs-extra';
import BaseBuilder from './BaseBuilder';
import { PakeAppOptions } from '@/types';
-import tauriConfig from '@/helpers/tauriConfig';
-import { shellExec } from '@/utils/shell';
+import { shellExec, type ShellCommand } from '@/utils/shell';
+import { execa } from 'execa';
import { generateLinuxPackageName } from '@/utils/name';
import {
LINUX_TARGET_TYPES,
@@ -38,7 +39,7 @@ export default class LinuxBuilder extends BaseBuilder {
getFileName() {
const { name = 'pake-app', targets } = this.options;
- const version = tauriConfig.version;
+ const version = this.options.appVersion;
const buildType =
this.currentBuildType || targets.split(',').map((t) => t.trim())[0];
@@ -129,7 +130,7 @@ export default class LinuxBuilder extends BaseBuilder {
];
for (const { tool, pacmanPackage } of requiredTools) {
try {
- await shellExec(`command -v ${tool} >/dev/null 2>&1`);
+ 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}".`,
@@ -145,23 +146,25 @@ export default class LinuxBuilder extends BaseBuilder {
}) {
const { name = 'pake-app' } = this.options;
const packageName = generateLinuxPackageName(name);
- const version = tauriConfig.version;
+ 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`,
);
- const workDir = path.resolve('.pake-arch-package');
+ 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');
- await this.ensureArchPackagingTools();
- await fsExtra.remove(workDir);
- await fsExtra.ensureDir(dataDir);
- await fsExtra.ensureDir(controlDir);
-
try {
- await shellExec(`cd "${controlDir}" && ar x "${debPath}"`);
+ 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'),
);
@@ -169,9 +172,10 @@ export default class LinuxBuilder extends BaseBuilder {
throw new Error(`Could not find data.tar payload in ${debPath}`);
}
- await shellExec(
- `tar -xf "${path.join(controlDir, dataArchive)}" -C "${dataDir}"`,
- );
+ await shellExec({
+ executable: 'tar',
+ args: ['-xf', path.join(controlDir, dataArchive), '-C', dataDir],
+ });
// Drop the desktop entry auto-generated by the Tauri deb bundler;
// the payload already ships Pake's own com.pake.<name>.desktop.
await fsExtra.remove(
@@ -223,9 +227,19 @@ post_remove() {
}
`,
);
- await shellExec(
- `bsdtar --zstd -cf "${packagePath}" -C "${dataDir}" .PKGINFO .INSTALL usr`,
- );
+ 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);
@@ -259,7 +273,7 @@ post_remove() {
await super.buildAndCopy(url, target, logSuccess);
}
- protected getBuildCommand(packageManager: string = 'pnpm'): string {
+ protected getBuildCommand(packageManager: string = 'pnpm'): ShellCommand {
const configPath = path.join('src-tauri', '.pake', 'tauri.conf.json');
const buildTarget =
@@ -267,7 +281,7 @@ post_remove() {
? (this.getTauriTarget(this.buildArch, 'linux') ?? undefined)
: undefined;
- let fullCommand = this.buildBaseCommand(
+ const fullCommand = this.buildBaseCommand(
packageManager,
configPath,
buildTarget,
@@ -276,11 +290,12 @@ post_remove() {
// --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) {
- return `${fullCommand} --no-bundle`;
+ fullCommand.args.push('--no-bundle');
+ return fullCommand;
}
if (this.currentBuildType) {
- fullCommand += ` --bundles ${this.currentBuildType}`;
+ fullCommand.args.push('--bundles', this.currentBuildType);
}
// Enable verbose output for AppImage builds when debugging or PAKE_VERBOSE is set.
@@ -292,7 +307,7 @@ post_remove() {
this.options.debug ||
process.env.PAKE_VERBOSE)
) {
- fullCommand += ' --verbose';
+ fullCommand.args.push('--verbose');
}
return fullCommand;
diff --git a/bin/builders/MacBuilder.ts b/bin/builders/MacBuilder.ts
index 95d7e285..b69ebaa7 100644
--- a/bin/builders/MacBuilder.ts
+++ b/bin/builders/MacBuilder.ts
@@ -1,7 +1,7 @@
import path from 'path';
-import tauriConfig from '@/helpers/tauriConfig';
import { PakeAppOptions } from '@/types';
import BaseBuilder from './BaseBuilder';
+import type { ShellCommand } from '@/utils/shell';
export default class MacBuilder extends BaseBuilder {
private buildFormat: string;
@@ -47,7 +47,7 @@ export default class MacBuilder extends BaseBuilder {
} else {
arch = this.getArchDisplayName(this.resolveTargetArch(this.buildArch));
}
- return `${name}_${tauriConfig.version}_${arch}`;
+ return `${name}_${this.options.appVersion}_${arch}`;
}
getReportArch(): string {
@@ -65,7 +65,7 @@ export default class MacBuilder extends BaseBuilder {
return this.resolveTargetArch(this.buildArch);
}
- protected getBuildCommand(packageManager: string = 'pnpm'): string {
+ protected getBuildCommand(packageManager: string = 'pnpm'): ShellCommand {
const configPath = path.join('src-tauri', '.pake', 'tauri.conf.json');
const actualArch = this.getActualArch();
diff --git a/bin/builders/WinBuilder.ts b/bin/builders/WinBuilder.ts
index 8c36c371..a3b668d4 100644
--- a/bin/builders/WinBuilder.ts
+++ b/bin/builders/WinBuilder.ts
@@ -1,8 +1,8 @@
import path from 'path';
import BaseBuilder from './BaseBuilder';
import { PakeAppOptions } from '@/types';
-import tauriConfig from '@/helpers/tauriConfig';
import { generateIdentifierSafeName } from '@/utils/name';
+import type { ShellCommand } from '@/utils/shell';
export default class WinBuilder extends BaseBuilder {
private buildFormat: string = 'msi';
@@ -23,12 +23,12 @@ export default class WinBuilder extends BaseBuilder {
getFileName(): string {
const { name } = this.options;
- const language = tauriConfig.bundle.windows.wix.language[0];
+ const language = this.options.installerLanguage;
const targetArch = this.getArchDisplayName(this.buildArch);
- return `${name}_${tauriConfig.version}_${targetArch}_${language}`;
+ return `${name}_${this.options.appVersion}_${targetArch}_${language}`;
}
- protected getBuildCommand(packageManager: string = 'pnpm'): string {
+ protected getBuildCommand(packageManager: string = 'pnpm'): ShellCommand {
const configPath = path.join('src-tauri', '.pake', 'tauri.conf.json');
const buildTarget = this.getTauriTarget(this.buildArch, 'win32');
diff --git a/bin/builders/env.ts b/bin/builders/env.ts
index 8b5b5780..f14845d2 100644
--- a/bin/builders/env.ts
+++ b/bin/builders/env.ts
@@ -3,8 +3,8 @@ import fsExtra from 'fs-extra';
import { CN_MIRROR_ENV } from '@/utils/mirror';
import { IS_MAC } from '@/utils/platform';
-import { npmDirectory } from '@/utils/dir';
import logger from '@/options/logger';
+import type { ShellCommand } from '@/utils/shell';
import packageJson from '../../package.json';
/**
@@ -130,12 +130,11 @@ export async function detectPackageManager(): Promise<'pnpm' | 'npm'> {
export function getInstallCommand(
packageManager: string,
useCnMirror: boolean,
-): string {
- const registryOption = useCnMirror
- ? ' --registry=https://registry.npmmirror.com'
- : '';
- const peerDepsOption = packageManager === 'npm' ? ' --legacy-peer-deps' : '';
- return `cd "${npmDirectory}" && ${packageManager} install${registryOption}${peerDepsOption}`;
+): ShellCommand {
+ 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(
diff --git a/bin/cli.ts b/bin/cli.ts
index 408671b6..ffefa37d 100644
--- a/bin/cli.ts
+++ b/bin/cli.ts
@@ -7,6 +7,11 @@ import handleInputOptions from './options/index';
import { getCliProgram } from './helpers/cli-program';
import { loadConfigFile } from './helpers/config-file';
import { restoreLocalTree } from './helpers/merge';
+import {
+ beginBuildCancellation,
+ enterBuildWorkspace,
+ throwIfBuildCancelled,
+} from './utils/build-workspace';
import { isPakeError, PakeError } from './utils/error';
import { validateUrlInput } from './utils/validate';
import {
@@ -86,6 +91,8 @@ program.action(async (urlArg: string, options: PakeCliOptions) => {
let phase: BuildPhase = 'input';
let appName: string | null = null;
let url = urlArg;
+ let leaveWorkspace: (() => Promise<void>) | undefined;
+ let endCancellation: (() => void) | undefined;
try {
// Heal a dist_bak stranded by an earlier crashed local-input run before
@@ -139,14 +146,24 @@ program.action(async (urlArg: string, options: PakeCliOptions) => {
log.setLevel('debug');
}
+ endCancellation = beginBuildCancellation();
+ phase = 'prepare';
+ leaveWorkspace = await enterBuildWorkspace();
+ phase = 'input';
const appOptions = await handleInputOptions(options, url);
+ throwIfBuildCancelled();
appName = appOptions.name ?? null;
const builder = BuilderProvider.create(appOptions);
phase = 'prepare';
await builder.prepare();
+ throwIfBuildCancelled();
phase = 'build';
await builder.build(url);
+ throwIfBuildCancelled();
+
+ await leaveWorkspace();
+ leaveWorkspace = undefined;
if (jsonMode) {
printJsonResult({
@@ -166,6 +183,11 @@ program.action(async (urlArg: string, options: PakeCliOptions) => {
return;
}
+ if (leaveWorkspace) {
+ await leaveWorkspace();
+ leaveWorkspace = undefined;
+ }
+
const classified = classifyError(error, phase);
if (jsonMode) {
@@ -196,10 +218,12 @@ program.action(async (urlArg: string, options: PakeCliOptions) => {
// restore run and guarantees the JSON result is flushed on piped stdout.
process.exitCode = ERROR_EXIT_CODES[classified.code];
} finally {
- // A local-input run replaces the package's own dist/ during staging; put
- // it back so the CLI stays intact and later builds cannot embed this
- // user's files.
- restoreLocalTree();
+ // Failed builds discard their private inputs without touching the package.
+ try {
+ if (leaveWorkspace) await leaveWorkspace();
+ } finally {
+ endCancellation?.();
+ }
}
});
diff --git a/bin/helpers/merge.ts b/bin/helpers/merge.ts
index b135fea5..7d02fdd4 100644
--- a/bin/helpers/merge.ts
+++ b/bin/helpers/merge.ts
@@ -16,7 +16,11 @@ import {
TauriPlatform,
WindowConfig,
} from '@/types';
-import { tauriConfigDirectory, npmDirectory } from '@/utils/dir';
+import {
+ tauriConfigDirectory,
+ npmDirectory,
+ packageDirectory,
+} from '@/utils/dir';
import { PakeError } from '@/utils/error';
import { LINUX_TARGET_TYPES, resolveLinuxBundleTargets } from '@/utils/targets';
@@ -123,8 +127,11 @@ async function stageLocalTree(sourceDir: string): Promise<void> {
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 ||
diff --git a/bin/helpers/rust.ts b/bin/helpers/rust.ts
index 4a61f76a..804fd340 100644
--- a/bin/helpers/rust.ts
+++ b/bin/helpers/rust.ts
@@ -68,29 +68,58 @@ export function ensureRustEnv() {
}
export async function installRust() {
- const rustInstallScriptForUnix = isCnMirrorEnabled()
- ? 'export RUSTUP_DIST_SERVER="https://rsproxy.cn" && export RUSTUP_UPDATE_ROOT="https://rsproxy.cn/rustup" && curl --proto "=https" --tlsv1.2 -sSf https://rsproxy.cn/rustup-init.sh | sh'
- : "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y";
- const rustInstallScriptForWindows = 'winget install --id Rustlang.Rustup';
-
const spinner = getSpinner('Downloading Rust...');
try {
- await shellExec(
- IS_WIN ? rustInstallScriptForWindows : rustInstallScriptForUnix,
- 300000,
- undefined,
- );
+ 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!'));
- if (error instanceof Error) {
- console.error(error.message);
- } else {
- console.error(error);
- }
- process.exit(1);
+ // The CLI owns error reporting and workspace/cache cleanup.
+ throw error;
}
}
diff --git a/bin/options/icon.ts b/bin/options/icon.ts
index c313bf3d..4eeed823 100644
--- a/bin/options/icon.ts
+++ b/bin/options/icon.ts
@@ -687,8 +687,6 @@ export async function downloadIcon(
signal: controller.signal,
});
- clearTimeout(timeoutId);
-
if (!response.ok) {
if (response.status === 404 && !showSpinner) {
return null;
@@ -712,7 +710,6 @@ export async function downloadIcon(
return await saveIconFile(arrayBuffer, extension);
} catch (error: unknown) {
- clearTimeout(timeoutId);
if (showSpinner) {
if (error instanceof Error && error.name === 'AbortError') {
logger.error('Icon download timed out!');
@@ -724,6 +721,8 @@ export async function downloadIcon(
}
}
return null;
+ } finally {
+ clearTimeout(timeoutId);
}
}
diff --git a/bin/utils/build-workspace.ts b/bin/utils/build-workspace.ts
new file mode 100644
index 00000000..7f1ed4f8
--- /dev/null
+++ b/bin/utils/build-workspace.ts
@@ -0,0 +1,201 @@
+import os from 'os';
+import path from 'path';
+import fs from 'fs-extra';
+import { setTimeout as delay } from 'timers/promises';
+import { packageDirectory, setBuildDirectory } from './dir';
+import logger from '@/options/logger';
+import { PakeError } from './error';
+import { hasReadyTauriCli } from './tauri-cli';
+
+let cancellation:
+ | { controller: AbortController; unsafeCleanup?: string }
+ | undefined;
+
+export function beginBuildCancellation(): () => void {
+ const scope = { controller: new AbortController() };
+ cancellation = scope;
+ const cancel = (signal: NodeJS.Signals) =>
+ 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;
+ };
+}
+
+export function getBuildCancellationSignal(): AbortSignal | undefined {
+ return cancellation?.controller.signal;
+}
+
+export function preventBuildWorkspaceCleanup(reason: string): void {
+ if (cancellation) cancellation.unsafeCleanup = reason;
+}
+
+export function throwIfBuildCancelled(): void {
+ getBuildCancellationSignal()?.throwIfAborted();
+}
+
+/** Copy only build inputs; cached or previously generated user content is not a template. */
+export async function createBuildWorkspace(sourceDirectory: string) {
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'pake-build-'));
+ try {
+ for (const file of [
+ 'package.json',
+ 'pnpm-lock.yaml',
+ 'package-lock.json',
+ ]) {
+ const source = path.join(sourceDirectory, file);
+ if (await fs.pathExists(source))
+ await fs.copy(source, path.join(directory, file));
+ }
+ const sourceTauri = path.join(sourceDirectory, 'src-tauri');
+ await fs.copy(sourceTauri, path.join(directory, 'src-tauri'), {
+ filter: (source) =>
+ !['target', '.pake', 'gen'].includes(
+ path.relative(sourceTauri, source).split(path.sep)[0],
+ ),
+ });
+ await fs.ensureDir(path.join(directory, 'dist'));
+ // Keep the CLI runnable while local input staging replaces this workspace's dist.
+ await fs.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 fs.symlink(
+ modules,
+ path.join(directory, 'node_modules'),
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ }
+ return directory;
+ } catch (error) {
+ await fs.remove(directory);
+ throw error;
+ }
+}
+
+/** Hold the cache through artifact copying, beyond Cargo's own compile lock. */
+export async function acquireBuildCache(
+ targetDirectory: string,
+): Promise<() => Promise<void>> {
+ await fs.ensureDir(targetDirectory);
+ const lock = path.join(targetDirectory, '.pake-build.lock');
+ const started = Date.now();
+ let announced = false;
+ for (;;) {
+ throwIfBuildCancelled();
+ try {
+ const handle = await fs.open(lock, 'wx');
+ try {
+ fs.writeFileSync(handle, String(process.pid));
+ } finally {
+ fs.closeSync(handle);
+ }
+ let released = false;
+ return async () => {
+ if (!released) {
+ await fs.remove(lock);
+ released = true;
+ }
+ };
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;
+ }
+ try {
+ const owner = Number(await fs.readFile(lock, 'utf8'));
+ if (Number.isInteger(owner) && owner > 0) {
+ try {
+ process.kill(owner, 0);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).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 as NodeJS.ErrnoException).code === 'ENOENT') continue;
+ throw error;
+ }
+ if (Date.now() - started > 900_000) {
+ 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 delay(200);
+ }
+}
+
+export async function enterBuildWorkspace(): Promise<() => Promise<void>> {
+ const previousTarget = process.env.CARGO_TARGET_DIR;
+ const targetDirectory = path.resolve(
+ packageDirectory,
+ previousTarget || 'src-tauri/target',
+ );
+ const release = await acquireBuildCache(targetDirectory);
+ let directory: string;
+ try {
+ directory = await createBuildWorkspace(packageDirectory);
+ } catch (error) {
+ await release();
+ throw error;
+ }
+ 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 fs.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 leave;
+}
diff --git a/bin/utils/dir.ts b/bin/utils/dir.ts
index c261667b..5f8c92d2 100644
--- a/bin/utils/dir.ts
+++ b/bin/utils/dir.ts
@@ -5,10 +5,17 @@ import { fileURLToPath } from 'url';
const currentModulePath = fileURLToPath(import.meta.url);
// Resolve the parent directory of the current module
-export const npmDirectory = path.join(path.dirname(currentModulePath), '..');
-
-export const tauriConfigDirectory = path.join(
- npmDirectory,
- 'src-tauri',
- '.pake',
+export const packageDirectory = path.join(
+ path.dirname(currentModulePath),
+ '..',
);
+export let npmDirectory = packageDirectory;
+
+export 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.
+export function setBuildDirectory(directory: string): void {
+ npmDirectory = directory;
+ tauriConfigDirectory = path.join(directory, 'src-tauri', '.pake');
+}
diff --git a/bin/utils/shell.ts b/bin/utils/shell.ts
index cc141fcf..9c14f51c 100644
--- a/bin/utils/shell.ts
+++ b/bin/utils/shell.ts
@@ -1,15 +1,65 @@
import { execa } from 'execa';
import { npmDirectory } from './dir';
import { isMachineMode } from './output';
+import { setTimeout as delay } from 'timers/promises';
+import {
+ getBuildCancellationSignal,
+ preventBuildWorkspaceCleanup,
+} from './build-workspace';
+
+export interface ShellCommand {
+ executable: string;
+ args: string[];
+ cwd?: string;
+}
+
+async function terminateBuildTree(pid: number): Promise<void> {
+ if (process.platform === 'win32') {
+ await execa('taskkill', ['/pid', String(pid), '/T', '/F'], {
+ timeout: 5000,
+ windowsHide: true,
+ });
+ return;
+ }
+
+ const killGroup = (signal: NodeJS.Signals) => {
+ try {
+ process.kill(-pid, signal);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).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 delay(25);
+ }
+}
export async function shellExec(
- command: string,
+ command: ShellCommand,
timeout: number = 300000,
env?: Record<string, string>,
) {
+ const signal = getBuildCancellationSignal();
+ signal?.throwIfAborted();
try {
- const { exitCode } = await execa(command, {
- cwd: npmDirectory,
+ 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,
@@ -17,18 +67,43 @@ export async function shellExec(
stdin: 'inherit',
stdout: isMachineMode() ? process.stderr : 'inherit',
stderr: 'inherit',
- shell: true,
+ shell: false,
+ detached: Boolean(signal) && process.platform !== 'win32',
timeout,
env: env ? { ...process.env, ...env } : process.env,
});
- return exitCode;
+ let termination: Promise<void> | undefined;
+ 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: any) {
+ 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: "${command}". Try increasing timeout or check network connectivity.`,
+ `Command timed out after ${timeout}ms: ${description}. Try increasing timeout or check network connectivity.`,
);
}
@@ -36,7 +111,7 @@ export async function shellExec(
// 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 "${command}". Exit code: ${exitCode}. Details: ${errorMessage}`,
+ `Error occurred while executing command ${description}. Exit code: ${exitCode}. Details: ${errorMessage}`,
);
}
}
diff --git a/bin/utils/tauri-cli.ts b/bin/utils/tauri-cli.ts
new file mode 100644
index 00000000..e24107e1
--- /dev/null
+++ b/bin/utils/tauri-cli.ts
@@ -0,0 +1,28 @@
+import path from 'path';
+import fs from 'fs-extra';
+import { execa } from 'execa';
+
+/** Check the local launcher and native binding, not just an installed manifest. */
+export async function hasReadyTauriCli(directory: string): Promise<boolean> {
+ 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 fs.access(
+ launcher,
+ process.platform === 'win32' ? fs.constants.F_OK : fs.constants.X_OK,
+ );
+ await execa(process.execPath, [entry, '--version'], {
+ cwd: directory,
+ stdio: 'ignore',
+ timeout: 10_000,
+ });
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/dist/cli.js b/dist/cli.js
index 2e895e66..450ee6da 100644
--- a/dist/cli.js
+++ b/dist/cli.js
@@ -4,13 +4,14 @@ import chalk from 'chalk';
import updateNotifier from 'update-notifier';
import path from 'path';
import fsExtra from 'fs-extra';
-import { fileURLToPath } from 'url';
import prompts from 'prompts';
import os from 'os';
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 { dir } from 'tmp-promise';
import { fileTypeFromBuffer } from 'file-type';
@@ -98,7 +99,6 @@ var devDependencies = {
"@types/prompts": "^2.4.9",
"@types/tmp": "^0.2.6",
"@types/update-notifier": "^6.0.8",
- "app-root-path": "^3.1.0",
"cross-env": "^10.1.0",
prettier: "^3.8.1",
rollup: "^4.59.0",
@@ -139,40 +139,6 @@ var packageJson = {
pnpm: pnpm
};
-// Convert the current module URL to a file path
-const currentModulePath = fileURLToPath(import.meta.url);
-// Resolve the parent directory of the current module
-const npmDirectory = path.join(path.dirname(currentModulePath), '..');
-const tauriConfigDirectory = path.join(npmDirectory, 'src-tauri', '.pake');
-
-// 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$2 } = process;
-// @ts-ignore
-const platformConfig = platformConfigs[platform$2];
-let tauriConfig = {
- ...CommonConf,
- bundle: platformConfig.bundle,
- app: {
- ...CommonConf.app,
- trayIcon: {
- ...(platformConfig?.app?.trayIcon ?? {}),
- },
- },
- build: CommonConf.build,
- pake: pakeConf,
-};
-
// 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 = {
@@ -281,10 +247,10 @@ function isCnMirrorEnabled(value = process.env[CN_MIRROR_ENV]) {
return TRUE_VALUES.has((value ?? '').trim().toLowerCase());
}
-const { platform: platform$1 } = process;
-const IS_MAC = platform$1 === 'darwin';
-const IS_WIN = platform$1 === 'win32';
-const IS_LINUX = platform$1 === 'linux';
+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',
@@ -373,10 +339,293 @@ 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',
+ ]) {
+ 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 release = await acquireBuildCache(targetDirectory);
+ let directory;
+ try {
+ directory = await createBuildWorkspace(packageDirectory);
+ }
+ catch (error) {
+ await release();
+ throw error;
+ }
+ 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 leave;
+}
+
+async function terminateBuildTree(pid) {
+ if (process.platform === 'win32') {
+ await execa('taskkill', ['/pid', String(pid), '/T', '/F'], {
+ timeout: 5000,
+ windowsHide: true,
+ });
+ 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 { exitCode } = await execa(command, {
- cwd: npmDirectory,
+ 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,
@@ -384,22 +633,53 @@ async function shellExec(command, timeout = 300000, env) {
stdin: 'inherit',
stdout: isMachineMode() ? process.stderr : 'inherit',
stderr: 'inherit',
- shell: true,
+ shell: false,
+ detached: Boolean(signal) && process.platform !== 'win32',
timeout,
env: env ? { ...process.env, ...env } : process.env,
});
- return exitCode;
+ 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: "${command}". Try increasing timeout or check network connectivity.`);
+ 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 "${command}". Exit code: ${exitCode}. Details: ${errorMessage}`);
+ throw new Error(`Error occurred while executing command ${description}. Exit code: ${exitCode}. Details: ${errorMessage}`);
}
}
@@ -450,25 +730,54 @@ function ensureRustEnv() {
ensureCargoBinOnPath();
}
async function installRust() {
- const rustInstallScriptForUnix = isCnMirrorEnabled()
- ? 'export RUSTUP_DIST_SERVER="https://rsproxy.cn" && export RUSTUP_UPDATE_ROOT="https://rsproxy.cn/rustup" && curl --proto "=https" --tlsv1.2 -sSf https://rsproxy.cn/rustup-init.sh | sh'
- : "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y";
- const rustInstallScriptForWindows = 'winget install --id Rustlang.Rustup';
const spinner = getSpinner('Downloading Rust...');
try {
- await shellExec(IS_WIN ? rustInstallScriptForWindows : rustInstallScriptForUnix, 300000, undefined);
+ 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!'));
- if (error instanceof Error) {
- console.error(error.message);
- }
- else {
- console.error(error);
- }
- process.exit(1);
+ // The CLI owns error reporting and workspace/cache cleanup.
+ throw error;
}
}
function checkRustInstalled() {
@@ -506,24 +815,6 @@ async function combineFiles(files, output) {
return files;
}
-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)));
- },
-};
-
function generateSafeFilename(name) {
return name
.replace(/[<>:"/\\|?*]/g, '_')
@@ -561,31 +852,6 @@ function generateIdentifierSafeName(name) {
return cleaned;
}
-/**
- * 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));
-}
-
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.
@@ -688,8 +954,11 @@ async function stageLocalTree(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 === resolvedPackage ||
+ if (resolvedSource === installedPackage ||
+ installedPackage.startsWith(resolvedSource + path.sep) ||
+ resolvedSource === resolvedPackage ||
resolvedPackage.startsWith(resolvedSource + path.sep) ||
resolvedSource === packageDist ||
resolvedSource.startsWith(packageDist + path.sep)) {
@@ -1041,6 +1310,34 @@ async function mergeConfig(url, options, tauriConf) {
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,
+ trayIcon: {
+ ...(platformConfig?.app?.trayIcon ?? {}),
+ },
+ },
+ 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
@@ -1132,11 +1429,12 @@ async function detectPackageManager() {
return 'pnpm';
}
function getInstallCommand(packageManager, useCnMirror) {
- const registryOption = useCnMirror
- ? ' --registry=https://registry.npmmirror.com'
- : '';
- const peerDepsOption = packageManager === 'npm' ? ' --legacy-peer-deps' : '';
- return `cd "${npmDirectory}" && ${packageManager} install${registryOption}${peerDepsOption}`;
+ 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)) {
@@ -1268,7 +1566,7 @@ class BaseBuilder {
}
async prepare() {
const tauriSrcPath = path.join(npmDirectory, 'src-tauri');
- const tauriTargetPath = path.join(tauriSrcPath, 'target');
+ const tauriTargetPath = this.getCargoTargetDir();
const tauriTargetPathExists = await fsExtra.pathExists(tauriTargetPath);
if (!IS_MAC && !tauriTargetPathExists) {
logger.warn('✼ The first use requires installing system dependencies.');
@@ -1297,9 +1595,21 @@ class BaseBuilder {
});
}
}
- const spinner = getSpinner('Installing package...');
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();
@@ -1335,23 +1645,24 @@ class BaseBuilder {
}
async start(url) {
logger.info('Pake dev server starting...');
- await mergeConfig(url, this.options, tauriConfig);
+ 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 featureArgs = features.length > 0 ? `--features ${features.join(',')}` : '';
- const argSeparator = packageManager === 'npm' ? ' --' : '';
- const command = `cd "${npmDirectory}" && ${packageManager} run tauri${argSeparator} dev --config "${configPath}" ${featureArgs}`;
- await shellExec(command);
+ 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) {
const { name = 'pake-app' } = this.options;
- await mergeConfig(url, this.options, tauriConfig);
+ await mergeConfig(url, this.options, structuredClone(tauriConfig));
const packageManager = await detectPackageManager();
// Build app
const buildSpinner = getSpinner('Building app...');
- // Let spinner run for a moment so user can see it, then stop before package manager command
- await new Promise((resolve) => setTimeout(resolve, 500));
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.
@@ -1368,7 +1679,7 @@ class BaseBuilder {
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 buildCommand = `cd "${npmDirectory}" && ${this.getBuildCommand(packageManager)}`;
+ const buildCommand = this.getBuildCommand(packageManager);
const buildTimeout = getBuildTimeout();
try {
await shellExec(buildCommand, buildTimeout, resolveExecEnv());
@@ -1476,24 +1787,23 @@ class BaseBuilder {
return BaseBuilder.ARCH_DISPLAY_NAMES[arch] || arch;
}
buildBaseCommand(packageManager, configPath, target) {
- const baseCommand = this.options.debug
- ? `${packageManager} run build:debug`
- : `${packageManager} run build`;
- const argSeparator = packageManager === 'npm' ? ' --' : '';
- let fullCommand = `${baseCommand}${argSeparator} -c "${configPath}"`;
+ const args = ['run', this.options.debug ? 'build:debug' : 'build'];
+ if (packageManager === 'npm')
+ args.push('--');
+ args.push('-c', configPath);
if (target) {
- fullCommand += ` --target ${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) {
- fullCommand += ' --verbose';
+ args.push('--verbose');
}
const features = this.getBuildFeatures();
if (features.length > 0) {
- fullCommand += ` --features ${features.join(',')}`;
+ args.push('--features', features.join(','));
}
- return fullCommand;
+ return { executable: packageManager, args };
}
getBuildFeatures() {
const features = ['cli-build'];
@@ -1509,10 +1819,10 @@ class BaseBuilder {
getBuildCommand(packageManager = 'pnpm') {
// Use temporary config directory to avoid modifying source files
const configPath = path.join(npmDirectory, 'src-tauri', '.pake', 'tauri.conf.json');
- let fullCommand = this.buildBaseCommand(packageManager, configPath);
+ 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 += ' --bundles app';
+ fullCommand.args.push('--bundles', 'app');
}
return fullCommand;
}
@@ -1663,7 +1973,7 @@ class MacBuilder extends BaseBuilder {
else {
arch = this.getArchDisplayName(this.resolveTargetArch(this.buildArch));
}
- return `${name}_${tauriConfig.version}_${arch}`;
+ return `${name}_${this.options.appVersion}_${arch}`;
}
getReportArch() {
return this.getActualArch();
@@ -1726,9 +2036,9 @@ class WinBuilder extends BaseBuilder {
}
getFileName() {
const { name } = this.options;
- const language = tauriConfig.bundle.windows.wix.language[0];
+ const language = this.options.installerLanguage;
const targetArch = this.getArchDisplayName(this.buildArch);
- return `${name}_${tauriConfig.version}_${targetArch}_${language}`;
+ return `${name}_${this.options.appVersion}_${targetArch}_${language}`;
}
getBuildCommand(packageManager = 'pnpm') {
const configPath = path.join('src-tauri', '.pake', 'tauri.conf.json');
@@ -1784,7 +2094,7 @@ class LinuxBuilder extends BaseBuilder {
}
getFileName() {
const { name = 'pake-app', targets } = this.options;
- const version = tauriConfig.version;
+ const version = this.options.appVersion;
const buildType = this.currentBuildType || targets.split(',').map((t) => t.trim())[0];
let arch;
if (this.buildArch === 'arm64') {
@@ -1862,7 +2172,7 @@ class LinuxBuilder extends BaseBuilder {
];
for (const { tool, pacmanPackage } of requiredTools) {
try {
- await shellExec(`command -v ${tool} >/dev/null 2>&1`);
+ 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}".`);
@@ -1872,24 +2182,30 @@ class LinuxBuilder extends BaseBuilder {
async createArchPackageFromDeb({ removeSourceDeb, }) {
const { name = 'pake-app' } = this.options;
const packageName = generateLinuxPackageName(name);
- const version = tauriConfig.version;
+ 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`);
- const workDir = path.resolve('.pake-arch-package');
+ 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');
- await this.ensureArchPackagingTools();
- await fsExtra.remove(workDir);
- await fsExtra.ensureDir(dataDir);
- await fsExtra.ensureDir(controlDir);
try {
- await shellExec(`cd "${controlDir}" && ar x "${debPath}"`);
+ 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(`tar -xf "${path.join(controlDir, dataArchive)}" -C "${dataDir}"`);
+ await shellExec({
+ executable: 'tar',
+ args: ['-xf', path.join(controlDir, dataArchive), '-C', dataDir],
+ });
// Drop the desktop entry auto-generated by the Tauri deb bundler;
// the payload already ships Pake's own com.pake.<name>.desktop.
await fsExtra.remove(path.join(dataDir, 'usr', 'share', 'applications', `${packageName}.desktop`));
@@ -1929,7 +2245,19 @@ post_remove() {
update-desktop-database -q usr/share/applications
}
`);
- await shellExec(`bsdtar --zstd -cf "${packagePath}" -C "${dataDir}" .PKGINFO .INSTALL usr`);
+ 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);
@@ -1967,14 +2295,15 @@ post_remove() {
const buildTarget = this.buildArch === 'arm64'
? (this.getTauriTarget(this.buildArch, 'linux') ?? undefined)
: undefined;
- let fullCommand = this.buildBaseCommand(packageManager, configPath, buildTarget);
+ 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) {
- return `${fullCommand} --no-bundle`;
+ fullCommand.args.push('--no-bundle');
+ return fullCommand;
}
if (this.currentBuildType) {
- fullCommand += ` --bundles ${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,
@@ -1983,7 +2312,7 @@ post_remove() {
(this.options.targets.includes('appimage') ||
this.options.debug ||
process.env.PAKE_VERBOSE)) {
- fullCommand += ' --verbose';
+ fullCommand.args.push('--verbose');
}
return fullCommand;
}
@@ -2831,7 +3160,6 @@ async function downloadIcon(iconUrl, showSpinner = true, customTimeout) {
const response = await fetch(iconUrl, {
signal: controller.signal,
});
- clearTimeout(timeoutId);
if (!response.ok) {
if (response.status === 404 && !showSpinner) {
return null;
@@ -2848,7 +3176,6 @@ async function downloadIcon(iconUrl, showSpinner = true, customTimeout) {
return await saveIconFile(arrayBuffer, extension);
}
catch (error) {
- clearTimeout(timeoutId);
if (showSpinner) {
if (error instanceof Error && error.name === 'AbortError') {
logger.error('Icon download timed out!');
@@ -2859,6 +3186,9 @@ async function downloadIcon(iconUrl, showSpinner = true, customTimeout) {
}
return null;
}
+ finally {
+ clearTimeout(timeoutId);
+ }
}
/**
* Saves icon file to temporary location
@@ -3437,6 +3767,8 @@ program.action(async (urlArg, options) => {
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.
@@ -3483,13 +3815,22 @@ program.action(async (urlArg, options) => {
if (options.debug) {
log.setLevel('debug');
}
+ endCancellation = beginBuildCancellation();
+ phase = 'prepare';
+ leaveWorkspace = await enterBuildWorkspace();
+ 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 builder.build(url);
+ throwIfBuildCancelled();
+ await leaveWorkspace();
+ leaveWorkspace = undefined;
if (jsonMode) {
printJsonResult({
ok: true,
@@ -3508,6 +3849,10 @@ program.action(async (urlArg, options) => {
if (isCommanderExit(error) && error.exitCode === 0) {
return;
}
+ if (leaveWorkspace) {
+ await leaveWorkspace();
+ leaveWorkspace = undefined;
+ }
const classified = classifyError(error, phase);
if (jsonMode) {
printJsonResult({
@@ -3540,10 +3885,14 @@ program.action(async (urlArg, options) => {
process.exitCode = ERROR_EXIT_CODES[classified.code];
}
finally {
- // A local-input run replaces the package's own dist/ during staging; put
- // it back so the CLI stays intact and later builds cannot embed this
- // user's files.
- restoreLocalTree();
+ // Failed builds discard their private inputs without touching the package.
+ try {
+ if (leaveWorkspace)
+ await leaveWorkspace();
+ }
+ finally {
+ endCancellation?.();
+ }
}
});
program.parseAsync().catch((error) => {
diff --git a/package.json b/package.json
index 8977f5a7..5a00ec95 100644
--- a/package.json
+++ b/package.json
@@ -80,7 +80,6 @@
"@types/prompts": "^2.4.9",
"@types/tmp": "^0.2.6",
"@types/update-notifier": "^6.0.8",
- "app-root-path": "^3.1.0",
"cross-env": "^10.1.0",
"prettier": "^3.8.1",
"rollup": "^4.59.0",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 424722c3..0d4c2de7 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -86,9 +86,6 @@ importers:
'@types/update-notifier':
specifier: ^6.0.8
version: 6.0.8
- app-root-path:
- specifier: ^3.1.0
- version: 3.1.0
cross-env:
specifier: ^10.1.0
version: 10.1.0
@@ -805,10 +802,6 @@ packages:
resolution: {integrity: sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==}
engines: {node: '>=12'}
- resolution: {integrity: sha512-biN3PwB2gUtjaYy/isrU3aNWI5w+fAfvHkSvCKeQGxhmYpwKFUxudR3Yya+KqVRHBmEDYh+/lTozYCFbmzX4nA==}
- engines: {node: '>= 6.0.0'}
-
resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}
engines: {node: '>=12'}
@@ -2021,8 +2014,6 @@ snapshots:
-
diff --git a/rollup.config.js b/rollup.config.js
index d5fa2b75..bfba1f5f 100644
--- a/rollup.config.js
+++ b/rollup.config.js
@@ -1,6 +1,6 @@
import path from "path";
import fs from "fs";
-import appRootPath from "app-root-path";
+import { fileURLToPath } from "node:url";
import typescript from "rollup-plugin-typescript2";
import alias from "@rollup/plugin-alias";
import commonjs from "@rollup/plugin-commonjs";
@@ -18,6 +18,7 @@ if (process.platform === "darwin") {
}
const isProduction = process.env.NODE_ENV === "production";
+const projectDirectory = path.dirname(fileURLToPath(import.meta.url));
const devPlugins = !isProduction ? [pakeCliDevPlugin()] : [];
export default {
@@ -65,7 +66,7 @@ export default {
preventAssignment: true,
}),
alias({
- entries: [{ find: "@", replacement: path.join(appRootPath.path, "bin") }],
+ entries: [{ find: "@", replacement: path.join(projectDirectory, "bin") }],
}),
...devPlugins,
],
diff --git a/tests/index.js b/tests/index.js
index 09f08099..57eca8af 100644
--- a/tests/index.js
+++ b/tests/index.js
@@ -249,15 +249,16 @@ class PakeTestRunner {
// URL validation test
await this.runTest("URL Validation", () => {
- try {
- execSync(`node "${config.CLI_PATH}" "invalid-url" --name TestApp`, {
- encoding: "utf8",
- timeout: TIMEOUTS.QUICK,
- });
- return false; // Should have failed
- } catch (error) {
- return error.status !== 0;
- }
+ const result = spawnSync(
+ process.execPath,
+ [config.CLI_PATH, "", "--name", "TestApp", "--json"],
+ { encoding: "utf8", timeout: TIMEOUTS.QUICK },
+ );
+ return (
+ !result.error &&
+ result.status === 2 &&
+ JSON.parse(result.stdout).error?.code === "INVALID_INPUT"
+ );
});
// Number validation test
@@ -283,23 +284,6 @@ class PakeTestRunner {
const elapsed = Date.now() - start;
return elapsed < 5000;
});
-
- // Weekly URL accessibility test
- await this.runTest("Weekly URL Accessibility", () => {
- try {
- const testCommand = `node "${config.CLI_PATH}" ${TEST_URLS.WEEKLY} --name "URLTest" --debug`;
- execSync(`echo "n" | timeout 5s ${testCommand} || true`, {
- encoding: "utf8",
- timeout: 8000,
- });
- return true; // If we get here, URL was parsed successfully
- } catch (error) {
- return (
- !error.message.includes("Invalid URL") &&
- !error.message.includes("invalid")
- );
- }
- });
}
async runIntegrationTests() {
@@ -688,27 +672,32 @@ class PakeTestRunner {
}
async runLocalFileTest() {
- await this.runTest("Local File Build Handling", async () => {
- const testFile = path.join(config.PROJECT_ROOT, "test-local.html");
- fs.writeFileSync(
- testFile,
- "<html><body><h1>Hello Pake</h1></body></html>",
+ if (process.platform !== "darwin") {
+ console.log(
+ "Local artifact fixture skipped: currently uses macOS .app paths; staging is covered by Vitest.",
);
- this.trackTempFile(testFile);
-
- try {
- const command = `node "${config.CLI_PATH}" "${testFile}" --name "LocalApp" --debug`;
- // We just verify it accepts the local file path
- execSync(`echo "n" | timeout 5s ${command} || true`, {
- encoding: "utf8",
- timeout: 8000,
- });
+ return;
+ }
+ await this.runTest(
+ "Local File Build Isolation",
+ () => {
+ const result = spawnSync(
+ process.execPath,
+ [
+ path.join(
+ config.PROJECT_ROOT,
+ "tests/integration/build-workspace.mjs",
+ ),
+ ],
+ { cwd: config.PROJECT_ROOT, encoding: "utf8", timeout: 120000 },
+ );
+ if (result.error || result.status !== 0) {
+ throw result.error || new Error(result.stderr || result.stdout);
+ }
return true;
- } catch (error) {
- // Validation failure is what we want to catch (if it rejected local files)
- return !error.message.includes("Invalid URL");
- }
- });
+ },
+ 120000,
+ );
}
async runRealBuildTest() {
diff --git a/tests/integration/build-workspace.mjs b/tests/integration/build-workspace.mjs
new file mode 100644
index 00000000..32100db7
--- /dev/null
+++ b/tests/integration/build-workspace.mjs
@@ -0,0 +1,216 @@
+// Exercises the shipped CLI with a deterministic compiler stand-in. Native
+// compilation is verified separately; this checks actual staging and copying.
+import fs from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import assert from "node:assert/strict";
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+
+if (process.platform !== "darwin")
+ throw new Error("This artifact fixture uses macOS .app paths.");
+const exec = promisify(execFile);
+const repo = process.cwd();
+const root = await fs.mkdtemp(
+ path.join(os.tmpdir(), "pake-cli-workspace-test-"),
+);
+const pkg = path.join(root, "package");
+const cache = path.join(root, "cache");
+const buildScript = `
+const fs = require('node:fs');
+const path = require('node:path');
+const { spawn } = require('node:child_process');
+const config = JSON.parse(fs.readFileSync('src-tauri/.pake/tauri.conf.json'));
+const name = config.productName;
+const snapshot = {
+ name, directory: process.cwd(),
+ html: fs.readFileSync('dist/index.html', 'utf8'),
+ custom: fs.readFileSync('src-tauri/src/inject/custom.js', 'utf8'),
+};
+if (name === 'Fail') process.exit(9);
+if (name.startsWith('Cancel')) {
+ const writes = path.join(process.env.PAKE_FIXTURE_ROOT, name + '-writes');
+ const child = spawn(process.execPath, ['-e', 'process.on("SIGTERM",()=>{});setInterval(()=>require("fs").appendFileSync(process.argv[1],"x"),10)', writes], {stdio:'ignore'});
+ process.on('SIGTERM', () => {});
+ fs.writeFileSync(path.join(process.env.PAKE_FIXTURE_ROOT, name + '-ready.json'), JSON.stringify({directory:process.cwd(),pid:process.pid,child:child.pid}));
+ setInterval(() => {}, 10000);
+} else setTimeout(() => {
+ const arch = process.arch === 'arm64' ? 'aarch64' : 'x86_64';
+ const output = path.join(process.env.CARGO_TARGET_DIR, arch + '-apple-darwin', 'release', 'bundle', 'macos', name + '.app');
+ fs.mkdirSync(output, {recursive:true});
+ fs.writeFileSync(path.join(output, 'snapshot.json'), JSON.stringify(snapshot));
+}, 100);
+`;
+
+try {
+ await fs.mkdir(path.join(pkg, "dist"), { recursive: true });
+ await fs.copyFile(
+ process.env.PAKE_CLI_SOURCE || path.join(repo, "dist/cli.js"),
+ path.join(pkg, "dist/cli.js"),
+ );
+ const manifest = JSON.parse(
+ await fs.readFile(path.join(repo, "package.json"), "utf8"),
+ );
+ manifest.scripts.build = "node src-tauri/fixture.cjs";
+ await fs.writeFile(path.join(pkg, "package.json"), JSON.stringify(manifest));
+ await fs.cp(path.join(repo, "src-tauri"), path.join(pkg, "src-tauri"), {
+ recursive: true,
+ filter: (file) =>
+ !["target", ".pake", "gen", ".cargo"].includes(
+ path.relative(path.join(repo, "src-tauri"), file).split(path.sep)[0],
+ ),
+ });
+ await fs.writeFile(path.join(pkg, "src-tauri/fixture.cjs"), buildScript);
+ await fs.symlink(
+ path.join(repo, "node_modules"),
+ path.join(pkg, "node_modules"),
+ "dir",
+ );
+ const customTemplate = await fs.readFile(
+ path.join(pkg, "src-tauri/src/inject/custom.js"),
+ "utf8",
+ );
+ const sourceConfig = await fs.readFile(
+ path.join(pkg, "src-tauri/tauri.conf.json"),
+ "utf8",
+ );
+ async function build(name, signal) {
+ const input = path.join(root, name);
+ await fs.mkdir(input);
+ await fs.writeFile(path.join(input, "index.html"), name);
+ await fs.writeFile(
+ path.join(input, "custom.js"),
+ `window.fixture = ${JSON.stringify(name)};`,
+ );
+ const running = exec(
+ process.execPath,
+ [
+ path.join(pkg, "dist/cli.js"),
+ input,
+ "--name",
+ name,
+ "--targets",
+ "app",
+ "--json",
+ "--icon",
+ path.join(repo, "src-tauri/icons/icon.icns"),
+ "--inject",
+ path.join(input, "custom.js"),
+ ],
+ {
+ cwd: root,
+ env: {
+ ...process.env,
+ CI: "true",
+ CARGO_TARGET_DIR: cache,
+ PAKE_FIXTURE_ROOT: root,
+ },
+ timeout: 30_000,
+ },
+ );
+ if (signal) {
+ running.catch(() => {});
+ const ready = path.join(root, name + "-ready.json");
+ const started = Date.now();
+ for (;;) {
+ try {
+ await fs.access(ready);
+ break;
+ } catch {}
+ if (Date.now() - started > 20000)
+ throw new Error("Compiler fixture did not start.");
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+ // Wait until the descendant has installed its TERM handler and written.
+ const writes = path.join(root, name + "-writes");
+ for (;;) {
+ try {
+ await fs.access(writes);
+ break;
+ } catch {}
+ if (Date.now() - started > 20000)
+ throw new Error("Compiler descendant did not start.");
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+ running.child.kill(signal);
+ }
+ return running;
+ }
+ const outcomes = await Promise.all([build("Alpha"), build("Beta")]);
+ for (const [index, name] of ["Alpha", "Beta"].entries()) {
+ const result = JSON.parse(outcomes[index].stdout);
+ assert.equal(result.ok, true);
+ const snapshot = JSON.parse(
+ await fs.readFile(
+ path.join(root, `${name}.app`, "snapshot.json"),
+ "utf8",
+ ),
+ );
+ assert.equal(snapshot.html, name);
+ assert.match(snapshot.custom, new RegExp(name));
+ assert.notEqual(snapshot.directory, pkg);
+ await assert.rejects(fs.access(snapshot.directory));
+ }
+ await assert.rejects(build("Fail"), (error) => {
+ assert.equal(JSON.parse(error.stdout).ok, false);
+ assert.equal(error.code, 3);
+ return true;
+ });
+ const recovery = await build("Recovery");
+ assert.equal(JSON.parse(recovery.stdout).ok, true);
+ for (const [name, signal] of [
+ ["CancelInt", "SIGINT"],
+ ["CancelTerm", "SIGTERM"],
+ ]) {
+ await assert.rejects(build(name, signal), (error) => {
+ const result = JSON.parse(error.stdout);
+ assert.equal(result.ok, false);
+ assert.equal(result.error.code, "BUILD_FAILED");
+ assert.match(result.error.message, new RegExp(signal));
+ assert.equal(error.code, 3);
+ return true;
+ });
+ const ready = JSON.parse(
+ await fs.readFile(path.join(root, name + "-ready.json"), "utf8"),
+ );
+ await assert.rejects(fs.access(ready.directory));
+ await assert.rejects(fs.access(path.join(cache, ".pake-build.lock")));
+ const writes = path.join(root, name + "-writes");
+ const size = (await fs.stat(writes)).size;
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ assert.equal(
+ (await fs.stat(writes)).size,
+ size,
+ "Compiler must stop before cleanup finishes.",
+ );
+ assert.equal(JSON.parse((await build("After" + name)).stdout).ok, true);
+ }
+ assert.equal(
+ await fs.readFile(path.join(pkg, "src-tauri/src/inject/custom.js"), "utf8"),
+ customTemplate,
+ );
+ assert.equal(
+ await fs.readFile(path.join(pkg, "src-tauri/tauri.conf.json"), "utf8"),
+ sourceConfig,
+ );
+ assert.deepEqual(await fs.readdir(path.join(pkg, "dist")), ["cli.js"]);
+ await assert.rejects(fs.access(path.join(pkg, "src-tauri/.pake")));
+ await assert.rejects(fs.access(path.join(cache, ".pake-build.lock")));
+ console.log(
+ "PASS: concurrent inputs, shipped CLI artifacts, failed-build cleanup, SIGINT/SIGTERM descendant shutdown, next-build recovery, unchanged installation",
+ );
+} finally {
+ for (const name of ["CancelInt", "CancelTerm"]) {
+ try {
+ const ready = JSON.parse(
+ await fs.readFile(path.join(root, name + "-ready.json"), "utf8"),
+ );
+ for (const pid of [ready.pid, ready.child]) {
+ try {
+ process.kill(pid, "SIGKILL");
+ } catch {}
+ }
+ } catch {}
+ }
+ await fs.rm(root, { recursive: true, force: true });
+}
diff --git a/tests/unit/base-builder.test.ts b/tests/unit/base-builder.test.ts
index 380e64e8..4e4daf73 100644
--- a/tests/unit/base-builder.test.ts
+++ b/tests/unit/base-builder.test.ts
@@ -163,16 +163,20 @@ describe('BaseBuilder guards', () => {
it('uses official npm registry by default', () => {
const command = getInstallCommand('pnpm', false);
- expect(command).toContain('pnpm install');
- expect(command).not.toContain('registry.npmmirror.com');
+ expect(command).toEqual({ executable: 'pnpm', args: ['install'] });
});
it('uses npmmirror only when CN mirror is enabled', () => {
const command = getInstallCommand('npm', true);
- expect(command).toContain(
- 'npm install --registry=https://registry.npmmirror.com --legacy-peer-deps',
- );
+ expect(command).toEqual({
+ executable: 'npm',
+ args: [
+ 'install',
+ '--registry=https://registry.npmmirror.com',
+ '--legacy-peer-deps',
+ ],
+ });
});
it('uses pnpm when the installed major matches the pinned package manager', async () => {
@@ -302,12 +306,44 @@ describe('BaseBuilder guards', () => {
} as any);
const command = (builder as any).getBuildCommand('pnpm');
- const normalizedCommand = command.replace(/\\/g, '/');
+ const normalizedCommand = command.args.join(' ').replace(/\\/g, '/');
expect(normalizedCommand).toContain('src-tauri/.pake/tauri.conf.json');
- expect(command).toContain('--features cli-build');
+ expect(command.args).toContain('--features');
+ expect(
+ command.args.find((arg: string) => arg.startsWith('cli-build')),
+ ).toBeTruthy();
});
+ it.each(['npm', 'pnpm'])(
+ 'preserves build arguments for %s',
+ (packageManager) => {
+ const builder = new TestBuilder({ debug: true } as any);
+ const configPath = path.join(
+ 'config with spaces',
+ '$(printf untouched).json',
+ );
+ const command = (builder as any).buildBaseCommand(
+ packageManager,
+ configPath,
+ 'aarch64-apple-darwin',
+ );
+ expect(command.executable).toBe(packageManager);
+ expect(command.args.slice(0, packageManager === 'npm' ? 3 : 2)).toEqual(
+ packageManager === 'npm'
+ ? ['run', 'build:debug', '--']
+ : ['run', 'build:debug'],
+ );
+ const configIndex = command.args.indexOf('-c');
+ expect(command.args[configIndex + 1]).toBe(configPath);
+ expect(command.args.slice(configIndex + 2, configIndex + 5)).toEqual([
+ '--target',
+ 'aarch64-apple-darwin',
+ '--verbose',
+ ]);
+ },
+ );
+
it('copies Windows build artifacts from CARGO_TARGET_DIR when it is set', () => {
const cargoTargetDir = path.join(process.cwd(), '.short-cargo-target');
process.env.CARGO_TARGET_DIR = cargoTargetDir;
diff --git a/tests/unit/build-workspace.test.ts b/tests/unit/build-workspace.test.ts
new file mode 100644
index 00000000..80725d55
--- /dev/null
+++ b/tests/unit/build-workspace.test.ts
@@ -0,0 +1,181 @@
+import fs from 'fs-extra';
+import path from 'path';
+import os from 'os';
+import { afterEach, describe, expect, it } from 'vitest';
+import {
+ createBuildWorkspace,
+ acquireBuildCache,
+} from '@/utils/build-workspace';
+
+const directories: string[] = [];
+afterEach(async () => {
+ await Promise.all(
+ directories.splice(0).map((directory) => fs.remove(directory)),
+ );
+});
+
+async function fixture() {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'pake-workspace-test-'));
+ directories.push(root);
+ await fs.outputJSON(path.join(root, 'package.json'), { name: 'fixture' });
+ await fs.outputFile(
+ path.join(root, 'src-tauri', 'src', 'inject', 'custom.js'),
+ 'template',
+ );
+ await fs.outputFile(
+ path.join(root, 'src-tauri', '.pake', 'pake.json'),
+ 'previous user',
+ );
+ await fs.outputFile(
+ path.join(root, 'src-tauri', 'target', 'private'),
+ 'old cache',
+ );
+ await fs.outputFile(path.join(root, 'dist', 'cli.js'), 'cli');
+ await fs.outputFile(
+ path.join(root, 'dist', 'private.html'),
+ 'previous local input',
+ );
+ await fs.outputFile(
+ path.join(root, 'node_modules', 'dependency', 'index.js'),
+ 'dependency',
+ );
+ await fs.outputJSON(
+ path.join(root, 'node_modules', '@tauri-apps', 'cli', 'package.json'),
+ { name: '@tauri-apps/cli' },
+ );
+ await fs.outputFile(
+ path.join(root, 'node_modules', '@tauri-apps', 'cli', 'tauri.js'),
+ 'process.exit(process.argv[2] === "--version" ? 0 : 1);',
+ );
+ const launcher = path.join(
+ root,
+ 'node_modules',
+ '.bin',
+ process.platform === 'win32' ? 'tauri.cmd' : 'tauri',
+ );
+ await fs.outputFile(launcher, 'fixture');
+ await fs.chmod(launcher, 0o755);
+ return root;
+}
+
+describe('build workspace', () => {
+ it('isolates simultaneous build inputs without copying stale local content or cache', async () => {
+ const source = await fixture();
+ const roots = await Promise.all([
+ createBuildWorkspace(source),
+ createBuildWorkspace(source),
+ ]);
+ directories.push(...roots);
+ expect(roots[0]).not.toBe(roots[1]);
+ await fs.writeFile(
+ path.join(roots[0], 'src-tauri', 'src', 'inject', 'custom.js'),
+ 'first user',
+ );
+ for (const root of [source, roots[1]]) {
+ expect(
+ await fs.readFile(
+ path.join(root, 'src-tauri', 'src', 'inject', 'custom.js'),
+ 'utf8',
+ ),
+ ).toBe('template');
+ }
+ for (const root of roots) {
+ expect(await fs.pathExists(path.join(root, 'src-tauri', '.pake'))).toBe(
+ false,
+ );
+ expect(await fs.pathExists(path.join(root, 'src-tauri', 'target'))).toBe(
+ false,
+ );
+ expect(await fs.readdir(path.join(root, 'dist'))).toEqual(['cli.js']);
+ expect(await fs.realpath(path.join(root, 'node_modules'))).toBe(
+ await fs.realpath(path.join(source, 'node_modules')),
+ );
+ }
+ });
+
+ it('holds shared cache ownership until the previous build releases it', async () => {
+ const source = await fixture();
+ const target = path.join(source, 'cache');
+ const firstRelease = await acquireBuildCache(target);
+ let acquired = false;
+ const second = acquireBuildCache(target).then((release) => {
+ acquired = true;
+ return release;
+ });
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ expect(acquired).toBe(false);
+ await firstRelease();
+ const secondRelease = await second;
+ expect(acquired).toBe(true);
+ await secondRelease();
+ expect(await fs.pathExists(path.join(target, '.pake-build.lock'))).toBe(
+ false,
+ );
+ });
+
+ it('cleans a failed partial copy without returning an unusable workspace', async () => {
+ const source = await fixture();
+ await fs.remove(path.join(source, 'dist', 'cli.js'));
+ await expect(createBuildWorkspace(source)).rejects.toMatchObject({
+ code: 'ENOENT',
+ });
+ expect(
+ await fs.readFile(
+ path.join(source, 'src-tauri', 'src', 'inject', 'custom.js'),
+ 'utf8',
+ ),
+ ).toBe('template');
+ });
+
+ it('does not link incomplete dependencies that the install fallback would mutate', async () => {
+ const source = await fixture();
+ await fs.remove(path.join(source, 'node_modules', '@tauri-apps'));
+ const root = await createBuildWorkspace(source);
+ directories.push(root);
+ expect(await fs.pathExists(path.join(root, 'node_modules'))).toBe(false);
+ expect(
+ await fs.readFile(
+ path.join(source, 'node_modules', 'dependency', 'index.js'),
+ 'utf8',
+ ),
+ ).toBe('dependency');
+ });
+
+ it('does not link a manifest-only installation missing its CLI entry', async () => {
+ const source = await fixture();
+ await fs.remove(
+ path.join(source, 'node_modules', '@tauri-apps', 'cli', 'tauri.js'),
+ );
+ const root = await createBuildWorkspace(source);
+ directories.push(root);
+ expect(await fs.pathExists(path.join(root, 'node_modules'))).toBe(false);
+ expect(
+ await fs.pathExists(
+ path.join(source, 'node_modules', '@tauri-apps', 'cli', 'package.json'),
+ ),
+ ).toBe(true);
+ });
+
+ it('never removes an abandoned lock while another waiter could be acquiring it', async () => {
+ const source = await fixture();
+ const target = path.join(source, 'cache');
+ const lock = path.join(target, '.pake-build.lock');
+ // Obtain an actual exited PID rather than assume a large PID is absent.
+ const { execFileSync } = await import('child_process');
+ const owner = execFileSync(
+ process.execPath,
+ ['-e', 'process.stdout.write(String(process.pid))'],
+ { encoding: 'utf8' },
+ );
+ await fs.outputFile(lock, owner);
+ const results = await Promise.allSettled([
+ acquireBuildCache(target),
+ acquireBuildCache(target),
+ ]);
+ expect(results.map((result) => result.status)).toEqual([
+ 'rejected',
+ 'rejected',
+ ]);
+ expect(await fs.readFile(lock, 'utf8')).toBe(owner);
+ });
+});
diff --git a/tests/unit/icon.test.ts b/tests/unit/icon.test.ts
index e87dfc33..5a98b1e7 100644
--- a/tests/unit/icon.test.ts
+++ b/tests/unit/icon.test.ts
@@ -3,6 +3,7 @@ import os from 'os';
import path from 'path';
import { afterEach, describe, expect, it, vi } from 'vitest';
import sharp from 'sharp';
+import http from 'http';
const execaMock = vi.hoisted(() => vi.fn());
@@ -16,6 +17,30 @@ import { getIconSourcePriority } from '@/utils/icon-source';
const downloadedIconPaths: string[] = [];
const generatedIconDirs: string[] = [];
+it('keeps the download deadline active until the response body completes', async () => {
+ let bodyCompleted = false;
+ const server = http.createServer((_request, response) => {
+ response.writeHead(200, { 'content-type': 'image/png' });
+ response.flushHeaders();
+ const timer = setTimeout(() => {
+ bodyCompleted = true;
+ response.end('x');
+ }, 500);
+ response.on('close', () => clearTimeout(timer));
+ });
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ try {
+ const port = (server.address() as import('net').AddressInfo).port;
+ expect(
+ await downloadIcon(`http://127.0.0.1:${port}/icon`, false, 50),
+ ).toBeNull();
+ expect(bodyCompleted).toBe(false);
+ } finally {
+ server.closeAllConnections();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ }
+});
+
afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
diff --git a/tests/unit/linux-arch-package.test.ts b/tests/unit/linux-arch-package.test.ts
new file mode 100644
index 00000000..c9bcaa39
--- /dev/null
+++ b/tests/unit/linux-arch-package.test.ts
@@ -0,0 +1,61 @@
+import path from 'path';
+import fsExtra from 'fs-extra';
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/utils/dir', () => ({
+ npmDirectory: process.cwd(),
+ tauriConfigDirectory: path.join(process.cwd(), 'src-tauri', '.pake'),
+}));
+vi.mock('@/utils/shell', () => ({ shellExec: vi.fn() }));
+
+import LinuxBuilder from '@/builders/LinuxBuilder';
+import { shellExec } from '@/utils/shell';
+import { DEFAULT_PAKE_OPTIONS } from '@/defaults';
+
+describe('Arch repacking workspace', () => {
+ it('keeps concurrent extraction trees separate and cleans both after failure', async () => {
+ const directories: string[] = [];
+ let releaseExtractions: () => void = () => {};
+ const bothStarted = new Promise<void>((resolve) => {
+ releaseExtractions = resolve;
+ });
+ vi.mocked(shellExec).mockImplementation(async (command) => {
+ if (command.executable === 'ar') {
+ directories.push(command.cwd!);
+ expect(command.args[0]).toBe('x');
+ if (directories.length === 2) releaseExtractions();
+ await bothStarted;
+ throw new Error('fixture extraction failed');
+ }
+ return 0;
+ });
+ const makeBuilder = () => {
+ const builder = new LinuxBuilder({
+ ...DEFAULT_PAKE_OPTIONS,
+ name: 'demo',
+ targets: 'zst',
+ } as any);
+ vi.spyOn(builder as any, 'ensureArchPackagingTools').mockResolvedValue(
+ undefined,
+ );
+ return builder;
+ };
+ const results = await Promise.allSettled([
+ (makeBuilder() as any).createArchPackageFromDeb({
+ removeSourceDeb: false,
+ }),
+ (makeBuilder() as any).createArchPackageFromDeb({
+ removeSourceDeb: false,
+ }),
+ ]);
+ expect(results.map((result) => result.status)).toEqual([
+ 'rejected',
+ 'rejected',
+ ]);
+ expect(directories).toHaveLength(2);
+ expect(directories[0]).not.toBe(directories[1]);
+ for (const directory of directories) {
+ expect(await fsExtra.pathExists(path.dirname(directory))).toBe(false);
+ }
+ });
+});
diff --git a/tests/unit/local-staging.test.ts b/tests/unit/local-staging.test.ts
index 4da2de95..5d67c3c5 100644
--- a/tests/unit/local-staging.test.ts
+++ b/tests/unit/local-staging.test.ts
@@ -15,6 +15,7 @@ vi.mock('@/utils/dir', async () => {
const base = nodePath.join(nodeOs.tmpdir(), `pake-staging-${process.pid}`);
return {
npmDirectory: nodePath.join(base, 'pkg'),
+ packageDirectory: nodePath.join(base, 'pkg'),
tauriConfigDirectory: nodePath.join(base, 'pkg', 'src-tauri', '.pake'),
};
});
diff --git a/tests/unit/no-bundle.test.ts b/tests/unit/no-bundle.test.ts
index 1db01d8f..5c2023a6 100644
--- a/tests/unit/no-bundle.test.ts
+++ b/tests/unit/no-bundle.test.ts
@@ -16,13 +16,13 @@ const makeBuilder = (bundle: boolean) =>
describe('LinuxBuilder --no-bundle', () => {
it('appends --no-bundle and skips --bundles when bundle is false', () => {
- const cmd = (makeBuilder(false) as any).getBuildCommand('pnpm');
+ const cmd = (makeBuilder(false) as any).getBuildCommand('pnpm').args;
expect(cmd).toContain('--no-bundle');
expect(cmd).not.toContain('--bundles');
});
it('does not append --no-bundle when bundle is true (default)', () => {
- const cmd = (makeBuilder(true) as any).getBuildCommand('pnpm');
+ const cmd = (makeBuilder(true) as any).getBuildCommand('pnpm').args;
expect(cmd).not.toContain('--no-bundle');
});
});
diff --git a/tests/unit/rust.test.ts b/tests/unit/rust.test.ts
new file mode 100644
index 00000000..636f74a2
--- /dev/null
+++ b/tests/unit/rust.test.ts
@@ -0,0 +1,50 @@
+import path from 'path';
+import fsExtra from 'fs-extra';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const spinner = vi.hoisted(() => ({ succeed: vi.fn(), fail: vi.fn() }));
+vi.mock('@/utils/info', () => ({ getSpinner: () => spinner }));
+vi.mock('@/utils/platform', () => ({ IS_WIN: false }));
+vi.mock('@/utils/mirror', () => ({ isCnMirrorEnabled: () => false }));
+vi.mock('@/utils/shell', () => ({ shellExec: vi.fn() }));
+
+import { shellExec } from '@/utils/shell';
+import { installRust } from '@/helpers/rust';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+});
+
+describe('Rust installation failure cleanup', () => {
+ it.each(['curl', 'sh'])(
+ 'propagates %s failure so the CLI can release its build workspace',
+ async (failingExecutable) => {
+ const failure = new Error('fixture installer failure');
+ const exitSpy = vi
+ .spyOn(process, 'exit')
+ .mockImplementation(() => undefined as never);
+ const consoleSpy = vi
+ .spyOn(console, 'error')
+ .mockImplementation(() => {});
+ let scriptPath = '';
+ vi.mocked(shellExec).mockImplementation(async (command) => {
+ if (command.executable === 'curl') {
+ scriptPath = command.args[command.args.indexOf('-o') + 1];
+ await fsExtra.writeFile(scriptPath, '# fixture only, never executed');
+ }
+ if (command.executable === failingExecutable) throw failure;
+ return 0;
+ });
+
+ await expect(installRust()).rejects.toBe(failure);
+
+ expect(exitSpy).not.toHaveBeenCalled();
+ expect(consoleSpy).not.toHaveBeenCalled();
+ expect(spinner.fail).toHaveBeenCalledOnce();
+ expect(spinner.succeed).not.toHaveBeenCalled();
+ expect(scriptPath).not.toBe('');
+ expect(await fsExtra.pathExists(path.dirname(scriptPath))).toBe(false);
+ },
+ );
+});
diff --git a/tests/unit/shell.test.ts b/tests/unit/shell.test.ts
new file mode 100644
index 00000000..01cbc1fc
--- /dev/null
+++ b/tests/unit/shell.test.ts
@@ -0,0 +1,140 @@
+import os from 'os';
+import path from 'path';
+import fs from 'fs/promises';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/utils/dir', () => ({ npmDirectory: process.cwd() }));
+vi.mock('@/utils/output', () => ({ isMachineMode: vi.fn(() => false) }));
+vi.mock('execa', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('execa')>();
+ return { ...actual, execa: vi.fn(actual.execa) };
+});
+
+import { execa } from 'execa';
+import { isMachineMode } from '@/utils/output';
+import { shellExec } from '@/utils/shell';
+import { beginBuildCancellation } from '@/utils/build-workspace';
+
+const tempDirs: string[] = [];
+afterEach(async () => {
+ vi.clearAllMocks();
+ vi.mocked(isMachineMode).mockReturnValue(false);
+ await Promise.all(
+ tempDirs
+ .splice(0)
+ .map((dir) => fs.rm(dir, { recursive: true, force: true })),
+ );
+});
+
+describe('structured process execution', () => {
+ it('passes shell syntax and spaces literally in arguments and cwd', async () => {
+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'pake-exec-'));
+ tempDirs.push(tempDir);
+ const cwd = path.join(tempDir, 'space $(printf substituted)');
+ await fs.mkdir(cwd);
+ const resultPath = path.join(cwd, 'result.json');
+ const values = [
+ 'two words',
+ '$(printf PAKE_SHOULD_STAY_LITERAL)',
+ '`printf substituted`',
+ 'a"b',
+ 'a&b',
+ ];
+ await shellExec(
+ {
+ executable: process.execPath,
+ args: [
+ '-e',
+ 'require("fs").writeFileSync(process.argv[1], JSON.stringify({args:process.argv.slice(2),cwd:process.cwd(),env:process.env.PAKE_EXEC_TEST}))',
+ resultPath,
+ ...values,
+ ],
+ cwd,
+ },
+ 5000,
+ { PAKE_EXEC_TEST: 'value with spaces' },
+ );
+
+ const result = JSON.parse(await fs.readFile(resultPath, 'utf8'));
+ expect(result).toEqual({
+ args: values,
+ cwd: await fs.realpath(cwd),
+ env: 'value with spaces',
+ });
+ expect(vi.mocked(execa).mock.calls[0][2]).toMatchObject({ shell: false });
+ });
+
+ it('reserves stdout for the JSON result in machine mode', async () => {
+ vi.mocked(isMachineMode).mockReturnValue(true);
+ await shellExec({ executable: process.execPath, args: ['-e', ''] });
+ expect(vi.mocked(execa).mock.calls[0][2]).toMatchObject({
+ cwd: process.cwd(),
+ stdin: 'inherit',
+ stdout: process.stderr,
+ stderr: 'inherit',
+ });
+ });
+
+ it('reports a real nonzero process exit', async () => {
+ await expect(
+ shellExec({
+ executable: process.execPath,
+ args: ['-e', 'process.exit(7)'],
+ }),
+ ).rejects.toThrow('Exit code: 7');
+ });
+
+ it('terminates a process when its timeout expires', async () => {
+ await expect(
+ shellExec(
+ {
+ executable: process.execPath,
+ args: ['-e', 'setTimeout(() => {}, 10000)'],
+ },
+ 50,
+ ),
+ ).rejects.toThrow('Command timed out after 50ms');
+ });
+
+ it.skipIf(process.platform === 'win32')(
+ 'stops compiler descendants before rejecting a timed-out build',
+ async () => {
+ const directory = await fs.mkdtemp(
+ path.join(os.tmpdir(), 'pake-timeout-tree-'),
+ );
+ tempDirs.push(directory);
+ const writes = path.join(directory, 'writes');
+ const childPidPath = path.join(directory, 'child-pid');
+ const endCancellation = beginBuildCancellation();
+ const script = `
+ const {spawn} = require('child_process');
+ const fs = require('fs');
+ const child = spawn(process.execPath, ['-e', 'process.on("SIGTERM",()=>{});setInterval(()=>require("fs").appendFileSync(process.argv[1],"x"),10)', process.argv[1]], {stdio:'ignore'});
+ fs.writeFileSync(process.argv[2], String(child.pid));
+ setInterval(()=>{},10000);
+ `;
+ try {
+ await expect(
+ shellExec(
+ {
+ executable: process.execPath,
+ args: ['-e', script, writes, childPidPath],
+ },
+ 500,
+ ),
+ ).rejects.toThrow('Command timed out after 500ms');
+ const size = (await fs.stat(writes)).size;
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ expect((await fs.stat(writes)).size).toBe(size);
+ } finally {
+ endCancellation();
+ try {
+ process.kill(
+ Number(await fs.readFile(childPidPath, 'utf8')),
+ 'SIGKILL',
+ );
+ } catch {}
+ }
+ },
+ );
+});
diff --git a/tests/unit/tauri-cli.test.ts b/tests/unit/tauri-cli.test.ts
new file mode 100644
index 00000000..a07c8a00
--- /dev/null
+++ b/tests/unit/tauri-cli.test.ts
@@ -0,0 +1,71 @@
+import os from 'os';
+import path from 'path';
+import fs from 'fs-extra';
+import { afterEach, describe, expect, it } from 'vitest';
+import { hasReadyTauriCli } from '@/utils/tauri-cli';
+
+const directories: string[] = [];
+afterEach(async () => {
+ await Promise.all(
+ directories.splice(0).map((directory) => fs.remove(directory)),
+ );
+});
+
+async function fixture() {
+ const directory = await fs.mkdtemp(
+ path.join(os.tmpdir(), 'pake-tauri-ready-'),
+ );
+ directories.push(directory);
+ const cli = path.join(directory, 'node_modules', '@tauri-apps', 'cli');
+ const entry = path.join(cli, 'tauri.js');
+ const launcher = path.join(
+ directory,
+ 'node_modules',
+ '.bin',
+ process.platform === 'win32' ? 'tauri.cmd' : 'tauri',
+ );
+ await fs.outputJSON(path.join(cli, 'package.json'), {
+ name: '@tauri-apps/cli',
+ });
+ await fs.outputFile(
+ entry,
+ 'process.exit(process.argv[2] === "--version" ? 0 : 1);',
+ );
+ await fs.outputFile(launcher, 'fixture');
+ await fs.chmod(launcher, 0o755);
+ return { directory, entry, launcher };
+}
+
+describe('Tauri CLI readiness', () => {
+ it('accepts a runnable local CLI', async () => {
+ const { directory } = await fixture();
+ expect(await hasReadyTauriCli(directory)).toBe(true);
+ });
+
+ it('rejects a manifest without its CLI entry', async () => {
+ const { directory, entry } = await fixture();
+ await fs.remove(entry);
+ expect(await hasReadyTauriCli(directory)).toBe(false);
+ });
+
+ it('rejects a missing native binding even when the entry exists', async () => {
+ const { directory, entry } = await fixture();
+ await fs.writeFile(entry, 'require("./missing-native-binding.node");');
+ expect(await hasReadyTauriCli(directory)).toBe(false);
+ });
+
+ it('rejects a missing package-script launcher', async () => {
+ const { directory, launcher } = await fixture();
+ await fs.remove(launcher);
+ expect(await hasReadyTauriCli(directory)).toBe(false);
+ });
+
+ it.skipIf(process.platform === 'win32')(
+ 'rejects a non-executable launcher',
+ async () => {
+ const { directory, launcher } = await fixture();
+ await fs.chmod(launcher, 0o644);
+ expect(await hasReadyTauriCli(directory)).toBe(false);
+ },
+ );
+});