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.

refactor: eliminate remaining panics and narrow platform types

Tw936efe733b683c
diff --git a/bin/helpers/merge.ts b/bin/helpers/merge.ts
index cf42a959..fa650378 100644
--- a/bin/helpers/merge.ts
+++ b/bin/helpers/merge.ts
@@ -12,12 +12,28 @@ import {
import {
PakeAppOptions,
PakeTauriConfig,
- PlatformMap,
- PlatformSpecific,
+ SupportedPlatform,
+ TauriPlatform,
WindowConfig,
} from '@/types';
import { tauriConfigDirectory, npmDirectory } from '@/utils/dir';
+type PlatformIconInfo = {
+ fileExt: string;
+ path: string;
+ defaultIcon: string;
+ message: string;
+};
+
+function asSupportedPlatform(platform: NodeJS.Platform): SupportedPlatform {
+ if (platform !== 'win32' && platform !== 'darwin' && platform !== 'linux') {
+ throw new Error(
+ `Pake only supports win32, darwin, and linux; detected '${platform}'.`,
+ );
+ }
+ return platform;
+}
+
async function copyTemplateConfigs(): Promise<void> {
const srcTauriDir = path.join(npmDirectory, 'src-tauri');
await fsExtra.ensureDir(tauriConfigDirectory);
@@ -86,7 +102,12 @@ async function mergeLinuxConfig(
tauriConf: PakeTauriConfig,
linuxBinaryName: string,
): Promise<void> {
- const linuxBundle = tauriConf.bundle.linux!;
+ const linuxBundle = tauriConf.bundle.linux;
+ if (!linuxBundle) {
+ throw new Error(
+ 'Linux bundle configuration is missing from tauri.linux.conf.json; cannot build Linux target.',
+ );
+ }
delete linuxBundle.deb.files;
const linuxName = generateLinuxPackageName(name);
@@ -151,10 +172,10 @@ async function mergeIcons(
options: PakeAppOptions,
name: string,
tauriConf: PakeTauriConfig,
- platform: string,
+ platform: SupportedPlatform,
safeAppName: string,
): Promise<void> {
- const platformIconMap: PlatformMap = {
+ const platformIconMap: Record<SupportedPlatform, PlatformIconInfo> = {
win32: {
fileExt: '.ico',
path: `png/${safeAppName}_256.ico`,
@@ -332,9 +353,9 @@ ${entitlementEntries.join('\n')}
async function writeAllConfigs(
tauriConf: PakeTauriConfig,
- platform: string,
+ platform: SupportedPlatform,
): Promise<void> {
- const platformConfigPaths: PlatformMap = {
+ const platformConfigPaths: Record<SupportedPlatform, string> = {
win32: 'tauri.windows.conf.json',
darwin: 'tauri.macos.conf.json',
linux: 'tauri.linux.conf.json',
@@ -401,7 +422,7 @@ export async function mergeConfig(
microphone,
} = options;
- const { platform } = process;
+ const platform = asSupportedPlatform(process.platform);
const platformHideOnClose = hideOnClose ?? platform === 'darwin';
const tauriConfWindowOptions: Partial<WindowConfig> = {
@@ -442,19 +463,23 @@ export async function mergeConfig(
: `pake-${generateIdentifierSafeName(name)}`;
if (platform === 'win32') {
- tauriConf.bundle.windows!.wix.language[0] = installerLanguage;
+ const windowsBundle = tauriConf.bundle.windows;
+ if (!windowsBundle) {
+ throw new Error(
+ 'Windows bundle configuration is missing from tauri.windows.conf.json; cannot build Windows target.',
+ );
+ }
+ windowsBundle.wix.language[0] = installerLanguage;
}
await handleLocalFile(url, useLocalFile, tauriConf);
- const platformMap: PlatformMap = {
+ const platformMap: Record<SupportedPlatform, TauriPlatform> = {
win32: 'windows',
linux: 'linux',
darwin: 'macos',
};
- const currentPlatform = platformMap[platform] as keyof PlatformSpecific<
- string | boolean
- >;
+ const currentPlatform = platformMap[platform];
if (userAgent.length > 0) {
tauriConf.pake.user_agent[currentPlatform] = userAgent;
diff --git a/bin/options/index.ts b/bin/options/index.ts
index 634b735b..43618aae 100644
--- a/bin/options/index.ts
+++ b/bin/options/index.ts
@@ -10,7 +10,7 @@ import {
resolveIdentifier,
} from '@/utils/info';
import { generateLinuxPackageName } from '@/utils/name';
-import { PakeAppOptions, PakeCliOptions, PlatformMap } from '@/types';
+import { PakeAppOptions, PakeCliOptions } from '@/types';
function resolveAppName(name: string, platform: NodeJS.Platform): string {
const domain = getDomain(name) || 'pake';
@@ -34,11 +34,10 @@ function resolveLocalAppName(
}
function isValidName(name: string, platform: NodeJS.Platform): boolean {
- const platformRegexMapping: PlatformMap = {
- linux: /^[a-z0-9\u4e00-\u9fff][a-z0-9\u4e00-\u9fff-]*$/,
- default: /^[a-zA-Z0-9\u4e00-\u9fff][a-zA-Z0-9\u4e00-\u9fff- ]*$/,
- };
- const reg = platformRegexMapping[platform] || platformRegexMapping.default;
+ const reg =
+ platform === 'linux'
+ ? /^[a-z0-9\u4e00-\u9fff][a-z0-9\u4e00-\u9fff-]*$/
+ : /^[a-zA-Z0-9\u4e00-\u9fff][a-zA-Z0-9\u4e00-\u9fff- ]*$/;
return !!name && reg.test(name);
}
diff --git a/bin/types.ts b/bin/types.ts
index 8314fffc..9c947774 100644
--- a/bin/types.ts
+++ b/bin/types.ts
@@ -1,6 +1,5 @@
-export interface PlatformMap {
- [key: string]: any;
-}
+export type SupportedPlatform = 'win32' | 'darwin' | 'linux';
+export type TauriPlatform = 'windows' | 'macos' | 'linux';
export interface PakeCliOptions {
// Application name
diff --git a/dist/cli.js b/dist/cli.js
index 1ad841d5..19c21cdd 100644
--- a/dist/cli.js
+++ b/dist/cli.js
@@ -480,6 +480,12 @@ function generateIdentifierSafeName(name) {
return cleaned;
}
+function asSupportedPlatform(platform) {
+ if (platform !== 'win32' && platform !== 'darwin' && platform !== 'linux') {
+ throw new Error(`Pake only supports win32, darwin, and linux; detected '${platform}'.`);
+ }
+ return platform;
+}
async function copyTemplateConfigs() {
const srcTauriDir = path.join(npmDirectory, 'src-tauri');
await fsExtra.ensureDir(tauriConfigDirectory);
@@ -526,6 +532,9 @@ async function handleLocalFile(url, useLocalFile, tauriConf) {
}
async function mergeLinuxConfig(options, name, tauriConf, linuxBinaryName) {
const linuxBundle = tauriConf.bundle.linux;
+ if (!linuxBundle) {
+ throw new Error('Linux bundle configuration is missing from tauri.linux.conf.json; cannot build Linux target.');
+ }
delete linuxBundle.deb.files;
const linuxName = generateLinuxPackageName(name);
const desktopFileName = `com.pake.${linuxName}.desktop`;
@@ -727,7 +736,7 @@ async function writeAllConfigs(tauriConf, platform) {
async function mergeConfig(url, options, tauriConf) {
await copyTemplateConfigs();
const { width, height, fullscreen, maximize, hideTitleBar, alwaysOnTop, appVersion, darkMode, disabledWebShortcuts, activationShortcut, userAgent, showSystemTray, useLocalFile, identifier, name = 'pake-app', resizable = true, installerLanguage, hideOnClose, incognito, title, wasm, enableDragDrop, startToTray, forceInternalNavigation, internalUrlRegex, zoom, minWidth, minHeight, ignoreCertificateErrors, newWindow, camera, microphone, } = options;
- const { platform } = process;
+ const platform = asSupportedPlatform(process.platform);
const platformHideOnClose = hideOnClose ?? platform === 'darwin';
const tauriConfWindowOptions = {
width,
@@ -764,7 +773,11 @@ async function mergeConfig(url, options, tauriConf) {
? linuxBinaryName
: `pake-${generateIdentifierSafeName(name)}`;
if (platform === 'win32') {
- tauriConf.bundle.windows.wix.language[0] = installerLanguage;
+ const windowsBundle = tauriConf.bundle.windows;
+ if (!windowsBundle) {
+ throw new Error('Windows bundle configuration is missing from tauri.windows.conf.json; cannot build Windows target.');
+ }
+ windowsBundle.wix.language[0] = installerLanguage;
}
await handleLocalFile(url, useLocalFile, tauriConf);
const platformMap = {
@@ -2192,11 +2205,9 @@ function resolveLocalAppName(filePath, platform) {
return normalized || 'pake-app';
}
function isValidName(name, platform) {
- const platformRegexMapping = {
- linux: /^[a-z0-9\u4e00-\u9fff][a-z0-9\u4e00-\u9fff-]*$/,
- default: /^[a-zA-Z0-9\u4e00-\u9fff][a-zA-Z0-9\u4e00-\u9fff- ]*$/,
- };
- const reg = platformRegexMapping[platform] || platformRegexMapping.default;
+ const reg = platform === 'linux'
+ ? /^[a-z0-9\u4e00-\u9fff][a-z0-9\u4e00-\u9fff-]*$/
+ : /^[a-zA-Z0-9\u4e00-\u9fff][a-zA-Z0-9\u4e00-\u9fff- ]*$/;
return !!name && reg.test(name);
}
async function handleOptions(options, url) {
diff --git a/src-tauri/src/app/setup.rs b/src-tauri/src/app/setup.rs
index 485ed940..ff6e5e6a 100644
--- a/src-tauri/src/app/setup.rs
+++ b/src-tauri/src/app/setup.rs
@@ -39,7 +39,7 @@ pub fn set_system_tray(
app.app_handle().remove_tray_by_id("pake-tray");
- let tray = TrayIconBuilder::new()
+ let mut tray_builder = TrayIconBuilder::new()
.menu(&menu)
.on_menu_event(move |app, event| match event.id().as_ref() {
"new_window" => {
@@ -85,20 +85,23 @@ pub fn set_system_tray(
}
}
_ => {}
- })
- .icon(if tray_icon_path.is_empty() {
- app.default_window_icon()
- .unwrap_or_else(|| panic!("Failed to get default window icon"))
- .clone()
- } else {
- tauri::image::Image::from_path(tray_icon_path).unwrap_or_else(|_| {
- // If custom tray icon fails to load, fallback to default
- app.default_window_icon()
- .unwrap_or_else(|| panic!("Failed to get default window icon"))
- .clone()
- })
- })
- .build(app)?;
+ });
+
+ let resolved_icon = if tray_icon_path.is_empty() {
+ app.default_window_icon().cloned()
+ } else {
+ tauri::image::Image::from_path(tray_icon_path)
+ .ok()
+ .or_else(|| app.default_window_icon().cloned())
+ };
+
+ if let Some(icon) = resolved_icon {
+ tray_builder = tray_builder.icon(icon);
+ } else {
+ eprintln!("[Pake] No tray icon available; tray will build without an icon.");
+ }
+
+ let tray = tray_builder.build(app)?;
tray.set_icon_as_template(false)?;
Ok(())
diff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rs
index f5c1a6cd..4cdb48df 100644
--- a/src-tauri/src/app/window.rs
+++ b/src-tauri/src/app/window.rs
@@ -1,6 +1,10 @@
use crate::app::config::PakeConfig;
use crate::util::get_data_dir;
-use std::{path::PathBuf, str::FromStr, sync::Mutex};
+use std::{
+ path::PathBuf,
+ str::FromStr,
+ sync::atomic::{AtomicU32, Ordering},
+};
use tauri::{
webview::{NewWindowFeatures, NewWindowResponse},
AppHandle, Config, Manager, Url, WebviewUrl, WebviewWindow, WebviewWindowBuilder,
@@ -28,7 +32,7 @@ fn build_proxy_browser_arg(url: &Url) -> Option<String> {
pub struct MultiWindowState {
pub pake_config: PakeConfig,
pub tauri_config: Config,
- next_window_index: Mutex<u32>,
+ next_window_index: AtomicU32,
}
impl MultiWindowState {
@@ -36,14 +40,13 @@ impl MultiWindowState {
Self {
pake_config,
tauri_config,
- next_window_index: Mutex::new(0),
+ next_window_index: AtomicU32::new(0),
}
}
fn next_window_label(&self) -> String {
- let mut index = self.next_window_index.lock().unwrap();
- *index += 1;
- format!("pake-{}", *index)
+ let index = self.next_window_index.fetch_add(1, Ordering::Relaxed) + 1;
+ format!("pake-{index}")
}
}
@@ -124,7 +127,18 @@ fn build_window_with_label(
.first()
.expect("At least one window configuration is required");
let url = match window_config.url_type.as_str() {
- "web" => WebviewUrl::App(window_config.url.parse().unwrap()),
+ "web" => {
+ let parsed = window_config.url.parse().map_err(|err| {
+ tauri::Error::Io(std::io::Error::new(
+ std::io::ErrorKind::InvalidInput,
+ format!(
+ "Invalid 'web' url '{}' in pake.json: {err}",
+ window_config.url
+ ),
+ ))
+ })?;
+ WebviewUrl::App(parsed)
+ }
"local" => WebviewUrl::App(PathBuf::from(&window_config.url)),
other => {
return Err(tauri::Error::Io(std::io::Error::new(