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: harden macOS new-window handling and build flow

Tw93ef22aaa71225
diff --git a/.gitignore b/.gitignore
index c92961d1..d02ef8b6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -47,3 +47,10 @@ yarn-error.log*
# Generated code review graph files
code-review-graph.mmd
code-review-graph.json
+
+# Local test artifacts
+test-local.html
+src-tauri/icons/testapp.icns
+src-tauri/icons/localapp.icns
+src-tauri/icons/urltest.icns
+src-tauri/icons/githubmultiarch.icns
diff --git a/bin/builders/BaseBuilder.ts b/bin/builders/BaseBuilder.ts
index 1a48f504..909c1390 100644
--- a/bin/builders/BaseBuilder.ts
+++ b/bin/builders/BaseBuilder.ts
@@ -27,13 +27,22 @@ export default abstract class BaseBuilder {
}
private getBuildEnvironment() {
- return IS_MAC
- ? {
- CFLAGS: '-fno-modules',
- CXXFLAGS: '-fno-modules',
- MACOSX_DEPLOYMENT_TARGET: '14.0',
- }
- : undefined;
+ if (!IS_MAC) {
+ return undefined;
+ }
+
+ const currentPath = process.env.PATH || '';
+ const systemToolsPath = '/usr/bin';
+ const buildPath = currentPath.startsWith(`${systemToolsPath}:`)
+ ? currentPath
+ : `${systemToolsPath}:${currentPath}`;
+
+ return {
+ CFLAGS: '-fno-modules',
+ CXXFLAGS: '-fno-modules',
+ MACOSX_DEPLOYMENT_TARGET: '14.0',
+ PATH: buildPath,
+ };
}
private getInstallTimeout(): number {
@@ -71,6 +80,28 @@ export default abstract class BaseBuilder {
}
}
+ private async copyFileWithSamePathGuard(
+ sourcePath: string,
+ destinationPath: string,
+ ): Promise<void> {
+ if (path.resolve(sourcePath) === path.resolve(destinationPath)) {
+ return;
+ }
+
+ try {
+ await fsExtra.copy(sourcePath, destinationPath, { overwrite: true });
+ } catch (error) {
+ if (
+ error instanceof Error &&
+ error.message.includes('Source and destination must not be the same')
+ ) {
+ return;
+ }
+
+ throw error;
+ }
+ }
+
async prepare() {
const tauriSrcPath = path.join(npmDirectory, 'src-tauri');
const tauriTargetPath = path.join(tauriSrcPath, 'target');
@@ -130,7 +161,7 @@ export default abstract class BaseBuilder {
`✺ Located in China, using ${packageManager}/rsProxy CN mirror.`,
);
const projectCnConf = path.join(tauriSrcPath, 'rust_proxy.toml');
- await fsExtra.copy(projectCnConf, projectConf);
+ await this.copyFileWithSamePathGuard(projectCnConf, projectConf);
await shellExec(
`cd "${npmDirectory}" && ${packageManager} install${registryOption}${peerDepsOption}`,
timeout,
@@ -163,7 +194,7 @@ export default abstract class BaseBuilder {
try {
const projectCnConf = path.join(tauriSrcPath, 'rust_proxy.toml');
- await fsExtra.copy(projectCnConf, projectConf);
+ await this.copyFileWithSamePathGuard(projectCnConf, projectConf);
await shellExec(
`cd "${npmDirectory}" && ${packageManager} install${registryOption}${peerDepsOption}`,
timeout,
@@ -356,7 +387,6 @@ export default abstract class BaseBuilder {
);
}
- // 架构映射配置
protected static readonly ARCH_MAPPINGS: Record<
string,
Record<string, string>
@@ -376,16 +406,12 @@ export default abstract class BaseBuilder {
},
};
- // 架构名称映射(用于文件名生成)
protected static readonly ARCH_DISPLAY_NAMES: Record<string, string> = {
arm64: 'aarch64',
x64: 'x64',
universal: 'universal',
};
- /**
- * 解析目标架构
- */
protected resolveTargetArch(requestedArch?: string): string {
if (requestedArch === 'auto' || !requestedArch) {
return process.arch;
@@ -393,9 +419,6 @@ export default abstract class BaseBuilder {
return requestedArch;
}
- /**
- * 获取Tauri构建目标
- */
protected getTauriTarget(
arch: string,
platform: NodeJS.Platform = process.platform,
@@ -405,16 +428,10 @@ export default abstract class BaseBuilder {
return platformMappings[arch] || null;
}
- /**
- * 获取架构显示名称(用于文件名)
- */
protected getArchDisplayName(arch: string): string {
return BaseBuilder.ARCH_DISPLAY_NAMES[arch] || arch;
}
- /**
- * 构建基础构建命令
- */
protected buildBaseCommand(
packageManager: string,
configPath: string,
@@ -440,9 +457,6 @@ export default abstract class BaseBuilder {
return fullCommand;
}
- /**
- * 获取构建特性列表
- */
protected getBuildFeatures(): string[] {
const features = ['cli-build'];
diff --git a/bin/helpers/merge.ts b/bin/helpers/merge.ts
index 8f23eeaf..54479910 100644
--- a/bin/helpers/merge.ts
+++ b/bin/helpers/merge.ts
@@ -295,7 +295,20 @@ Terminal=false
// Avoid copying if source and destination are the same
const absoluteDestPath = path.resolve(iconPath);
if (resolvedIconPath !== absoluteDestPath) {
- await fsExtra.copy(resolvedIconPath, iconPath);
+ try {
+ await fsExtra.copy(resolvedIconPath, iconPath);
+ } catch (error) {
+ if (
+ !(
+ error instanceof Error &&
+ error.message.includes(
+ 'Source and destination must not be the same',
+ )
+ )
+ ) {
+ throw error;
+ }
+ }
}
}
diff --git a/default_app_list.json b/default_app_list.json
index 57cac8af..7ff73ea2 100644
--- a/default_app_list.json
+++ b/default_app_list.json
@@ -45,8 +45,7 @@
"name": "chatgpt",
"title": "ChatGPT",
"name_zh": "ChatGPT",
- "url": "https://chatgpt.com/",
- "new_window": true
+ "url": "https://chatgpt.com/"
},
{
"name": "flomo",
diff --git a/dist/cli.js b/dist/cli.js
index 395cca3e..73066f66 100644
--- a/dist/cli.js
+++ b/dist/cli.js
@@ -22,7 +22,7 @@ import * as psl from 'psl';
import { InvalidArgumentError, program as program$1, Option } from 'commander';
var name = "pake-cli";
-var version = "3.10.1";
+var version = "3.11.2";
var description = "🤱🏻 Turn any webpage into a desktop app with one command. 🤱🏻 一键打包网页生成轻量桌面应用。";
var engines = {
node: ">=18.0.0"
@@ -682,7 +682,15 @@ Terminal=false
// Avoid copying if source and destination are the same
const absoluteDestPath = path.resolve(iconPath);
if (resolvedIconPath !== absoluteDestPath) {
- await fsExtra.copy(resolvedIconPath, iconPath);
+ try {
+ await fsExtra.copy(resolvedIconPath, iconPath);
+ }
+ catch (error) {
+ if (!(error instanceof Error &&
+ error.message.includes('Source and destination must not be the same'))) {
+ throw error;
+ }
+ }
}
}
if (updateIconPath) {
@@ -796,13 +804,20 @@ class BaseBuilder {
this.options = options;
}
getBuildEnvironment() {
- return IS_MAC
- ? {
- CFLAGS: '-fno-modules',
- CXXFLAGS: '-fno-modules',
- MACOSX_DEPLOYMENT_TARGET: '14.0',
- }
- : undefined;
+ if (!IS_MAC) {
+ return undefined;
+ }
+ const currentPath = process.env.PATH || '';
+ const systemToolsPath = '/usr/bin';
+ const buildPath = currentPath.startsWith(`${systemToolsPath}:`)
+ ? currentPath
+ : `${systemToolsPath}:${currentPath}`;
+ return {
+ CFLAGS: '-fno-modules',
+ CXXFLAGS: '-fno-modules',
+ MACOSX_DEPLOYMENT_TARGET: '14.0',
+ PATH: buildPath,
+ };
}
getInstallTimeout() {
// Windows needs more time due to native compilation and antivirus scanning
@@ -834,6 +849,21 @@ class BaseBuilder {
}
}
}
+ async copyFileWithSamePathGuard(sourcePath, destinationPath) {
+ if (path.resolve(sourcePath) === path.resolve(destinationPath)) {
+ return;
+ }
+ try {
+ await fsExtra.copy(sourcePath, destinationPath, { overwrite: true });
+ }
+ catch (error) {
+ if (error instanceof Error &&
+ error.message.includes('Source and destination must not be the same')) {
+ return;
+ }
+ throw error;
+ }
+ }
async prepare() {
const tauriSrcPath = path.join(npmDirectory, 'src-tauri');
const tauriTargetPath = path.join(tauriSrcPath, 'target');
@@ -879,7 +909,7 @@ class BaseBuilder {
if (isChina) {
logger.info(`✺ Located in China, using ${packageManager}/rsProxy CN mirror.`);
const projectCnConf = path.join(tauriSrcPath, 'rust_proxy.toml');
- await fsExtra.copy(projectCnConf, projectConf);
+ await this.copyFileWithSamePathGuard(projectCnConf, projectConf);
await shellExec(`cd "${npmDirectory}" && ${packageManager} install${registryOption}${peerDepsOption}`, timeout, { ...buildEnv, CI: 'true' });
}
else {
@@ -898,7 +928,7 @@ class BaseBuilder {
usedMirror = true;
try {
const projectCnConf = path.join(tauriSrcPath, 'rust_proxy.toml');
- await fsExtra.copy(projectCnConf, projectConf);
+ await this.copyFileWithSamePathGuard(projectCnConf, projectConf);
await shellExec(`cd "${npmDirectory}" && ${packageManager} install${registryOption}${peerDepsOption}`, timeout, { ...buildEnv, CI: 'true' });
retrySpinner.succeed(chalk.green('Package installed with CN mirror!'));
}
@@ -1034,33 +1064,21 @@ class BaseBuilder {
message.includes('appimage tool failed') ||
message.includes('strip tool'));
}
- /**
- * 解析目标架构
- */
resolveTargetArch(requestedArch) {
if (requestedArch === 'auto' || !requestedArch) {
return process.arch;
}
return requestedArch;
}
- /**
- * 获取Tauri构建目标
- */
getTauriTarget(arch, platform = process.platform) {
const platformMappings = BaseBuilder.ARCH_MAPPINGS[platform];
if (!platformMappings)
return null;
return platformMappings[arch] || null;
}
- /**
- * 获取架构显示名称(用于文件名)
- */
getArchDisplayName(arch) {
return BaseBuilder.ARCH_DISPLAY_NAMES[arch] || arch;
}
- /**
- * 构建基础构建命令
- */
buildBaseCommand(packageManager, configPath, target) {
const baseCommand = this.options.debug
? `${packageManager} run build:debug`
@@ -1077,9 +1095,6 @@ class BaseBuilder {
}
return fullCommand;
}
- /**
- * 获取构建特性列表
- */
getBuildFeatures() {
const features = ['cli-build'];
// Add macos-proxy feature for modern macOS (Darwin 23+ = macOS 14+)
@@ -1188,7 +1203,6 @@ class BaseBuilder {
}
}
BaseBuilder.packageManagerCache = null;
-// 架构映射配置
BaseBuilder.ARCH_MAPPINGS = {
darwin: {
arm64: 'aarch64-apple-darwin',
@@ -1204,7 +1218,6 @@ BaseBuilder.ARCH_MAPPINGS = {
x64: 'x86_64-unknown-linux-gnu',
},
};
-// 架构名称映射(用于文件名生成)
BaseBuilder.ARCH_DISPLAY_NAMES = {
arm64: 'aarch64',
x64: 'x64',
diff --git a/package.json b/package.json
index 82bdc73b..89c226c3 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "pake-cli",
- "version": "3.11.0",
+ "version": "3.11.2",
"description": "🤱🏻 Turn any webpage into a desktop app with one command. 🤱🏻 一键打包网页生成轻量桌面应用。",
"engines": {
"node": ">=18.0.0"
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 0f4a838e..9f55af92 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -2564,7 +2564,7 @@ dependencies = [
[[package]]
name = "pake"
-version = "3.10.1"
+version = "3.11.2"
dependencies = [
"serde",
"serde_json",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 9cea02a5..845fac1a 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "pake"
-version = "3.11.0"
+version = "3.11.2"
description = "🤱🏻 Turn any webpage into a desktop app with Rust."
authors = ["Tw93"]
license = "MIT"
diff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rs
index a0c7bcac..2c344f5c 100644
--- a/src-tauri/src/app/window.rs
+++ b/src-tauri/src/app/window.rs
@@ -79,7 +79,7 @@ fn open_requested_window(
tauri_config,
WindowBuildOptions {
label: &label,
- url: WebviewUrl::External("about:blank".parse().unwrap()),
+ url: WebviewUrl::External(target_url.clone()),
visible: true,
new_window_features: Some(features),
},
@@ -369,50 +369,29 @@ fn build_window(
}
if let Some(features) = new_window_features {
- window_builder = window_builder.window_features(features).focused(true);
- }
-
- // Allow navigation to OAuth/authentication domains
- window_builder = window_builder.on_navigation(|url| {
- let url_str = url.as_str();
-
- // Always allow same-origin navigation
- if url_str.starts_with("http://localhost") || url_str.starts_with("http://127.0.0.1") {
- return true;
- }
+ // macOS popup webviews must reuse the opener webview configuration.
+ #[cfg(target_os = "macos")]
+ {
+ if let Some(position) = features.position() {
+ window_builder = window_builder.position(position.x, position.y);
+ }
- // Check for OAuth/authentication domains
- let auth_patterns = [
- "accounts.google.com",
- "login.microsoftonline.com",
- "github.com/login",
- "appleid.apple.com",
- "facebook.com",
- "twitter.com",
- ];
-
- let auth_paths = ["/oauth/", "/auth/", "/authorize", "/login"];
-
- // Allow if matches auth patterns
- for pattern in &auth_patterns {
- if url_str.contains(pattern) {
- #[cfg(debug_assertions)]
- println!("Allowing OAuth navigation to: {}", url_str);
- return true;
+ if let Some(size) = features.size() {
+ window_builder = window_builder.inner_size(size.width, size.height);
}
+
+ window_builder = window_builder
+ .with_webview_configuration(features.opener().target_configuration.clone())
+ .focused(true);
}
- for path in &auth_paths {
- if url_str.contains(path) {
- #[cfg(debug_assertions)]
- println!("Allowing auth path navigation to: {}", url_str);
- return true;
- }
+ #[cfg(not(target_os = "macos"))]
+ {
+ window_builder = window_builder.window_features(features).focused(true);
}
+ }
- // Allow all other navigation by default
- true
- });
+ window_builder = window_builder.on_navigation(|_| true);
window_builder.build()
}
diff --git a/src-tauri/src/inject/event.js b/src-tauri/src/inject/event.js
index 5e0faf54..0f57103f 100644
--- a/src-tauri/src/inject/event.js
+++ b/src-tauri/src/inject/event.js
@@ -534,7 +534,7 @@ document.addEventListener("DOMContentLoaded", () => {
return;
}
- // Handle _blank links: same domain navigates in-app, cross-domain opens new window
+ // Handle _blank links: internal links stay in-app, external links open in the system browser
if (target === "_blank") {
if (forceInternalNavigation) {
e.preventDefault();
@@ -550,13 +550,7 @@ document.addEventListener("DOMContentLoaded", () => {
e.preventDefault();
e.stopImmediatePropagation();
- const newWindow = originalWindowOpen.call(
- window,
- absoluteUrl,
- "_blank",
- "width=1200,height=800,scrollbars=yes,resizable=yes",
- );
- if (!newWindow) handleExternalLink(absoluteUrl);
+ handleExternalLink(absoluteUrl);
return;
}
@@ -587,7 +581,7 @@ document.addEventListener("DOMContentLoaded", () => {
return;
}
- // Handle regular links: internal URLs allow normal navigation, external opens new window
+ // Handle regular links: internal URLs allow normal navigation, external links open in the system browser
if (!target || target === "_self") {
// Optimization: Allow previewable media to be handled by the app/browser directly
// This fixes issues where CDN links are treated as external
@@ -602,13 +596,7 @@ document.addEventListener("DOMContentLoaded", () => {
e.preventDefault();
e.stopImmediatePropagation();
- const newWindow = originalWindowOpen.call(
- window,
- absoluteUrl,
- "_blank",
- "width=1200,height=800,scrollbars=yes,resizable=yes",
- );
- if (!newWindow) handleExternalLink(absoluteUrl);
+ handleExternalLink(absoluteUrl);
}
}
}
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index 5dbef7ff..d3c7d3d7 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -1,7 +1,7 @@
{
"productName": "Weekly",
"identifier": "com.pake.weekly",
- "version": "3.10.1",
+ "version": "3.11.2",
"app": {
"withGlobalTauri": true,
"trayIcon": {
diff --git a/tests/index.js b/tests/index.js
index e12c690a..6cf3dde0 100644
--- a/tests/index.js
+++ b/tests/index.js
@@ -1381,6 +1381,7 @@ class PakeTestRunner {
const iconsDir = path.join(config.PROJECT_ROOT, "src-tauri/icons");
const testNames = [
"urltest",
+ "testapp",
"githubapp",
"githubmultiarch",
"githubconfigtest",
@@ -1469,6 +1470,11 @@ class PakeTestRunner {
if (fs.existsSync(pakeDir)) {
fs.rmSync(pakeDir, { recursive: true, force: true });
}
+
+ const localTestFile = path.join(config.PROJECT_ROOT, "test-local.html");
+ if (fs.existsSync(localTestFile)) {
+ fs.rmSync(localTestFile, { force: true });
+ }
} catch (e) {
console.warn(" [Warn] Cleanup warning:", e.message);
}
diff --git a/tests/unit/base-builder.test.ts b/tests/unit/base-builder.test.ts
new file mode 100644
index 00000000..61d50293
--- /dev/null
+++ b/tests/unit/base-builder.test.ts
@@ -0,0 +1,73 @@
+import path from 'path';
+import fsExtra from 'fs-extra';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/utils/dir', () => ({
+ npmDirectory: process.cwd(),
+ tauriConfigDirectory: path.join(process.cwd(), 'src-tauri', '.pake'),
+}));
+
+import BaseBuilder from '@/builders/BaseBuilder';
+
+class TestBuilder extends BaseBuilder {
+ getFileName(): string {
+ return 'test-app';
+ }
+}
+
+describe('BaseBuilder guards', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('prepends /usr/bin to PATH for macOS build environment', () => {
+ const builder = new TestBuilder({} as any);
+ const originalPath = process.env.PATH;
+ process.env.PATH = '/opt/homebrew/bin:/usr/local/bin';
+
+ try {
+ const env = (builder as any).getBuildEnvironment();
+
+ if (process.platform === 'darwin') {
+ expect(env).toBeDefined();
+ expect(env.PATH.startsWith('/usr/bin:')).toBe(true);
+ } else {
+ expect(env).toBeUndefined();
+ }
+ } finally {
+ process.env.PATH = originalPath;
+ }
+ });
+
+ it('skips copy when source and destination are the same path', async () => {
+ const builder = new TestBuilder({} as any);
+ const copySpy = vi
+ .spyOn(fsExtra, 'copy')
+ .mockResolvedValue(undefined as any);
+
+ await expect(
+ (builder as any).copyFileWithSamePathGuard('/tmp/same', '/tmp/same'),
+ ).resolves.toBeUndefined();
+ expect(copySpy).not.toHaveBeenCalled();
+ });
+
+ it('suppresses same-path fs-extra copy errors', async () => {
+ const builder = new TestBuilder({} as any);
+ vi.spyOn(fsExtra, 'copy').mockRejectedValue(
+ new Error('Source and destination must not be the same.'),
+ );
+
+ await expect(
+ (builder as any).copyFileWithSamePathGuard('/tmp/a', '/tmp/b'),
+ ).resolves.toBeUndefined();
+ });
+
+ it('rethrows non-same-path copy errors', async () => {
+ const builder = new TestBuilder({} as any);
+ vi.spyOn(fsExtra, 'copy').mockRejectedValue(new Error('permission denied'));
+
+ await expect(
+ (builder as any).copyFileWithSamePathGuard('/tmp/a', '/tmp/b'),
+ ).rejects.toThrow('permission denied');
+ });
+});