Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.
Rust chatgptclaudeclidesktopdesktop-appelectron-alternativegeminilinuxmacosnativefierno-electronrusttauriweb-to-desktopwebsite-to-appwebviewwindowsyoutube
refactor: architecture cleanup across CLI and Rust layers
Tw936f04d8ff9eee
diff --git a/bin/builders/BaseBuilder.ts b/bin/builders/BaseBuilder.tsindex 909c1390..1a48ce22 100644--- a/bin/builders/BaseBuilder.ts+++ b/bin/builders/BaseBuilder.ts@@ -125,7 +125,7 @@ export default abstract class BaseBuilder {await installRust();} else {logger.error('✕ Rust required to package your webapp.');- process.exit(0);+ process.exit(1);}}@@ -454,6 +454,11 @@ export default abstract class BaseBuilder {fullCommand += ' --verbose';}+ const features = this.getBuildFeatures();+ if (features.length > 0) {+ fullCommand += ` --features ${features.join(',')}`;+ }+return fullCommand;}@@ -487,12 +492,6 @@ export default abstract class BaseBuilder {fullCommand += ' --bundles app';}- // Add features- const features = this.getBuildFeatures();- if (features.length > 0) {- fullCommand += ` --features ${features.join(',')}`;- }-return fullCommand;}diff --git a/bin/builders/LinuxBuilder.ts b/bin/builders/LinuxBuilder.tsindex eceb906f..41d13f04 100644--- a/bin/builders/LinuxBuilder.ts+++ b/bin/builders/LinuxBuilder.ts@@ -88,11 +88,6 @@ export default class LinuxBuilder extends BaseBuilder {buildTarget,);- const features = this.getBuildFeatures();- if (features.length > 0) {- fullCommand += ` --features ${features.join(',')}`;- }-if (this.currentBuildType) {fullCommand += ` --bundles ${this.currentBuildType}`;}diff --git a/bin/builders/MacBuilder.ts b/bin/builders/MacBuilder.tsindex 1fb2611f..ebf061d4 100644--- a/bin/builders/MacBuilder.ts+++ b/bin/builders/MacBuilder.ts@@ -68,18 +68,7 @@ export default class MacBuilder extends BaseBuilder {throw new Error(`Unsupported architecture: ${actualArch} for macOS`);}- let fullCommand = this.buildBaseCommand(- packageManager,- configPath,- buildTarget,- );-- const features = this.getBuildFeatures();- if (features.length > 0) {- fullCommand += ` --features ${features.join(',')}`;- }-- return fullCommand;+ return this.buildBaseCommand(packageManager, configPath, buildTarget);}protected getBasePath(): string {diff --git a/bin/builders/WinBuilder.ts b/bin/builders/WinBuilder.tsindex 5d3b8e72..4a3ffc80 100644--- a/bin/builders/WinBuilder.ts+++ b/bin/builders/WinBuilder.ts@@ -33,18 +33,7 @@ export default class WinBuilder extends BaseBuilder {);}- let fullCommand = this.buildBaseCommand(- packageManager,- configPath,- buildTarget,- );-- const features = this.getBuildFeatures();- if (features.length > 0) {- fullCommand += ` --features ${features.join(',')}`;- }-- return fullCommand;+ return this.buildBaseCommand(packageManager, configPath, buildTarget);}protected getBasePath(): string {diff --git a/bin/code-review-graph.ts b/bin/code-review-graph.tsdeleted file mode 100644index fb4f091b..00000000--- a/bin/code-review-graph.ts+++ /dev/null@@ -1,404 +0,0 @@-#!/usr/bin/env node--import { Command } from 'commander';-import { execSync } from 'child_process';-import * as fs from 'fs';-import * as path from 'path';--interface Contributor {- name: string;- email: string;- commits: number;- prsOpened: number;- prsMerged: number;- reviewsGiven: number;- reviewsReceived: number;- firstCommit: string;- lastCommit: string;- filesChanged: Set<string>;-}--interface PREvent {- number: number;- title: string;- author: { login: string };- state: string;- createdAt: string;- mergedAt?: string;- mergedBy?: { login: string };-}--interface ReviewGraph {- contributors: Map<string, Contributor>;- prs: PREvent[];- reviewRelations: Map<string, Map<string, number>>;- timeRange: { start: string; end: string };-}--class CodeReviewGraph {- private graph: ReviewGraph;-- constructor() {- this.graph = {- contributors: new Map(),- prs: [],- reviewRelations: new Map(),- timeRange: { start: '', end: '' },- };- }-- async build(): Promise<void> {- console.log('Analyzing repository data...\n');-- await this.analyzeCommits();- await this.analyzePRs();- this.analyzeReviewRelations();-- return;- }-- private async analyzeCommits(): Promise<void> {- try {- // Commands are hardcoded internal commands, not user input- const logOutput = execSync(- 'git log --format="%H|%an|%ae|%ad|%s" --date=short -500',- { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'ignore'] },- );-- const lines = logOutput.trim().split('\n');-- for (const line of lines) {- const parts = line.split('|');- if (parts.length < 5) continue;-- const [, name, email, date] = parts;-- if (!this.graph.contributors.has(email)) {- this.graph.contributors.set(email, {- name,- email,- commits: 0,- prsOpened: 0,- prsMerged: 0,- reviewsGiven: 0,- reviewsReceived: 0,- firstCommit: date,- lastCommit: date,- filesChanged: new Set(),- });- }-- const contributor = this.graph.contributors.get(email)!;- contributor.commits++;- contributor.lastCommit = date;-- if (!this.graph.timeRange.start || date < this.graph.timeRange.start) {- this.graph.timeRange.start = date;- }- if (!this.graph.timeRange.end || date > this.graph.timeRange.end) {- this.graph.timeRange.end = date;- }- }- } catch (error) {- console.warn('Could not analyze commits:', (error as Error).message);- }- }-- private async analyzePRs(): Promise<void> {- try {- const prOutput = execSync(- 'gh pr list --state all --limit 100 --json number,title,author,state,mergedAt,createdAt,mergedBy 2>/dev/null || echo "[]"',- { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'ignore'] },- );-- const prs = JSON.parse(prOutput.trim() || '[]') as PREvent[];- this.graph.prs = prs;-- for (const pr of prs) {- const authorEmail = this.findEmailByUsername(pr.author.login);-- if (authorEmail && this.graph.contributors.has(authorEmail)) {- const contributor = this.graph.contributors.get(authorEmail)!;- contributor.prsOpened++;- if (pr.state === 'MERGED') {- contributor.prsMerged++;- }- }-- if (pr.mergedBy?.login) {- const mergerEmail = this.findEmailByUsername(pr.mergedBy.login);- if (mergerEmail && this.graph.contributors.has(mergerEmail)) {- const merger = this.graph.contributors.get(mergerEmail)!;- merger.reviewsGiven++;- }- }- }- } catch (error) {- console.warn('Could not analyze PRs:', (error as Error).message);- }- }-- private findEmailByUsername(username: string): string | null {- const usernameLower = username.toLowerCase();- for (const [email, contributor] of this.graph.contributors) {- if (- contributor.name.toLowerCase().includes(usernameLower) ||- email.toLowerCase().includes(usernameLower)- ) {- return email;- }- }- return null;- }-- private analyzeReviewRelations(): void {- for (const pr of this.graph.prs) {- if (pr.mergedBy?.login && pr.author.login !== pr.mergedBy.login) {- const authorKey = pr.author.login;- const mergerKey = pr.mergedBy.login;-- if (!this.graph.reviewRelations.has(mergerKey)) {- this.graph.reviewRelations.set(mergerKey, new Map());- }-- const relations = this.graph.reviewRelations.get(mergerKey)!;- relations.set(authorKey, (relations.get(authorKey) || 0) + 1);- }- }- }-- generateMermaidGraph(): string {- const lines: string[] = [- '%% Code Review Graph for Pake',- '%% Generated automatically - do not edit manually',- '',- 'flowchart TB',- ' subgraph Contributors["Top Contributors"]',- ];-- const sortedContributors = Array.from(this.graph.contributors.values())- .sort((a, b) => b.commits - a.commits)- .slice(0, 15);-- const nodeMap = new Map<string, string>();- let idx = 0;-- for (const c of sortedContributors) {- const nodeId = `C${idx}`;- nodeMap.set(c.email, nodeId);-- const prBadge = c.prsMerged > 0 ? ` PRs:${c.prsMerged}` : '';- const label = `${c.name}(${c.commits})${prBadge}`;-- lines.push(` ${nodeId}["${label}"]`);- idx++;- }-- lines.push(' end');- lines.push('');-- const addedEdges = new Set<string>();- for (const [reviewer, relations] of this.graph.reviewRelations) {- // reviewer is already a string (the login), not an object- const reviewerEmail = this.findEmailByUsername(reviewer);- if (!reviewerEmail || !nodeMap.has(reviewerEmail)) continue;-- const reviewerNode = nodeMap.get(reviewerEmail)!;-- for (const [author, count] of relations) {- // author is already a string (the login)- const authorEmail = this.findEmailByUsername(author);- if (!authorEmail || !nodeMap.has(authorEmail)) continue;-- const authorNode = nodeMap.get(authorEmail)!;- const edgeKey = `${reviewerNode}-${authorNode}`;-- if (!addedEdges.has(edgeKey)) {- lines.push(` ${reviewerNode} -.->|"reviews"| ${authorNode}`);- addedEdges.add(edgeKey);- }- }- }-- lines.push('');- lines.push(' subgraph Recent_Merges["Recent Merged PRs"]');-- const mergedPRs = this.graph.prs- .filter((pr) => pr.state === 'MERGED')- .slice(0, 8);-- for (let i = 0; i < mergedPRs.length; i++) {- const pr = mergedPRs[i];- const prNode = `PR${i}`;- const title =- pr.title.length > 30 ? pr.title.substring(0, 30) + '...' : pr.title;- lines.push(` ${prNode}["#${pr.number}: ${title}"]`);- }-- lines.push(' end');- lines.push('');-- lines.push(' subgraph Stats["Statistics"]');- lines.push(- ` TotalContributors["Total Contributors: ${this.graph.contributors.size}"]`,- );- lines.push(- ` TotalPRs["Total PRs Analyzed: ${this.graph.prs.length}"]`,- );- lines.push(- ` MergedPRs["Merged PRs: ${this.graph.prs.filter((p) => p.state === 'MERGED').length}"]`,- );- lines.push(- ` TimeRange["Period: ${this.graph.timeRange.start} to ${this.graph.timeRange.end}"]`,- );- lines.push(' end');-- lines.push('');- lines.push(' %% Styling');- lines.push(- ' classDef contributor fill:#e1f5fe,stroke:#01579b,stroke-width:2px',- );- lines.push(- ' classDef reviewer fill:#fff3e0,stroke:#e65100,stroke-width:2px',- );- lines.push(' classDef pr fill:#e8f5e9,stroke:#2e7d32,stroke-width:1px');- lines.push(- ' classDef stats fill:#f3e5f5,stroke:#6a1b9a,stroke-width:1px',- );-- for (let i = 0; i < idx; i++) {- lines.push(` class C${i} contributor`);- }- for (let i = 0; i < mergedPRs.length; i++) {- lines.push(` class PR${i} pr`);- }- lines.push(- ' class TotalContributors,TotalPRs,MergedPRs,TimeRange stats',- );-- return lines.join('\n');- }-- generateJSON(): object {- const contributors = Array.from(this.graph.contributors.values())- .map((c) => ({- ...c,- filesChanged: Array.from(c.filesChanged),- }))- .sort((a, b) => b.commits - a.commits);-- return {- metadata: {- generatedAt: new Date().toISOString(),- repository: 'tw93/Pake',- timeRange: this.graph.timeRange,- },- summary: {- totalContributors: this.graph.contributors.size,- totalPRs: this.graph.prs.length,- mergedPRs: this.graph.prs.filter((p) => p.state === 'MERGED').length,- closedPRs: this.graph.prs.filter((p) => p.state === 'CLOSED').length,- openPRs: this.graph.prs.filter((p) => p.state === 'OPEN').length,- },- contributors: contributors.slice(0, 20),- recentPRs: this.graph.prs.slice(0, 20),- reviewRelations: Object.fromEntries(- Array.from(this.graph.reviewRelations.entries()).map(([k, v]) => [- k,- Object.fromEntries(v),- ]),- ),- };- }-- printSummary(): void {- console.log(- '\n===============================================================',- );- console.log(- ' Code Review Graph Summary ',- );- console.log(- '===============================================================\n',- );-- console.log(- `Time Range: ${this.graph.timeRange.start} to ${this.graph.timeRange.end}`,- );- console.log(`Total Contributors: ${this.graph.contributors.size}`);- console.log(`Total PRs Analyzed: ${this.graph.prs.length}`);- console.log(- ` Merged: ${this.graph.prs.filter((p) => p.state === 'MERGED').length}`,- );- console.log(- ` Closed: ${this.graph.prs.filter((p) => p.state === 'CLOSED').length}`,- );- console.log(- ` Open: ${this.graph.prs.filter((p) => p.state === 'OPEN').length}\n`,- );-- console.log('Top Contributors by Commits:');- const sorted = Array.from(this.graph.contributors.values())- .sort((a, b) => b.commits - a.commits)- .slice(0, 10);-- for (let i = 0; i < sorted.length; i++) {- const c = sorted[i];- const rank = i === 0 ? '1.' : i === 1 ? '2.' : i === 2 ? '3.' : ' ';- const prInfo = c.prsMerged > 0 ? ` (PRs merged: ${c.prsMerged})` : '';- console.log(` ${rank} ${c.name}: ${c.commits} commits${prInfo}`);- }-- if (this.graph.reviewRelations.size > 0) {- console.log('\nReview Relationships (Merger -> Author):');- for (const [reviewer, relations] of this.graph.reviewRelations) {- const relationsStr = Array.from(relations.entries())- .map(([author, count]) => `${author}(${count})`)- .join(', ');- console.log(` ${reviewer} -> ${relationsStr}`);- }- }-- console.log('\n');- }-}--const program = new Command();--program- .name('code-review-graph')- .description('Generate code review graph for Pake project')- .version('1.0.0')- .option('-o, --output <path>', 'Output file path', 'code-review-graph.mmd')- .option('-f, --format <format>', 'Output format (mermaid|json)', 'mermaid')- .option('-s, --stdout', 'Print to stdout instead of file', false)- .action(async (options) => {- const graph = new CodeReviewGraph();- await graph.build();-- graph.printSummary();-- let output: string;- if (options.format === 'json') {- output = JSON.stringify(graph.generateJSON(), null, 2);- } else {- output = graph.generateMermaidGraph();- }-- if (options.stdout) {- console.log(output);- } else {- const outputPath = path.resolve(options.output);- fs.writeFileSync(outputPath, output, 'utf-8');- console.log(`Graph saved to: ${outputPath}`);-- if (options.format === 'mermaid') {- console.log('\nTo view this graph:');- console.log(' 1. Use GitHub markdown (paste into .md file)');- console.log(' 2. Use VS Code with Mermaid extension');- console.log(' 3. Visit https://mermaid.live/ and paste the content');- }- }- });--program.parse();diff --git a/bin/helpers/cli-program.ts b/bin/helpers/cli-program.tsindex a43773bc..e5a748fd 100644--- a/bin/helpers/cli-program.ts+++ b/bin/helpers/cli-program.ts@@ -1,10 +1,7 @@import chalk from 'chalk';import { program, Option } from 'commander';import packageJson from '../../package.json';-import {- DEFAULT_PAKE_OPTIONS as DEFAULT,- DEFAULT_PAKE_OPTIONS,-} from '../defaults';+import { DEFAULT_PAKE_OPTIONS as DEFAULT } from '../defaults';import { validateNumberInput, validateUrlInput } from '../utils/validate';export function getCliProgram() {@@ -72,7 +69,7 @@ ${green('|_| \\__,_|_|\\_\\___| can turn any webpage into a desktop app with'--proxy-url <url>','Proxy URL for all network requests (http://, https://, socks5://)',)- .default(DEFAULT_PAKE_OPTIONS.proxyUrl)+ .default(DEFAULT.proxyUrl).hideHelp(),).addOption(@@ -116,7 +113,7 @@ ${green('|_| \\__,_|_|\\_\\___| can turn any webpage into a desktop app with).addOption(new Option('--activation-shortcut <string>', 'Shortcut key to active App')- .default(DEFAULT_PAKE_OPTIONS.activationShortcut)+ .default(DEFAULT.activationShortcut).hideHelp(),).addOption(@@ -251,10 +248,13 @@ ${green('|_| \\__,_|_|\\_\\___| can turn any webpage into a desktop app with.default(DEFAULT.newWindow).hideHelp(),)- .option(- '--install',- 'Auto-install app to /Applications (macOS) after build and remove local bundle',- DEFAULT.install,+ .addOption(+ new Option(+ '--install',+ 'Auto-install app to /Applications (macOS) after build and remove local bundle',+ )+ .default(DEFAULT.install)+ .hideHelp(),).addOption(new Option('--camera', 'Request camera permission on macOS')diff --git a/bin/helpers/merge.ts b/bin/helpers/merge.tsindex 54479910..a667e354 100644--- a/bin/helpers/merge.ts+++ b/bin/helpers/merge.ts@@ -12,16 +12,10 @@ import {import { PakeAppOptions, PlatformMap, WindowConfig } from '@/types';import { tauriConfigDirectory, npmDirectory } from '@/utils/dir';-export async function mergeConfig(- url: string,- options: PakeAppOptions,- tauriConf: any,-) {- // Ensure .pake directory exists and copy source templates if needed+async function copyTemplateConfigs(): Promise<void> {const srcTauriDir = path.join(npmDirectory, 'src-tauri');await fsExtra.ensureDir(tauriConfigDirectory);- // Copy source config files to .pake directory (as templates)const sourceFiles = ['tauri.conf.json','tauri.macos.conf.json',@@ -34,7 +28,6 @@ export async function mergeConfig(sourceFiles.map(async (file) => {const sourcePath = path.join(srcTauriDir, file);const destPath = path.join(tauriConfigDirectory, file);-if ((await fsExtra.pathExists(sourcePath)) &&!(await fsExtra.pathExists(destPath))@@ -43,100 +36,19 @@ export async function mergeConfig(}}),);- const {- width,- height,- fullscreen,- maximize,- hideTitleBar,- alwaysOnTop,- appVersion,- darkMode,- disabledWebShortcuts,- activationShortcut,- userAgent,- showSystemTray,- systemTrayIcon,- useLocalFile,- identifier,- name = 'pake-app',- resizable = true,- inject,- proxyUrl,- installerLanguage,- hideOnClose,- incognito,- title,- wasm,- enableDragDrop,- multiInstance,- multiWindow,- startToTray,- forceInternalNavigation,- internalUrlRegex,- zoom,- minWidth,- minHeight,- ignoreCertificateErrors,- newWindow,- camera,- microphone,- } = options;-- const { platform } = process;-- const platformHideOnClose = hideOnClose ?? platform === 'darwin';-- const tauriConfWindowOptions: Partial<WindowConfig> = {- width,- height,- fullscreen,- maximize,- resizable,- hide_title_bar: hideTitleBar,- activation_shortcut: activationShortcut,- always_on_top: alwaysOnTop,- dark_mode: darkMode,- disabled_web_shortcuts: disabledWebShortcuts,- hide_on_close: platformHideOnClose,- incognito: incognito,- title: title,- enable_wasm: wasm,- enable_drag_drop: enableDragDrop,- start_to_tray: startToTray && showSystemTray,- force_internal_navigation: forceInternalNavigation,- internal_url_regex: internalUrlRegex,- zoom,- min_width: minWidth,- min_height: minHeight,- ignore_certificate_errors: ignoreCertificateErrors,- new_window: newWindow,- };- Object.assign(tauriConf.pake.windows[0], { url, ...tauriConfWindowOptions });-- tauriConf.productName = name;- tauriConf.identifier = identifier;- tauriConf.version = appVersion;-- // Always set mainBinaryName to ensure binary uniqueness- const linuxBinaryName = `pake-${generateLinuxPackageName(name)}`;- tauriConf.mainBinaryName =- platform === 'linux'- ? linuxBinaryName- : `pake-${generateIdentifierSafeName(name)}`;-- if (platform == 'win32') {- tauriConf.bundle.windows.wix.language[0] = installerLanguage;- }+}+async function handleLocalFile(+ url: string,+ useLocalFile: boolean,+ tauriConf: any,+): Promise<void> {const pathExists = await fsExtra.pathExists(url);if (pathExists) {logger.warn('✼ Your input might be a local file.');- tauriConf.pake.windows[0].url_type = 'local';const fileName = path.basename(url);const dirName = path.dirname(url);-const distDir = path.join(npmDirectory, 'dist');const distBakDir = path.join(npmDirectory, 'dist_bak');@@ -147,8 +59,6 @@ export async function mergeConfig(fsExtra.moveSync(distDir, distBakDir, { overwrite: true });fsExtra.copySync(dirName, distDir, { overwrite: true });- // ignore it, because about_pake.html have be erased.- // const filesToCopyBack = ['cli.js', 'about_pake.html'];const filesToCopyBack = ['cli.js'];await Promise.all(filesToCopyBack.map((file) =>@@ -162,35 +72,23 @@ export async function mergeConfig(} else {tauriConf.pake.windows[0].url_type = 'web';}+}- const platformMap: PlatformMap = {- win32: 'windows',- linux: 'linux',- darwin: 'macos',- };- const currentPlatform = platformMap[platform];-- if (userAgent.length > 0) {- tauriConf.pake.user_agent[currentPlatform] = userAgent;- }-- tauriConf.pake.system_tray[currentPlatform] = showSystemTray;-- // Processing targets are currently only open to Linux.- if (platform === 'linux') {- // Remove hardcoded desktop files and regenerate with correct app name- delete tauriConf.bundle.linux.deb.files;-- // Generate correct desktop file configuration- const linuxName = generateLinuxPackageName(name);- const desktopFileName = `com.pake.${linuxName}.desktop`;- const iconName = `${linuxName}_512`;+async function mergeLinuxConfig(+ options: PakeAppOptions,+ name: string,+ tauriConf: any,+ linuxBinaryName: string,+): Promise<void> {+ delete tauriConf.bundle.linux.deb.files;- // Create desktop file content- // Determine if title contains Chinese characters for Name[zh_CN]- const chineseName = title && /[\u4e00-\u9fa5]/.test(title) ? title : null;+ const linuxName = generateLinuxPackageName(name);+ const desktopFileName = `com.pake.${linuxName}.desktop`;+ const iconName = `${linuxName}_512`;+ const { title } = options;- const desktopContent = `[Desktop Entry]+ const chineseName = title && /[\u4e00-\u9fa5]/.test(title) ? title : null;+ const desktopContent = `[Desktop Entry]Version=1.0Type=ApplicationName=${name}@@ -204,58 +102,51 @@ StartupNotify=trueTerminal=false`;- // Write desktop file to src-tauri/assets directory where Tauri expects it- const srcAssetsDir = path.join(npmDirectory, 'src-tauri/assets');- const srcDesktopFilePath = path.join(srcAssetsDir, desktopFileName);- await fsExtra.ensureDir(srcAssetsDir);- await fsExtra.writeFile(srcDesktopFilePath, desktopContent);-- // Set up desktop file in bundle configuration- // Use absolute path from src-tauri directory to assets- const desktopInstallPath = `/usr/share/applications/${desktopFileName}`;- tauriConf.bundle.linux.deb.files = {- [desktopInstallPath]: `assets/${desktopFileName}`,- };+ const srcAssetsDir = path.join(npmDirectory, 'src-tauri/assets');+ const srcDesktopFilePath = path.join(srcAssetsDir, desktopFileName);+ await fsExtra.ensureDir(srcAssetsDir);+ await fsExtra.writeFile(srcDesktopFilePath, desktopContent);- // Add desktop file support for RPM- if (!tauriConf.bundle.linux.rpm) {- tauriConf.bundle.linux.rpm = {};- }- tauriConf.bundle.linux.rpm.files = {- [desktopInstallPath]: `assets/${desktopFileName}`,- };+ const desktopInstallPath = `/usr/share/applications/${desktopFileName}`;+ tauriConf.bundle.linux.deb.files = {+ [desktopInstallPath]: `assets/${desktopFileName}`,+ };- const validTargets = [- 'deb',- 'appimage',- 'rpm',- 'deb-arm64',- 'appimage-arm64',- 'rpm-arm64',- ];- const baseTarget = options.targets.includes('-arm64')- ? options.targets.replace('-arm64', '')- : options.targets;-- if (validTargets.includes(options.targets)) {- tauriConf.bundle.targets = [baseTarget];- } else {- logger.warn(- `✼ The target must be one of ${validTargets.join(', ')}, the default 'deb' will be used.`,- );- }+ if (!tauriConf.bundle.linux.rpm) {+ tauriConf.bundle.linux.rpm = {};}+ tauriConf.bundle.linux.rpm.files = {+ [desktopInstallPath]: `assets/${desktopFileName}`,+ };- // Set macOS bundle targets (for app vs dmg)- if (platform === 'darwin') {- const validMacTargets = ['app', 'dmg'];- if (validMacTargets.includes(options.targets)) {- tauriConf.bundle.targets = [options.targets];- }+ const validTargets = [+ 'deb',+ 'appimage',+ 'rpm',+ 'deb-arm64',+ 'appimage-arm64',+ 'rpm-arm64',+ ];+ const baseTarget = options.targets.includes('-arm64')+ ? options.targets.replace('-arm64', '')+ : options.targets;++ if (validTargets.includes(options.targets)) {+ tauriConf.bundle.targets = [baseTarget];+ } else {+ logger.warn(+ `✼ The target must be one of ${validTargets.join(', ')}, the default 'deb' will be used.`,+ );}+}- // Set icon.- const safeAppName = getSafeAppName(name);+async function mergeIcons(+ options: PakeAppOptions,+ name: string,+ tauriConf: any,+ platform: string,+ safeAppName: string,+): Promise<void> {const platformIconMap: PlatformMap = {win32: {fileExt: '.ico',@@ -276,13 +167,15 @@ Terminal=falsemessage: 'macOS icon must be .icns type.',},};+const iconInfo = platformIconMap[platform];const resolvedIconPath = options.icon ? path.resolve(options.icon) : null;const exists =resolvedIconPath && (await fsExtra.pathExists(resolvedIconPath));+if (exists) {let updateIconPath = true;- let customIconExt = path.extname(resolvedIconPath).toLowerCase();+ const customIconExt = path.extname(resolvedIconPath).toLowerCase();if (customIconExt !== iconInfo.fileExt) {updateIconPath = false;@@ -292,7 +185,6 @@ Terminal=falseconst iconPath = path.join(npmDirectory, 'src-tauri/', iconInfo.path);tauriConf.bundle.resources = [iconInfo.path];- // Avoid copying if source and destination are the sameconst absoluteDestPath = path.resolve(iconPath);if (resolvedIconPath !== absoluteDestPath) {try {@@ -327,18 +219,17 @@ Terminal=false// Set tray icon path.let trayIconPath =platform === 'darwin' ? 'png/icon_512.png' : tauriConf.bundle.icon[0];- if (systemTrayIcon.length > 0) {+ if (options.systemTrayIcon.length > 0) {try {- await fsExtra.pathExists(systemTrayIcon);- // 需要判断图标格式,默认只支持ico和png两种- let iconExt = path.extname(systemTrayIcon).toLowerCase();- if (iconExt == '.png' || iconExt == '.ico') {+ await fsExtra.pathExists(options.systemTrayIcon);+ const iconExt = path.extname(options.systemTrayIcon).toLowerCase();+ if (iconExt === '.png' || iconExt === '.ico') {const trayIcoPath = path.join(npmDirectory,`src-tauri/png/${safeAppName}${iconExt}`,);trayIconPath = `png/${safeAppName}${iconExt}`;- await fsExtra.copy(systemTrayIcon, trayIcoPath);+ await fsExtra.copy(options.systemTrayIcon, trayIcoPath);} else {logger.warn(`✼ System tray icon must be .ico or .png, but you provided ${iconExt}.`,@@ -346,28 +237,26 @@ Terminal=falselogger.warn(`✼ Default system tray icon will be used.`);}} catch {- logger.warn(`✼ ${systemTrayIcon} not exists!`);+ logger.warn(`✼ ${options.systemTrayIcon} not exists!`);logger.warn(`✼ Default system tray icon will remain unchanged.`);}}- // Ensure trayIcon object exists before setting iconPath- if (!tauriConf.app.trayIcon) {- tauriConf.app.trayIcon = {};- }- tauriConf.app.trayIcon.iconPath = trayIconPath;tauriConf.pake.system_tray_path = trayIconPath;-delete tauriConf.app.trayIcon;+}+async function injectCustomCode(+ options: PakeAppOptions,+ tauriConf: any,+): Promise<void> {+ const { inject, proxyUrl, multiInstance, multiWindow, wasm } = options;const injectFilePath = path.join(npmDirectory,- `src-tauri/src/inject/custom.js`,+ 'src-tauri/src/inject/custom.js',);- // inject js or css filesif (inject?.length > 0) {- // Ensure inject is an array before calling .every()const injectArray = Array.isArray(inject) ? inject : [inject];if (!injectArray.every(@@ -386,11 +275,11 @@ Terminal=falsetauriConf.pake.inject = [];await fsExtra.writeFile(injectFilePath, '');}+tauriConf.pake.proxy_url = proxyUrl || '';tauriConf.pake.multi_instance = multiInstance;tauriConf.pake.multi_window = multiWindow;- // Configure WASM support with required HTTP headersif (wasm) {tauriConf.app.security = {headers: {@@ -399,21 +288,24 @@ Terminal=false},};}+}- // Write entitlements dynamically on macOS so camera/microphone are opt-in- if (platform === 'darwin') {- const entitlementEntries: string[] = [];- if (camera) {- entitlementEntries.push(- ' <key>com.apple.security.device.camera</key>\n <true/>',- );- }- if (microphone) {- entitlementEntries.push(- ' <key>com.apple.security.device.audio-input</key>\n <true/>',- );- }- const entitlementsContent = `<?xml version="1.0" encoding="UTF-8"?>+async function generateMacEntitlements(+ camera: boolean,+ microphone: boolean,+): Promise<void> {+ const entitlementEntries: string[] = [];+ if (camera) {+ entitlementEntries.push(+ ' <key>com.apple.security.device.camera</key>\n <true/>',+ );+ }+ if (microphone) {+ entitlementEntries.push(+ ' <key>com.apple.security.device.audio-input</key>\n <true/>',+ );+ }+ const entitlementsContent = `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict>@@ -421,15 +313,18 @@ ${entitlementEntries.join('\n')}</dict></plist>`;- const entitlementsPath = path.join(- npmDirectory,- 'src-tauri',- 'entitlements.plist',- );- await fsExtra.writeFile(entitlementsPath, entitlementsContent);- }+ const entitlementsPath = path.join(+ npmDirectory,+ 'src-tauri',+ 'entitlements.plist',+ );+ await fsExtra.writeFile(entitlementsPath, entitlementsContent);+}- // Save config file.+async function writeAllConfigs(+ tauriConf: any,+ platform: string,+): Promise<void> {const platformConfigPaths: PlatformMap = {win32: 'tauri.windows.conf.json',darwin: 'tauri.macos.conf.json',@@ -440,19 +335,140 @@ ${entitlementEntries.join('\n')}tauriConfigDirectory,platformConfigPaths[platform],);-const bundleConf = { bundle: tauriConf.bundle };await fsExtra.outputJSON(configPath, bundleConf, { spaces: 4 });+const pakeConfigPath = path.join(tauriConfigDirectory, 'pake.json');await fsExtra.outputJSON(pakeConfigPath, tauriConf.pake, { spaces: 4 });- let tauriConf2 = JSON.parse(JSON.stringify(tauriConf));+ const tauriConf2 = JSON.parse(JSON.stringify(tauriConf));delete tauriConf2.pake;-- // delete tauriConf2.bundle;if (process.env.NODE_ENV === 'development') {tauriConf2.bundle = bundleConf.bundle;}const configJsonPath = path.join(tauriConfigDirectory, 'tauri.conf.json');await fsExtra.outputJSON(configJsonPath, tauriConf2, { spaces: 4 });}++export async function mergeConfig(+ url: string,+ options: PakeAppOptions,+ tauriConf: any,+) {+ 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 platformHideOnClose = hideOnClose ?? platform === 'darwin';++ const tauriConfWindowOptions: Partial<WindowConfig> = {+ width,+ height,+ fullscreen,+ maximize,+ resizable,+ hide_title_bar: hideTitleBar,+ activation_shortcut: activationShortcut,+ always_on_top: alwaysOnTop,+ dark_mode: darkMode,+ disabled_web_shortcuts: disabledWebShortcuts,+ hide_on_close: platformHideOnClose,+ incognito,+ title,+ enable_wasm: wasm,+ enable_drag_drop: enableDragDrop,+ start_to_tray: startToTray && showSystemTray,+ force_internal_navigation: forceInternalNavigation,+ internal_url_regex: internalUrlRegex,+ zoom,+ min_width: minWidth,+ min_height: minHeight,+ ignore_certificate_errors: ignoreCertificateErrors,+ new_window: newWindow,+ };+ Object.assign(tauriConf.pake.windows[0], { url, ...tauriConfWindowOptions });++ tauriConf.productName = name;+ tauriConf.identifier = identifier;+ tauriConf.version = appVersion;++ const linuxBinaryName = `pake-${generateLinuxPackageName(name)}`;+ tauriConf.mainBinaryName =+ platform === 'linux'+ ? linuxBinaryName+ : `pake-${generateIdentifierSafeName(name)}`;++ if (platform === 'win32') {+ tauriConf.bundle.windows.wix.language[0] = installerLanguage;+ }++ await handleLocalFile(url, useLocalFile, tauriConf);++ const platformMap: PlatformMap = {+ win32: 'windows',+ linux: 'linux',+ darwin: 'macos',+ };+ const currentPlatform = platformMap[platform];++ if (userAgent.length > 0) {+ tauriConf.pake.user_agent[currentPlatform] = userAgent;+ }+ tauriConf.pake.system_tray[currentPlatform] = showSystemTray;++ if (platform === 'linux') {+ await mergeLinuxConfig(options, name, tauriConf, linuxBinaryName);+ }++ if (platform === 'darwin') {+ const validMacTargets = ['app', 'dmg'];+ if (validMacTargets.includes(options.targets)) {+ tauriConf.bundle.targets = [options.targets];+ }+ }++ const safeAppName = getSafeAppName(name);+ await mergeIcons(options, name, tauriConf, platform, safeAppName);++ await injectCustomCode(options, tauriConf);++ if (platform === 'darwin') {+ await generateMacEntitlements(camera, microphone);+ }++ await writeAllConfigs(tauriConf, platform);+}diff --git a/bin/options/icon.ts b/bin/options/icon.tsindex 623096f2..c767411c 100644--- a/bin/options/icon.ts+++ b/bin/options/icon.ts@@ -15,7 +15,7 @@ import {getIconSourcePriority,type IconSource,} from '@/utils/icon-source';-import { generateLinuxPackageName, generateSafeFilename } from '@/utils/name';+import { generateLinuxPackageName, getSafeAppName } from '@/utils/name';import { PakeAppOptions } from '@/types';import { writeIcoWithPreferredSize, buildIcoFromPngBuffers } from '@/utils/ico';@@ -74,7 +74,7 @@ function generateIconPath(appName: string, isDefault = false): string {function getIconBaseName(appName: string): string {const baseName = IS_LINUX? generateLinuxPackageName(appName)- : generateSafeFilename(appName).toLowerCase();+ : getSafeAppName(appName);return baseName || 'pake-app';}diff --git a/bin/options/logger.ts b/bin/options/logger.tsindex d35164b5..2d964c31 100644--- a/bin/options/logger.ts+++ b/bin/options/logger.ts@@ -12,7 +12,7 @@ const logger = {log.error(...msg.map((m) => chalk.red(m)));},warn(...msg: any[]) {- log.info(...msg.map((m) => chalk.yellow(m)));+ log.warn(...msg.map((m) => chalk.yellow(m)));},success(...msg: any[]) {log.info(...msg.map((m) => chalk.green(m)));diff --git a/bin/utils/combine.ts b/bin/utils/combine.tsindex dc9c1ab1..835a8d37 100644--- a/bin/utils/combine.ts+++ b/bin/utils/combine.ts@@ -1,24 +1,26 @@-import fs from 'fs';+import fs from 'fs/promises';export default async function combineFiles(files: string[], output: string) {- const contents = files.map((file) => {- if (file.endsWith('.css')) {- const fileContent = fs.readFileSync(file, 'utf-8');- return `window.addEventListener('DOMContentLoaded', (_event) => {+ const contents = await Promise.all(+ files.map(async (file) => {+ if (file.endsWith('.css')) {+ const fileContent = await fs.readFile(file, 'utf-8');+ return `window.addEventListener('DOMContentLoaded', (_event) => {const css = ${JSON.stringify(fileContent)};const style = document.createElement('style');style.textContent = css;document.head.appendChild(style);});`;- }+ }- const fileContent = fs.readFileSync(file);- return (- "window.addEventListener('DOMContentLoaded', (_event) => { " +- fileContent +- ' });'- );- });- fs.writeFileSync(output, contents.join('\n'));+ const fileContent = await fs.readFile(file);+ return (+ "window.addEventListener('DOMContentLoaded', (_event) => { " ++ fileContent ++ ' });'+ );+ }),+ );+ await fs.writeFile(output, contents.join('\n'));return files;}diff --git a/dist/cli.js b/dist/cli.jsindex 8306efc4..d817c0b3 100644--- a/dist/cli.js+++ b/dist/cli.js@@ -95,7 +95,6 @@ var devDependencies = {"@rollup/plugin-terser": "^0.4.4","@types/fs-extra": "^11.0.4","@types/node": "^25.3.2",- "@types/page-icon": "^0.3.6","@types/prompts": "^2.4.9","@types/tmp": "^0.2.6","@types/update-notifier": "^6.0.8",@@ -289,7 +288,7 @@ const logger = {log.error(...msg.map((m) => chalk.red(m)));},warn(...msg) {- log.info(...msg.map((m) => chalk.yellow(m)));+ log.warn(...msg.map((m) => chalk.yellow(m)));},success(...msg) {log.info(...msg.map((m) => chalk.green(m)));@@ -537,13 +536,12 @@ async function mergeConfig(url, options, tauriConf) {platform === 'linux'? linuxBinaryName: `pake-${generateIdentifierSafeName(name)}`;- if (platform == 'win32') {+ if (platform === 'win32') {tauriConf.bundle.windows.wix.language[0] = installerLanguage;}const pathExists = await fsExtra.pathExists(url);if (pathExists) {logger.warn('✼ Your input might be a local file.');- tauriConf.pake.windows[0].url_type = 'local';const fileName = path.basename(url);const dirName = path.dirname(url);const distDir = path.join(npmDirectory, 'dist');@@ -726,11 +724,6 @@ Terminal=falselogger.warn(`✼ Default system tray icon will remain unchanged.`);}}- // Ensure trayIcon object exists before setting iconPath- if (!tauriConf.app.trayIcon) {- tauriConf.app.trayIcon = {};- }- tauriConf.app.trayIcon.iconPath = trayIconPath;tauriConf.pake.system_tray_path = trayIconPath;delete tauriConf.app.trayIcon;const injectFilePath = path.join(npmDirectory, `src-tauri/src/inject/custom.js`);@@ -884,7 +877,7 @@ class BaseBuilder {}else {logger.error('✕ Rust required to package your webapp.');- process.exit(0);+ process.exit(1);}}const isChina = await isChinaDomain('www.npmjs.com');@@ -2469,7 +2462,9 @@ ${green('|_| \\__,_|_|\\_\\___| can turn any webpage into a desktop app with.addOption(new Option('--new-window', 'Allow sites to open new windows (for auth flows, tabs, branches)').default(DEFAULT_PAKE_OPTIONS.newWindow).hideHelp())- .option('--install', 'Auto-install app to /Applications (macOS) after build and remove local bundle', DEFAULT_PAKE_OPTIONS.install)+ .addOption(new Option('--install', 'Auto-install app to /Applications (macOS) after build and remove local bundle')+ .default(DEFAULT_PAKE_OPTIONS.install)+ .hideHelp()).addOption(new Option('--camera', 'Request camera permission on macOS').default(DEFAULT_PAKE_OPTIONS.camera).hideHelp())diff --git a/package.json b/package.jsonindex 89c226c3..dae5ec99 100644--- a/package.json+++ b/package.json@@ -73,7 +73,6 @@"@rollup/plugin-terser": "^0.4.4","@types/fs-extra": "^11.0.4","@types/node": "^25.3.2",- "@types/page-icon": "^0.3.6","@types/prompts": "^2.4.9","@types/tmp": "^0.2.6","@types/update-notifier": "^6.0.8",diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 9f55af92..ac50cf2f 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -4575,9 +4575,7 @@ dependencies = ["bytes","libc","mio",- "parking_lot","pin-project-lite",- "signal-hook-registry","socket2","tokio-macros","windows-sys 0.61.2",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 845fac1a..367c7c51 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -20,7 +20,7 @@ tauri-build = { version = "2.5.5", features = [] }[dependencies]serde_json = "1.0.149"serde = { version = "1.0.228", features = ["derive"] }-tokio = { version = "1.49.0", features = ["full"] }+tokio = { version = "1.49.0", features = ["time"] }tauri = { version = "2.10.2", features = ["tray-icon","image-ico",@@ -48,7 +48,7 @@ custom-protocol = ["tauri/custom-protocol"][profile.release]panic = "abort"-codegen-units = 16+codegen-units = 1lto = "thin"opt-level = "z"strip = truediff --git a/src-tauri/src/app/setup.rs b/src-tauri/src/app/setup.rsindex 19af80c1..f4e5b22a 100644--- a/src-tauri/src/app/setup.rs+++ b/src-tauri/src/app/setup.rs@@ -47,12 +47,12 @@ pub fn set_system_tray(}"hide_app" => {if let Some(window) = app.get_webview_window("pake") {- window.minimize().unwrap();+ let _ = window.minimize();}}"show_app" => {if let Some(window) = app.get_webview_window("pake") {- window.show().unwrap();+ let _ = window.show();#[cfg(target_os = "linux")]if _init_fullscreen && !window.is_fullscreen().unwrap_or(false) {let _ = window.set_fullscreen(true);@@ -61,8 +61,8 @@ pub fn set_system_tray(}}"quit" => {- app.save_window_state(StateFlags::all()).unwrap();- std::process::exit(0);+ let _ = app.save_window_state(StateFlags::all());+ app.exit(0);}_ => (),})@@ -72,10 +72,10 @@ pub fn set_system_tray(if let Some(window) = tray.app_handle().get_webview_window("pake") {let is_visible = window.is_visible().unwrap_or(false);if is_visible {- window.hide().unwrap();+ let _ = window.hide();} else {- window.show().unwrap();- window.set_focus().unwrap();+ let _ = window.show();+ let _ = window.set_focus();#[cfg(target_os = "linux")]if _init_fullscreen && !window.is_fullscreen().unwrap_or(false) {let _ = window.set_fullscreen(true);@@ -114,7 +114,10 @@ pub fn set_global_shortcut(}let app_handle = app.clone();- let shortcut_hotkey = Shortcut::from_str(&shortcut).unwrap();+ let shortcut_hotkey = match Shortcut::from_str(&shortcut) {+ Ok(s) => s,+ Err(_) => return Ok(()),+ };let last_triggered = Arc::new(Mutex::new(Instant::now()));app_handle@@ -133,12 +136,12 @@ pub fn set_global_shortcut(if shortcut_hotkey.eq(event) {if let Some(window) = app.get_webview_window("pake") {- let is_visible = window.is_visible().unwrap();+ let is_visible = window.is_visible().unwrap_or(false);if is_visible {- window.hide().unwrap();+ let _ = window.hide();} else {- window.show().unwrap();- window.set_focus().unwrap();+ let _ = window.show();+ let _ = window.set_focus();#[cfg(target_os = "linux")]if _init_fullscreen && !window.is_fullscreen().unwrap_or(false){@@ -153,7 +156,7 @@ pub fn set_global_shortcut().expect("Failed to set global shortcut");- app.global_shortcut().register(shortcut_hotkey).unwrap();+ let _ = app.global_shortcut().register(shortcut_hotkey);Ok(())}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 5a15545d..62441120 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -107,9 +107,8 @@ pub fn run_app() {&pake_config.system_tray_path,init_fullscreen,multi_window,- )- .unwrap();- set_global_shortcut(app.app_handle(), activation_shortcut, init_fullscreen).unwrap();+ )?;+ set_global_shortcut(app.app_handle(), activation_shortcut, init_fullscreen)?;// Show window after state restoration to prevent position flashing// Unless start_to_tray is enabled, then keep it hidden@@ -117,13 +116,13 @@ pub fn run_app() {let window_clone = window.clone();tauri::async_runtime::spawn(async move {tokio::time::sleep(tokio::time::Duration::from_millis(WINDOW_SHOW_DELAY)).await;- window_clone.show().unwrap();+ let _ = window_clone.show();// Fixed: Linux fullscreen issue with virtual keyboard#[cfg(target_os = "linux")]{if init_fullscreen {- window_clone.set_fullscreen(true).unwrap();+ let _ = window_clone.set_fullscreen(true);// Ensure webview maintains focus for input after fullscreenlet _ = window_clone.set_focus();} else {@@ -148,22 +147,22 @@ pub fn run_app() {#[cfg(target_os = "macos")]{if window.is_fullscreen().unwrap_or(false) {- window.set_fullscreen(false).unwrap();+ let _ = window.set_fullscreen(false);tokio::time::sleep(Duration::from_millis(900)).await;}}#[cfg(target_os = "linux")]{if window.is_fullscreen().unwrap_or(false) {- window.set_fullscreen(false).unwrap();+ let _ = window.set_fullscreen(false);// Restore focus after exiting fullscreen to fix input issueslet _ = window.set_focus();}}// On macOS, directly hide without minimize to avoid duplicate Dock icons#[cfg(not(target_os = "macos"))]- window.minimize().unwrap();- window.hide().unwrap();+ let _ = window.minimize();+ let _ = window.hide();});api.prevent_close();}diff --git a/tests/unit/cli-options.test.ts b/tests/unit/cli-options.test.tsindex dcbee27b..9b8c8005 100644--- a/tests/unit/cli-options.test.ts+++ b/tests/unit/cli-options.test.ts@@ -29,11 +29,11 @@ describe('CLI options', () => {expect(option?.hidden).toBe(true);});- it('registers visible --install option', () => {+ it('registers hidden --install option', () => {const option = program.options.find((item) => item.long === '--install');expect(option).toBeDefined();expect(option?.defaultValue).toBe(false);- expect(option?.hidden).toBe(false);+ expect(option?.hidden).toBe(true);});});