🔧 Global formatting and update formatting

This commit is contained in:
Tw93
2025-08-05 19:53:58 +08:00
parent 467123068a
commit 7c2c68f3a6
47 changed files with 824 additions and 653 deletions

7
bin/README.md vendored
View File

@@ -13,7 +13,6 @@ npm install pake-cli -g
- **CRITICAL**: Consult [Tauri prerequisites](https://tauri.app/start/prerequisites/) before proceeding.
- For Windows users (ensure that `Win10 SDK (10.0.19041.0)` and `Visual Studio build tool 2022 (>=17.2)` are installed), additional installations are required:
1. Microsoft Visual C++ 2015-2022 Redistributable (x64)
2. Microsoft Visual C++ 2015-2022 Redistributable (x86)
3. Microsoft Visual C++ 2012 Redistributable (x86) (optional)
@@ -251,7 +250,7 @@ Supports both comma-separated and multiple option formats:
# Comma-separated (recommended)
--inject ./tools/style.css,./tools/hotkey.js
# Multiple options
# Multiple options
--inject ./tools/style.css --inject ./tools/hotkey.js
# Single file
@@ -285,8 +284,8 @@ The `DEFAULT_DEV_PAKE_OPTIONS` configuration in `bin/defaults.ts` can be modifie
```typescript
export const DEFAULT_DEV_PAKE_OPTIONS: PakeCliOptions & { url: string } = {
...DEFAULT_PAKE_OPTIONS,
url: 'https://weread.qq.com',
name: 'Weread',
url: "https://weread.qq.com",
name: "Weread",
};
```

5
bin/README_CN.md vendored
View File

@@ -13,7 +13,6 @@ npm install pake-cli -g
- **非常重要**:请参阅 Tauri 的 [依赖项指南](https://tauri.app/start/prerequisites/)。
- 对于 Windows 用户,请确保至少安装了 `Win10 SDK(10.0.19041.0)``Visual Studio Build Tools 2022版本 17.2 或更高)`,此外还需要安装以下组件:
1. Microsoft Visual C++ 2015-2022 Redistributable (x64)
2. Microsoft Visual C++ 2015-2022 Redistributable (x86)
3. Microsoft Visual C++ 2012 Redistributable (x86)(可选)
@@ -287,8 +286,8 @@ pake [url] [options]
```typescript
export const DEFAULT_DEV_PAKE_OPTIONS: PakeCliOptions & { url: string } = {
...DEFAULT_PAKE_OPTIONS,
url: 'https://weread.qq.com',
name: 'Weread',
url: "https://weread.qq.com",
name: "Weread",
};
```

View File

@@ -56,13 +56,17 @@ export default abstract class BaseBuilder {
logger.info('✺ Located in China, using npm/rsProxy CN mirror.');
const projectCnConf = path.join(tauriSrcPath, 'rust_proxy.toml');
await fsExtra.copy(projectCnConf, projectConf);
await shellExec(`cd "${npmDirectory}" && npm install --registry=https://registry.npmmirror.com`);
await shellExec(
`cd "${npmDirectory}" && npm install --registry=https://registry.npmmirror.com`,
);
} else {
await shellExec(`cd "${npmDirectory}" && npm install`);
}
spinner.succeed(chalk.green('Package installed!'));
if (!tauriTargetPathExists) {
logger.warn('✼ The first packaging may be slow, please be patient and wait, it will be faster afterwards.');
logger.warn(
'✼ The first packaging may be slow, please be patient and wait, it will be faster afterwards.',
);
}
}
@@ -110,7 +114,16 @@ export default abstract class BaseBuilder {
return `src-tauri/target/${basePath}/bundle/`;
}
protected getBuildAppPath(npmDirectory: string, fileName: string, fileType: string): string {
return path.join(npmDirectory, this.getBasePath(), fileType.toLowerCase(), `${fileName}.${fileType}`);
protected getBuildAppPath(
npmDirectory: string,
fileName: string,
fileType: string,
): string {
return path.join(
npmDirectory,
this.getBasePath(),
fileType.toLowerCase(),
`${fileName}.${fileType}`,
);
}
}

View File

@@ -6,7 +6,10 @@ import { PakeAppOptions } from '@/types';
const { platform } = process;
const buildersMap: Record<string, new (options: PakeAppOptions) => BaseBuilder> = {
const buildersMap: Record<
string,
new (options: PakeAppOptions) => BaseBuilder
> = {
darwin: MacBuilder,
win32: WinBuilder,
linux: LinuxBuilder,

View File

@@ -20,7 +20,9 @@ export default class MacBuilder extends BaseBuilder {
}
protected getBuildCommand(): string {
return this.options.multiArch ? 'npm run build:mac' : super.getBuildCommand();
return this.options.multiArch
? 'npm run build:mac'
: super.getBuildCommand();
}
protected getBasePath(): string {

125
bin/cli.ts vendored
View File

@@ -3,7 +3,10 @@ import { program, Option } from 'commander';
import log from 'loglevel';
import packageJson from '../package.json';
import BuilderProvider from './builders/BuilderProvider';
import { DEFAULT_PAKE_OPTIONS as DEFAULT, DEFAULT_PAKE_OPTIONS } from './defaults';
import {
DEFAULT_PAKE_OPTIONS as DEFAULT,
DEFAULT_PAKE_OPTIONS,
} from './defaults';
import { checkUpdateTips } from './helpers/updater';
import handleInputOptions from './options/index';
@@ -18,7 +21,10 @@ ${green('| __/ (_| | < __/')} ${yellow('https://github.com/tw93/pake')}
${green('|_| \\__,_|_|\\_\\___| can turn any webpage into a desktop app with Rust.')}
`;
program.addHelpText('beforeAll', logo).usage(`[url] [options]`).showHelpAfterError();
program
.addHelpText('beforeAll', logo)
.usage(`[url] [options]`)
.showHelpAfterError();
program
.argument('[url]', 'The web URL you want to package', validateUrlInput)
@@ -26,15 +32,26 @@ program
// If the platform is Linux, use `-` as the connector, and convert all characters to lowercase.
// For example, Google Translate will become google-translate.
.option('--name <string...>', 'Application name', (value, previous) => {
const platform = process.platform
const connector = platform === 'linux' ? '-' : ' '
const name = previous === undefined ? value : `${previous}${connector}${value}`
return platform === 'linux' ? name.toLowerCase() : name
const platform = process.platform;
const connector = platform === 'linux' ? '-' : ' ';
const name =
previous === undefined ? value : `${previous}${connector}${value}`;
return platform === 'linux' ? name.toLowerCase() : name;
})
.option('--icon <string>', 'Application icon', DEFAULT.icon)
.option('--width <number>', 'Window width', validateNumberInput, DEFAULT.width)
.option('--height <number>', 'Window height', validateNumberInput, DEFAULT.height)
.option(
'--width <number>',
'Window width',
validateNumberInput,
DEFAULT.width,
)
.option(
'--height <number>',
'Window height',
validateNumberInput,
DEFAULT.height,
)
.option('--use-local-file', 'Use local file packaging', DEFAULT.useLocalFile)
.option('--fullscreen', 'Start in full screen', DEFAULT.fullscreen)
.option('--hide-title-bar', 'For Mac, hide title bar', DEFAULT.hideTitleBar)
@@ -44,41 +61,93 @@ program
'Injection of .js or .css files',
(val, previous) => {
if (!val) return DEFAULT.inject;
// Split by comma and trim whitespace, filter out empty strings
const files = val.split(',')
.map(item => item.trim())
.filter(item => item.length > 0);
const files = val
.split(',')
.map((item) => item.trim())
.filter((item) => item.length > 0);
// If previous values exist (from multiple --inject options), merge them
return previous ? [...previous, ...files] : files;
},
DEFAULT.inject,
)
.option('--debug', 'Debug build and more output', DEFAULT.debug)
.addOption(new Option('--proxy-url <url>', 'Proxy URL for all network requests').default(DEFAULT_PAKE_OPTIONS.proxyUrl).hideHelp())
.addOption(new Option('--user-agent <string>', 'Custom user agent').default(DEFAULT.userAgent).hideHelp())
.addOption(new Option('--targets <string>', 'For Linux, option "deb" or "appimage"').default(DEFAULT.targets).hideHelp())
.addOption(new Option('--app-version <string>', 'App version, the same as package.json version').default(DEFAULT.appVersion).hideHelp())
.addOption(new Option('--always-on-top', 'Always on the top level').default(DEFAULT.alwaysOnTop).hideHelp())
.addOption(new Option('--dark-mode', 'Force Mac app to use dark mode').default(DEFAULT.darkMode).hideHelp())
.addOption(new Option('--disabled-web-shortcuts', 'Disabled webPage shortcuts').default(DEFAULT.disabledWebShortcuts).hideHelp())
.addOption(
new Option('--activation-shortcut <string>', 'Shortcut key to active App').default(DEFAULT_PAKE_OPTIONS.activationShortcut).hideHelp(),
new Option('--proxy-url <url>', 'Proxy URL for all network requests')
.default(DEFAULT_PAKE_OPTIONS.proxyUrl)
.hideHelp(),
)
.addOption(
new Option('--user-agent <string>', 'Custom user agent')
.default(DEFAULT.userAgent)
.hideHelp(),
)
.addOption(
new Option('--targets <string>', 'For Linux, option "deb" or "appimage"')
.default(DEFAULT.targets)
.hideHelp(),
)
.addOption(
new Option(
'--app-version <string>',
'App version, the same as package.json version',
)
.default(DEFAULT.appVersion)
.hideHelp(),
)
.addOption(
new Option('--always-on-top', 'Always on the top level')
.default(DEFAULT.alwaysOnTop)
.hideHelp(),
)
.addOption(
new Option('--dark-mode', 'Force Mac app to use dark mode')
.default(DEFAULT.darkMode)
.hideHelp(),
)
.addOption(
new Option('--disabled-web-shortcuts', 'Disabled webPage shortcuts')
.default(DEFAULT.disabledWebShortcuts)
.hideHelp(),
)
.addOption(
new Option('--activation-shortcut <string>', 'Shortcut key to active App')
.default(DEFAULT_PAKE_OPTIONS.activationShortcut)
.hideHelp(),
)
.addOption(
new Option('--show-system-tray', 'Show system tray in app')
.default(DEFAULT.showSystemTray)
.hideHelp(),
)
.addOption(
new Option('--system-tray-icon <string>', 'Custom system tray icon')
.default(DEFAULT.systemTrayIcon)
.hideHelp(),
)
.addOption(
new Option('--hide-on-close', 'Hide window on close instead of exiting')
.default(DEFAULT.hideOnClose)
.hideHelp(),
)
.addOption(
new Option('--installer-language <string>', 'Installer language')
.default(DEFAULT.installerLanguage)
.hideHelp(),
)
.addOption(new Option('--show-system-tray', 'Show system tray in app').default(DEFAULT.showSystemTray).hideHelp())
.addOption(new Option('--system-tray-icon <string>', 'Custom system tray icon').default(DEFAULT.systemTrayIcon).hideHelp())
.addOption(new Option('--hide-on-close', 'Hide window on close instead of exiting').default(DEFAULT.hideOnClose).hideHelp())
.addOption(new Option('--installer-language <string>', 'Installer language').default(DEFAULT.installerLanguage).hideHelp())
.version(packageJson.version, '-v, --version', 'Output the current version')
.action(async (url: string, options: PakeCliOptions) => {
await checkUpdateTips();
if (!url) {
program.outputHelp(str => {
program.outputHelp((str) => {
return str
.split('\n')
.filter(line => !/((-h,|--help)|((-v|-V),|--version))\s+.+$/.test(line))
.filter(
(line) => !/((-h,|--help)|((-v|-V),|--version))\s+.+$/.test(line),
)
.join('\n');
});
process.exit(0);

2
bin/defaults.ts vendored
View File

@@ -18,7 +18,7 @@ export const DEFAULT_PAKE_OPTIONS: PakeCliOptions = {
targets: 'deb',
useLocalFile: false,
systemTrayIcon: '',
proxyUrl: "",
proxyUrl: '',
debug: false,
inject: [],
installerLanguage: 'en-US',

5
bin/dev.ts vendored
View File

@@ -6,7 +6,10 @@ import BuilderProvider from './builders/BuilderProvider';
async function startBuild() {
log.setDefaultLevel('debug');
const appOptions = await handleInputOptions(DEFAULT_DEV_PAKE_OPTIONS, DEFAULT_DEV_PAKE_OPTIONS.url);
const appOptions = await handleInputOptions(
DEFAULT_DEV_PAKE_OPTIONS,
DEFAULT_DEV_PAKE_OPTIONS.url,
);
log.debug('PakeAppOptions', appOptions);
const builder = BuilderProvider.create(appOptions);

50
bin/helpers/merge.ts vendored
View File

@@ -7,7 +7,11 @@ import logger from '@/options/logger';
import { PakeAppOptions, PlatformMap } from '@/types';
import { tauriConfigDirectory } from '@/utils/dir';
export async function mergeConfig(url: string, options: PakeAppOptions, tauriConf: any) {
export async function mergeConfig(
url: string,
options: PakeAppOptions,
tauriConf: any,
) {
const {
width,
height,
@@ -78,7 +82,11 @@ export async function mergeConfig(url: string, options: PakeAppOptions, tauriCon
// 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 => fsExtra.copy(path.join(distBakDir, file), path.join(distDir, file))));
await Promise.all(
filesToCopyBack.map((file) =>
fsExtra.copy(path.join(distBakDir, file), path.join(distDir, file)),
),
);
}
tauriConf.pake.windows[0].url = fileName;
@@ -107,7 +115,9 @@ export async function mergeConfig(url: string, options: PakeAppOptions, tauriCon
if (validTargets.includes(options.targets)) {
tauriConf.bundle.targets = [options.targets];
} else {
logger.warn(`✼ The target must be one of ${validTargets.join(', ')}, the default 'deb' will be used.`);
logger.warn(
`✼ The target must be one of ${validTargets.join(', ')}, the default 'deb' will be used.`,
);
}
}
@@ -154,23 +164,31 @@ export async function mergeConfig(url: string, options: PakeAppOptions, tauriCon
logger.warn(`✼ Icon will remain as default.`);
}
} else {
logger.warn('✼ Custom icon path may be invalid, default icon will be used instead.');
logger.warn(
'✼ Custom icon path may be invalid, default icon will be used instead.',
);
tauriConf.bundle.icon = [iconInfo.defaultIcon];
}
// Set tray icon path.
let trayIconPath = platform === 'darwin' ? 'png/icon_512.png' : tauriConf.bundle.icon[0];
let trayIconPath =
platform === 'darwin' ? 'png/icon_512.png' : tauriConf.bundle.icon[0];
if (systemTrayIcon.length > 0) {
try {
await fsExtra.pathExists(systemTrayIcon);
// 需要判断图标格式默认只支持ico和png两种
let iconExt = path.extname(systemTrayIcon).toLowerCase();
if (iconExt == '.png' || iconExt == '.ico') {
const trayIcoPath = path.join(npmDirectory, `src-tauri/png/${name.toLowerCase()}${iconExt}`);
const trayIcoPath = path.join(
npmDirectory,
`src-tauri/png/${name.toLowerCase()}${iconExt}`,
);
trayIconPath = `png/${name.toLowerCase()}${iconExt}`;
await fsExtra.copy(systemTrayIcon, trayIcoPath);
} else {
logger.warn(`✼ System tray icon must be .ico or .png, but you provided ${iconExt}.`);
logger.warn(
`✼ System tray icon must be .ico or .png, but you provided ${iconExt}.`,
);
logger.warn(`✼ Default system tray icon will be used.`);
}
} catch {
@@ -184,15 +202,22 @@ export async function mergeConfig(url: string, options: PakeAppOptions, tauriCon
delete tauriConf.app.trayIcon;
const injectFilePath = path.join(npmDirectory, `src-tauri/src/inject/custom.js`);
const injectFilePath = path.join(
npmDirectory,
`src-tauri/src/inject/custom.js`,
);
// inject js or css files
if (inject?.length > 0) {
if (!inject.every(item => item.endsWith('.css') || item.endsWith('.js'))) {
if (
!inject.every((item) => item.endsWith('.css') || item.endsWith('.js'))
) {
logger.error('The injected file must be in either CSS or JS format.');
return;
}
const files = inject.map(filepath => (path.isAbsolute(filepath) ? filepath : path.join(process.cwd(), filepath)));
const files = inject.map((filepath) =>
path.isAbsolute(filepath) ? filepath : path.join(process.cwd(), filepath),
);
tauriConf.pake.inject = files;
await combineFiles(files, injectFilePath);
} else {
@@ -208,7 +233,10 @@ export async function mergeConfig(url: string, options: PakeAppOptions, tauriCon
linux: 'tauri.linux.conf.json',
};
const configPath = path.join(tauriConfigDirectory, platformConfigPaths[platform]);
const configPath = path.join(
tauriConfigDirectory,
platformConfigPaths[platform],
);
const bundleConf = { bundle: tauriConf.bundle };
console.log('pakeConfig', tauriConf.pake);

4
bin/helpers/rust.ts vendored
View File

@@ -18,7 +18,9 @@ export async function installRust() {
const spinner = getSpinner('Downloading Rust...');
try {
await shellExec(IS_WIN ? rustInstallScriptForWindows : rustInstallScriptForMac);
await shellExec(
IS_WIN ? rustInstallScriptForWindows : rustInstallScriptForMac,
);
spinner.succeed(chalk.green('Rust installed successfully!'));
} catch (error) {
console.error('Error installing Rust:', error.message);

View File

@@ -2,5 +2,7 @@ import updateNotifier from 'update-notifier';
import packageJson from '../../package.json';
export async function checkUpdateTips() {
updateNotifier({ pkg: packageJson, updateCheckInterval: 1000 * 60 }).notify({ isGlobal: true });
updateNotifier({ pkg: packageJson, updateCheckInterval: 1000 * 60 }).notify({
isGlobal: true,
});
}

17
bin/options/icon.ts vendored
View File

@@ -19,12 +19,14 @@ export async function handleIcon(options: PakeAppOptions) {
return path.resolve(options.icon);
}
} else {
logger.warn('✼ No icon given, default in use. For a custom icon, use --icon option.');
logger.warn(
'✼ No icon given, default in use. For a custom icon, use --icon option.',
);
const iconPath = IS_WIN
? 'src-tauri/png/icon_256.ico'
: IS_LINUX
? 'src-tauri/png/icon_512.png'
: 'src-tauri/icons/icon.icns';
? 'src-tauri/png/icon_512.png'
: 'src-tauri/icons/icon.icns';
return path.join(npmDirectory, iconPath);
}
}
@@ -32,7 +34,9 @@ export async function handleIcon(options: PakeAppOptions) {
export async function downloadIcon(iconUrl: string) {
const spinner = getSpinner('Downloading icon...');
try {
const iconResponse = await axios.get(iconUrl, { responseType: 'arraybuffer' });
const iconResponse = await axios.get(iconUrl, {
responseType: 'arraybuffer',
});
const iconData = await iconResponse.data;
if (!iconData) {
@@ -49,7 +53,10 @@ export async function downloadIcon(iconUrl: string) {
// Fix this for linux
if (IS_LINUX) {
iconPath = 'png/linux_temp.png';
await fsExtra.outputFile(`${npmDirectory}/src-tauri/${iconPath}`, iconData);
await fsExtra.outputFile(
`${npmDirectory}/src-tauri/${iconPath}`,
iconData,
);
} else {
await fsExtra.outputFile(iconPath, iconData);
}

View File

@@ -20,7 +20,10 @@ function isValidName(name: string, platform: NodeJS.Platform): boolean {
return !!name && reg.test(name);
}
export default async function handleOptions(options: PakeCliOptions, url: string): Promise<PakeAppOptions> {
export default async function handleOptions(
options: PakeCliOptions,
url: string,
): Promise<PakeAppOptions> {
const { platform } = process;
const isActions = process.env.GITHUB_ACTIONS;
let name = options.name;
@@ -36,7 +39,8 @@ export default async function handleOptions(options: PakeCliOptions, url: string
if (!isValidName(name, platform)) {
const LINUX_NAME_ERROR = `✕ Name should only include lowercase letters, numbers, and dashes (not leading dashes), and must contain at least one lowercase letter or number. Examples: com-123-xxx, 123pan, pan123, weread, we-read.`;
const DEFAULT_NAME_ERROR = `✕ Name should only include letters, numbers, dashes, and spaces (not leading dashes and spaces), and must contain at least one letter or number. Examples: 123pan, 123Pan, Pan123, weread, WeRead, WERead, we-read, We Read.`;
const errorMsg = platform === 'linux' ? LINUX_NAME_ERROR : DEFAULT_NAME_ERROR;
const errorMsg =
platform === 'linux' ? LINUX_NAME_ERROR : DEFAULT_NAME_ERROR;
logger.error(errorMsg);
if (isActions) {
name = resolveAppName(url, platform);

View File

@@ -3,19 +3,19 @@ import log from 'loglevel';
const logger = {
info(...msg: any[]) {
log.info(...msg.map(m => chalk.white(m)));
log.info(...msg.map((m) => chalk.white(m)));
},
debug(...msg: any[]) {
log.debug(...msg);
},
error(...msg: any[]) {
log.error(...msg.map(m => chalk.red(m)));
log.error(...msg.map((m) => chalk.red(m)));
},
warn(...msg: any[]) {
log.info(...msg.map(m => chalk.yellow(m)));
log.info(...msg.map((m) => chalk.yellow(m)));
},
success(...msg: any[]) {
log.info(...msg.map(m => chalk.green(m)));
log.info(...msg.map((m) => chalk.green(m)));
},
};

View File

@@ -1,7 +1,7 @@
import fs from 'fs';
export default async function combineFiles(files: string[], output: string) {
const contents = files.map(file => {
const contents = files.map((file) => {
const fileContent = fs.readFileSync(file);
if (file.endsWith('.css')) {
return (
@@ -11,7 +11,11 @@ export default async function combineFiles(files: string[], output: string) {
);
}
return "window.addEventListener('DOMContentLoaded', (_event) => { " + fileContent + ' });';
return (
"window.addEventListener('DOMContentLoaded', (_event) => { " +
fileContent +
' });'
);
});
fs.writeFileSync(output, contents.join('\n'));
return files;

11
bin/utils/info.ts vendored
View File

@@ -5,11 +5,18 @@ import chalk from 'chalk';
// Generates an identifier based on the given URL.
export function getIdentifier(url: string) {
const postFixHash = crypto.createHash('md5').update(url).digest('hex').substring(0, 6);
const postFixHash = crypto
.createHash('md5')
.update(url)
.digest('hex')
.substring(0, 6);
return `com.pake.${postFixHash}`;
}
export async function promptText(message: string, initial?: string): Promise<string> {
export async function promptText(
message: string,
initial?: string,
): Promise<string> {
const response = await prompts({
type: 'text',
name: 'content',

4
bin/utils/ip.ts vendored
View File

@@ -13,13 +13,13 @@ const ping = async (host: string) => {
// Prevent timeouts from affecting user experience.
const requestPromise = new Promise<number>((resolve, reject) => {
const req = http.get(`http://${ip.address}`, res => {
const req = http.get(`http://${ip.address}`, (res) => {
const delay = new Date().getTime() - start.getTime();
res.resume();
resolve(delay);
});
req.on('error', err => {
req.on('error', (err) => {
reject(err);
});
});

6
bin/utils/shell.ts vendored
View File

@@ -5,10 +5,12 @@ export async function shellExec(command: string) {
try {
const { exitCode } = await execa(command, {
cwd: npmDirectory,
stdio: 'inherit'
stdio: 'inherit',
});
return exitCode;
} catch (error) {
throw new Error(`Error occurred while executing command "${command}". Exit code: ${error.exitCode}`);
throw new Error(
`Error occurred while executing command "${command}". Exit code: ${error.exitCode}`,
);
}
}