pake-cli 2.3.4 → 2.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -20,7 +20,7 @@ import psl from 'psl';
20
20
  import isUrl from 'is-url';
21
21
 
22
22
  var name = "pake-cli";
23
- var version = "2.3.4";
23
+ var version = "2.3.6";
24
24
  var description = "🤱🏻 Turn any webpage into a desktop app with Rust. 🤱🏻 利用 Rust 轻松构建轻量级多端桌面应用。";
25
25
  var engines = {
26
26
  node: ">=16.0.0"
@@ -67,42 +67,42 @@ var type = "module";
67
67
  var exports = "./dist/pake.js";
68
68
  var license = "MIT";
69
69
  var dependencies = {
70
- "@tauri-apps/api": "^1.4.0",
71
- "@tauri-apps/cli": "^1.4.0",
72
- axios: "^1.1.3",
73
- chalk: "^5.1.2",
74
- commander: "^11.0.0",
75
- "file-type": "^18.0.0",
76
- "fs-extra": "^11.1.0",
70
+ "@tauri-apps/api": "^1.5.1",
71
+ "@tauri-apps/cli": "^1.5.6",
72
+ axios: "^1.6.1",
73
+ chalk: "^5.3.0",
74
+ commander: "^11.1.0",
75
+ "file-type": "^18.6.0",
76
+ "fs-extra": "^11.1.1",
77
77
  "is-url": "^1.2.4",
78
78
  loglevel: "^1.8.1",
79
- ora: "^6.1.2",
79
+ ora: "^7.0.1",
80
80
  prompts: "^2.4.2",
81
81
  psl: "^1.9.0",
82
82
  shelljs: "^0.8.5",
83
83
  "tmp-promise": "^3.0.3",
84
- "update-notifier": "^6.0.2"
84
+ "update-notifier": "^7.0.0"
85
85
  };
86
86
  var devDependencies = {
87
- "@rollup/plugin-alias": "^4.0.2",
88
- "@rollup/plugin-commonjs": "^23.0.2",
89
- "@rollup/plugin-json": "^5.0.2",
90
- "@rollup/plugin-replace": "^5.0.2",
91
- "@rollup/plugin-terser": "^0.1.0",
92
- "@types/fs-extra": "^9.0.13",
93
- "@types/is-url": "^1.2.30",
94
- "@types/page-icon": "^0.3.4",
95
- "@types/prompts": "^2.4.1",
96
- "@types/psl": "^1.1.0",
97
- "@types/shelljs": "^0.8.11",
98
- "@types/tmp": "^0.2.3",
99
- "@types/update-notifier": "^6.0.1",
87
+ "@rollup/plugin-alias": "^5.0.1",
88
+ "@rollup/plugin-commonjs": "^25.0.7",
89
+ "@rollup/plugin-json": "^6.0.1",
90
+ "@rollup/plugin-replace": "^5.0.5",
91
+ "@rollup/plugin-terser": "^0.4.4",
92
+ "@types/fs-extra": "^11.0.4",
93
+ "@types/is-url": "^1.2.32",
94
+ "@types/page-icon": "^0.3.6",
95
+ "@types/prompts": "^2.4.8",
96
+ "@types/psl": "^1.1.3",
97
+ "@types/shelljs": "^0.8.15",
98
+ "@types/tmp": "^0.2.6",
99
+ "@types/update-notifier": "^6.0.7",
100
100
  "app-root-path": "^3.1.0",
101
101
  "cross-env": "^7.0.3",
102
- rollup: "^3.3.0",
103
- "rollup-plugin-typescript2": "^0.34.1",
104
- tslib: "^2.4.1",
105
- typescript: "^4.9.3"
102
+ rollup: "^4.3.0",
103
+ "rollup-plugin-typescript2": "^0.36.0",
104
+ tslib: "^2.6.2",
105
+ typescript: "^5.2.2"
106
106
  };
107
107
  var packageJson = {
108
108
  name: name,
@@ -124,7 +124,7 @@ var packageJson = {
124
124
 
125
125
  var windows = [
126
126
  {
127
- url: "https://weread.qq.com/",
127
+ url: "https://weread.qq.com",
128
128
  transparent: true,
129
129
  fullscreen: false,
130
130
  width: 1200,
@@ -307,752 +307,752 @@ var LinuxConf = {
307
307
  tauri: tauri
308
308
  };
309
309
 
310
- const platformConfigs = {
311
- win32: WinConf,
312
- darwin: MacConf,
313
- linux: LinuxConf,
314
- };
315
- const { platform: platform$2 } = process;
316
- // @ts-ignore
317
- const platformConfig = platformConfigs[platform$2];
318
- let tauriConfig = {
319
- tauri: {
320
- ...CommonConf.tauri,
321
- bundle: platformConfig.tauri.bundle,
322
- },
323
- package: CommonConf.package,
324
- build: CommonConf.build,
325
- pake: pakeConf,
310
+ const platformConfigs = {
311
+ win32: WinConf,
312
+ darwin: MacConf,
313
+ linux: LinuxConf,
314
+ };
315
+ const { platform: platform$2 } = process;
316
+ // @ts-ignore
317
+ const platformConfig = platformConfigs[platform$2];
318
+ let tauriConfig = {
319
+ tauri: {
320
+ ...CommonConf.tauri,
321
+ bundle: platformConfig.tauri.bundle,
322
+ },
323
+ package: CommonConf.package,
324
+ build: CommonConf.build,
325
+ pake: pakeConf,
326
326
  };
327
327
 
328
- // Generates an identifier based on the given URL.
329
- function getIdentifier(url) {
330
- const postFixHash = crypto.createHash('md5').update(url).digest('hex').substring(0, 6);
331
- return `com.pake.${postFixHash}`;
332
- }
333
- async function promptText(message, initial) {
334
- const response = await prompts({
335
- type: 'text',
336
- name: 'content',
337
- message,
338
- initial,
339
- });
340
- return response.content;
341
- }
342
- function capitalizeFirstLetter(string) {
343
- return string.charAt(0).toUpperCase() + string.slice(1);
344
- }
345
- function getSpinner(text) {
346
- const loadingType = {
347
- interval: 80,
348
- frames: ['✦', '✶', '✺', '✵', '✸', '✹', '✺'],
349
- };
350
- return ora({
351
- text: `${chalk.cyan(text)}\n`,
352
- spinner: loadingType,
353
- color: 'cyan',
354
- }).start();
328
+ // Generates an identifier based on the given URL.
329
+ function getIdentifier(url) {
330
+ const postFixHash = crypto.createHash('md5').update(url).digest('hex').substring(0, 6);
331
+ return `com.pake.${postFixHash}`;
332
+ }
333
+ async function promptText(message, initial) {
334
+ const response = await prompts({
335
+ type: 'text',
336
+ name: 'content',
337
+ message,
338
+ initial,
339
+ });
340
+ return response.content;
341
+ }
342
+ function capitalizeFirstLetter(string) {
343
+ return string.charAt(0).toUpperCase() + string.slice(1);
344
+ }
345
+ function getSpinner(text) {
346
+ const loadingType = {
347
+ interval: 80,
348
+ frames: ['✦', '✶', '✺', '✵', '✸', '✹', '✺'],
349
+ };
350
+ return ora({
351
+ text: `${chalk.cyan(text)}\n`,
352
+ spinner: loadingType,
353
+ color: 'cyan',
354
+ }).start();
355
355
  }
356
356
 
357
- const { platform: platform$1 } = process;
358
- const IS_MAC = platform$1 === 'darwin';
359
- const IS_WIN = platform$1 === 'win32';
357
+ const { platform: platform$1 } = process;
358
+ const IS_MAC = platform$1 === 'darwin';
359
+ const IS_WIN = platform$1 === 'win32';
360
360
  const IS_LINUX = platform$1 === 'linux';
361
361
 
362
- // Convert the current module URL to a file path
363
- const currentModulePath = fileURLToPath(import.meta.url);
364
- // Resolve the parent directory of the current module
365
- const npmDirectory = path.join(path.dirname(currentModulePath), '..');
362
+ // Convert the current module URL to a file path
363
+ const currentModulePath = fileURLToPath(import.meta.url);
364
+ // Resolve the parent directory of the current module
365
+ const npmDirectory = path.join(path.dirname(currentModulePath), '..');
366
366
  const tauriConfigDirectory = path.join(npmDirectory, 'src-tauri');
367
367
 
368
- function shellExec(command) {
369
- return new Promise((resolve, reject) => {
370
- shelljs.exec(command, { async: true, silent: false, cwd: npmDirectory }, code => {
371
- if (code === 0) {
372
- resolve(0);
373
- }
374
- else {
375
- reject(new Error(`${code}`));
376
- }
377
- });
378
- });
368
+ function shellExec(command) {
369
+ return new Promise((resolve, reject) => {
370
+ shelljs.exec(command, { async: true, silent: false, cwd: npmDirectory }, code => {
371
+ if (code === 0) {
372
+ resolve(0);
373
+ }
374
+ else {
375
+ reject(new Error(`${code}`));
376
+ }
377
+ });
378
+ });
379
379
  }
380
380
 
381
- const logger = {
382
- info(...msg) {
383
- log.info(...msg.map(m => chalk.white(m)));
384
- },
385
- debug(...msg) {
386
- log.debug(...msg);
387
- },
388
- error(...msg) {
389
- log.error(...msg.map(m => chalk.red(m)));
390
- },
391
- warn(...msg) {
392
- log.info(...msg.map(m => chalk.yellow(m)));
393
- },
394
- success(...msg) {
395
- log.info(...msg.map(m => chalk.green(m)));
396
- },
381
+ const logger = {
382
+ info(...msg) {
383
+ log.info(...msg.map(m => chalk.white(m)));
384
+ },
385
+ debug(...msg) {
386
+ log.debug(...msg);
387
+ },
388
+ error(...msg) {
389
+ log.error(...msg.map(m => chalk.red(m)));
390
+ },
391
+ warn(...msg) {
392
+ log.info(...msg.map(m => chalk.yellow(m)));
393
+ },
394
+ success(...msg) {
395
+ log.info(...msg.map(m => chalk.green(m)));
396
+ },
397
397
  };
398
398
 
399
- const resolve = promisify(dns.resolve);
400
- const ping = async (host) => {
401
- const lookup = promisify(dns.lookup);
402
- const ip = await lookup(host);
403
- const start = new Date();
404
- // Prevent timeouts from affecting user experience.
405
- const requestPromise = new Promise((resolve, reject) => {
406
- const req = http.get(`http://${ip.address}`, res => {
407
- const delay = new Date().getTime() - start.getTime();
408
- res.resume();
409
- resolve(delay);
410
- });
411
- req.on('error', err => {
412
- reject(err);
413
- });
414
- });
415
- const timeoutPromise = new Promise((_, reject) => {
416
- setTimeout(() => {
417
- reject(new Error('Request timed out after 3 seconds'));
418
- }, 1000);
419
- });
420
- return Promise.race([requestPromise, timeoutPromise]);
421
- };
422
- async function isChinaDomain(domain) {
423
- try {
424
- const [ip] = await resolve(domain);
425
- return await isChinaIP(ip, domain);
426
- }
427
- catch (error) {
428
- logger.debug(`${domain} can't be parse!`);
429
- return true;
430
- }
431
- }
432
- async function isChinaIP(ip, domain) {
433
- try {
434
- const delay = await ping(ip);
435
- logger.debug(`${domain} latency is ${delay} ms`);
436
- return delay > 1000;
437
- }
438
- catch (error) {
439
- logger.debug(`ping ${domain} failed!`);
440
- return true;
441
- }
399
+ const resolve = promisify(dns.resolve);
400
+ const ping = async (host) => {
401
+ const lookup = promisify(dns.lookup);
402
+ const ip = await lookup(host);
403
+ const start = new Date();
404
+ // Prevent timeouts from affecting user experience.
405
+ const requestPromise = new Promise((resolve, reject) => {
406
+ const req = http.get(`http://${ip.address}`, res => {
407
+ const delay = new Date().getTime() - start.getTime();
408
+ res.resume();
409
+ resolve(delay);
410
+ });
411
+ req.on('error', err => {
412
+ reject(err);
413
+ });
414
+ });
415
+ const timeoutPromise = new Promise((_, reject) => {
416
+ setTimeout(() => {
417
+ reject(new Error('Request timed out after 3 seconds'));
418
+ }, 1000);
419
+ });
420
+ return Promise.race([requestPromise, timeoutPromise]);
421
+ };
422
+ async function isChinaDomain(domain) {
423
+ try {
424
+ const [ip] = await resolve(domain);
425
+ return await isChinaIP(ip, domain);
426
+ }
427
+ catch (error) {
428
+ logger.debug(`${domain} can't be parse!`);
429
+ return true;
430
+ }
431
+ }
432
+ async function isChinaIP(ip, domain) {
433
+ try {
434
+ const delay = await ping(ip);
435
+ logger.debug(`${domain} latency is ${delay} ms`);
436
+ return delay > 1000;
437
+ }
438
+ catch (error) {
439
+ logger.debug(`ping ${domain} failed!`);
440
+ return true;
441
+ }
442
442
  }
443
443
 
444
- async function installRust() {
445
- const isActions = process.env.GITHUB_ACTIONS;
446
- const isInChina = await isChinaDomain('sh.rustup.rs');
447
- const rustInstallScriptForMac = isInChina && !isActions
448
- ? 'export RUSTUP_DIST_SERVER="https://rsproxy.cn" && export RUSTUP_UPDATE_ROOT="https://rsproxy.cn/rustup" && curl --proto "=https" --tlsv1.2 -sSf https://rsproxy.cn/rustup-init.sh | sh'
449
- : "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y";
450
- const rustInstallScriptForWindows = 'winget install --id Rustlang.Rustup';
451
- const spinner = getSpinner('Downloading Rust...');
452
- try {
453
- await shellExec(IS_WIN ? rustInstallScriptForWindows : rustInstallScriptForMac);
454
- spinner.succeed(chalk.green('Rust installed successfully!'));
455
- }
456
- catch (error) {
457
- console.error('Error installing Rust:', error.message);
458
- spinner.fail(chalk.red('Rust installation failed!'));
459
- process.exit(1);
460
- }
461
- }
462
- function checkRustInstalled() {
463
- return shelljs.exec('rustc --version', { silent: true }).code === 0;
444
+ async function installRust() {
445
+ const isActions = process.env.GITHUB_ACTIONS;
446
+ const isInChina = await isChinaDomain('sh.rustup.rs');
447
+ const rustInstallScriptForMac = isInChina && !isActions
448
+ ? 'export RUSTUP_DIST_SERVER="https://rsproxy.cn" && export RUSTUP_UPDATE_ROOT="https://rsproxy.cn/rustup" && curl --proto "=https" --tlsv1.2 -sSf https://rsproxy.cn/rustup-init.sh | sh'
449
+ : "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y";
450
+ const rustInstallScriptForWindows = 'winget install --id Rustlang.Rustup';
451
+ const spinner = getSpinner('Downloading Rust...');
452
+ try {
453
+ await shellExec(IS_WIN ? rustInstallScriptForWindows : rustInstallScriptForMac);
454
+ spinner.succeed(chalk.green('Rust installed successfully!'));
455
+ }
456
+ catch (error) {
457
+ console.error('Error installing Rust:', error.message);
458
+ spinner.fail(chalk.red('Rust installation failed!'));
459
+ process.exit(1);
460
+ }
461
+ }
462
+ function checkRustInstalled() {
463
+ return shelljs.exec('rustc --version', { silent: true }).code === 0;
464
464
  }
465
465
 
466
- async function combineFiles(files, output) {
467
- const contents = files.map(file => {
468
- const fileContent = fs.readFileSync(file);
469
- if (file.endsWith('.css')) {
470
- return "window.addEventListener('DOMContentLoaded', (_event) => { const css = `" + fileContent + "`; const style = document.createElement('style'); style.innerHTML = css; document.head.appendChild(style); });";
471
- }
472
- return "window.addEventListener('DOMContentLoaded', (_event) => { " + fileContent + " });";
473
- });
474
- fs.writeFileSync(output, contents.join('\n'));
475
- return files;
466
+ async function combineFiles(files, output) {
467
+ const contents = files.map(file => {
468
+ const fileContent = fs.readFileSync(file);
469
+ if (file.endsWith('.css')) {
470
+ return "window.addEventListener('DOMContentLoaded', (_event) => { const css = `" + fileContent + "`; const style = document.createElement('style'); style.innerHTML = css; document.head.appendChild(style); });";
471
+ }
472
+ return "window.addEventListener('DOMContentLoaded', (_event) => { " + fileContent + " });";
473
+ });
474
+ fs.writeFileSync(output, contents.join('\n'));
475
+ return files;
476
476
  }
477
477
 
478
- async function mergeConfig(url, options, tauriConf) {
479
- const { width, height, fullscreen, transparent, userAgent, showMenu, showSystemTray, systemTrayIcon, iterCopyFile, identifier, name, resizable = true, inject, safeDomain, } = options;
480
- const { platform } = process;
481
- // Set Windows parameters.
482
- const tauriConfWindowOptions = {
483
- width,
484
- height,
485
- fullscreen,
486
- transparent,
487
- resizable,
488
- };
489
- Object.assign(tauriConf.pake.windows[0], { url, ...tauriConfWindowOptions });
490
- tauriConf.package.productName = name;
491
- tauriConf.tauri.bundle.identifier = identifier;
492
- //Judge the type of URL, whether it is a file or a website.
493
- const pathExists = await fsExtra.pathExists(url);
494
- if (pathExists) {
495
- logger.warn('✼ Your input might be a local file.');
496
- tauriConf.pake.windows[0].url_type = 'local';
497
- const fileName = path.basename(url);
498
- const dirName = path.dirname(url);
499
- const distDir = path.join(npmDirectory, 'dist');
500
- const distBakDir = path.join(npmDirectory, 'dist_bak');
501
- if (!iterCopyFile) {
502
- const urlPath = path.join(distDir, fileName);
503
- await fsExtra.copy(url, urlPath);
504
- }
505
- else {
506
- fsExtra.moveSync(distDir, distBakDir, { overwrite: true });
507
- fsExtra.copySync(dirName, distDir, { overwrite: true });
508
- // ignore it, because about_pake.html have be erased.
509
- // const filesToCopyBack = ['cli.js', 'about_pake.html'];
510
- const filesToCopyBack = ['cli.js'];
511
- await Promise.all(filesToCopyBack.map(file => fsExtra.copy(path.join(distBakDir, file), path.join(distDir, file))));
512
- }
513
- tauriConf.pake.windows[0].url = fileName;
514
- tauriConf.pake.windows[0].url_type = 'local';
515
- }
516
- else {
517
- tauriConf.pake.windows[0].url_type = 'web';
518
- // Set the secure domain for calling window.__TAURI__ to the application domain that has been set.
519
- tauriConf.tauri.security.dangerousRemoteDomainIpcAccess = [
520
- {
521
- domain: new URL(url).hostname,
522
- windows: ['pake'],
523
- enableTauriAPI: true,
524
- },
525
- ];
526
- }
527
- if (safeDomain.length > 0) {
528
- tauriConf.tauri.security.dangerousRemoteDomainIpcAccess = [
529
- ...tauriConf.tauri.security.dangerousRemoteDomainIpcAccess,
530
- ...safeDomain.map(domain => ({
531
- domain,
532
- windows: ['pake'],
533
- enableTauriAPI: true,
534
- })),
535
- ];
536
- }
537
- const platformMap = {
538
- win32: 'windows',
539
- linux: 'linux',
540
- darwin: 'macos',
541
- };
542
- const currentPlatform = platformMap[platform];
543
- if (userAgent.length > 0) {
544
- tauriConf.pake.user_agent[currentPlatform] = userAgent;
545
- }
546
- tauriConf.pake.menu[currentPlatform] = showMenu;
547
- tauriConf.pake.system_tray[currentPlatform] = showSystemTray;
548
- // Processing targets are currently only open to Linux.
549
- if (platform === 'linux') {
550
- delete tauriConf.tauri.bundle.deb.files;
551
- const validTargets = ['all', 'deb', 'appimage'];
552
- if (validTargets.includes(options.targets)) {
553
- tauriConf.tauri.bundle.targets = options.targets === 'all' ? ['deb', 'appimage'] : [options.targets];
554
- }
555
- else {
556
- logger.warn(`✼ The target must be one of ${validTargets.join(', ')}, the default 'deb' will be used.`);
557
- }
558
- }
559
- // Set icon.
560
- const platformIconMap = {
561
- win32: {
562
- fileExt: '.ico',
563
- path: `png/${name.toLowerCase()}_256.ico`,
564
- defaultIcon: 'png/icon_256.ico',
565
- message: 'Windows icon must be .ico and 256x256px.',
566
- },
567
- linux: {
568
- fileExt: '.png',
569
- path: `png/${name.toLowerCase()}_512.png`,
570
- defaultIcon: 'png/icon_512.png',
571
- message: 'Linux icon must be .png and 512x512px.',
572
- },
573
- darwin: {
574
- fileExt: '.icns',
575
- path: `icons/${name.toLowerCase()}.icns`,
576
- defaultIcon: 'icons/icon.icns',
577
- message: 'macOS icon must be .icns type.',
578
- },
579
- };
580
- const iconInfo = platformIconMap[platform];
581
- const exists = await fsExtra.pathExists(options.icon);
582
- if (exists) {
583
- let updateIconPath = true;
584
- let customIconExt = path.extname(options.icon).toLowerCase();
585
- if (customIconExt !== iconInfo.fileExt) {
586
- updateIconPath = false;
587
- logger.warn(`✼ ${iconInfo.message}, but you give ${customIconExt}`);
588
- tauriConf.tauri.bundle.icon = [iconInfo.defaultIcon];
589
- }
590
- else {
591
- const iconPath = path.join(npmDirectory, 'src-tauri/', iconInfo.path);
592
- tauriConf.tauri.bundle.resources = [iconInfo.path];
593
- await fsExtra.copy(options.icon, iconPath);
594
- }
595
- if (updateIconPath) {
596
- tauriConf.tauri.bundle.icon = [options.icon];
597
- }
598
- else {
599
- logger.warn(`✼ Icon will remain as default.`);
600
- }
601
- }
602
- else {
603
- logger.warn('✼ Custom icon path may be invalid, default icon will be used instead.');
604
- tauriConf.tauri.bundle.icon = [iconInfo.defaultIcon];
605
- }
606
- // Set tray icon path.
607
- let trayIconPath = platform === 'darwin' ? 'png/icon_512.png' : tauriConf.tauri.bundle.icon[0];
608
- if (systemTrayIcon.length > 0) {
609
- try {
610
- await fsExtra.pathExists(systemTrayIcon);
611
- // 需要判断图标格式,默认只支持ico和png两种
612
- let iconExt = path.extname(systemTrayIcon).toLowerCase();
613
- if (iconExt == '.png' || iconExt == '.ico') {
614
- const trayIcoPath = path.join(npmDirectory, `src-tauri/png/${name.toLowerCase()}${iconExt}`);
615
- trayIconPath = `png/${name.toLowerCase()}${iconExt}`;
616
- await fsExtra.copy(systemTrayIcon, trayIcoPath);
617
- }
618
- else {
619
- logger.warn(`✼ System tray icon must be .ico or .png, but you provided ${iconExt}.`);
620
- logger.warn(`✼ Default system tray icon will be used.`);
621
- }
622
- }
623
- catch {
624
- logger.warn(`✼ ${systemTrayIcon} not exists!`);
625
- logger.warn(`✼ Default system tray icon will remain unchanged.`);
626
- }
627
- }
628
- tauriConf.tauri.systemTray.iconPath = trayIconPath;
629
- const injectFilePath = path.join(npmDirectory, `src-tauri/src/inject/custom.js`);
630
- // inject js or css files
631
- if (inject?.length > 0) {
632
- if (!inject.every(item => item.endsWith('.css') || item.endsWith('.js'))) {
633
- logger.error('The injected file must be in either CSS or JS format.');
634
- return;
635
- }
636
- const files = inject.map(filepath => path.isAbsolute(filepath) ? filepath : path.join(process.cwd(), filepath));
637
- tauriConf.pake.inject = files;
638
- await combineFiles(files, injectFilePath);
639
- }
640
- else {
641
- tauriConf.pake.inject = [];
642
- await fsExtra.writeFile(injectFilePath, '');
643
- }
644
- // Save config file.
645
- const platformConfigPaths = {
646
- win32: 'tauri.windows.conf.json',
647
- darwin: 'tauri.macos.conf.json',
648
- linux: 'tauri.linux.conf.json',
649
- };
650
- const configPath = path.join(tauriConfigDirectory, platformConfigPaths[platform]);
651
- const bundleConf = { tauri: { bundle: tauriConf.tauri.bundle } };
652
- await fsExtra.outputJSON(configPath, bundleConf, { spaces: 4 });
653
- const pakeConfigPath = path.join(tauriConfigDirectory, 'pake.json');
654
- await fsExtra.outputJSON(pakeConfigPath, tauriConf.pake, { spaces: 4 });
655
- let tauriConf2 = JSON.parse(JSON.stringify(tauriConf));
656
- delete tauriConf2.pake;
657
- delete tauriConf2.tauri.bundle;
658
- const configJsonPath = path.join(tauriConfigDirectory, 'tauri.conf.json');
659
- await fsExtra.outputJSON(configJsonPath, tauriConf2, { spaces: 4 });
478
+ async function mergeConfig(url, options, tauriConf) {
479
+ const { width, height, fullscreen, transparent, userAgent, showMenu, showSystemTray, systemTrayIcon, iterCopyFile, identifier, name, resizable = true, inject, safeDomain, } = options;
480
+ const { platform } = process;
481
+ // Set Windows parameters.
482
+ const tauriConfWindowOptions = {
483
+ width,
484
+ height,
485
+ fullscreen,
486
+ transparent,
487
+ resizable,
488
+ };
489
+ Object.assign(tauriConf.pake.windows[0], { url, ...tauriConfWindowOptions });
490
+ tauriConf.package.productName = name;
491
+ tauriConf.tauri.bundle.identifier = identifier;
492
+ //Judge the type of URL, whether it is a file or a website.
493
+ const pathExists = await fsExtra.pathExists(url);
494
+ if (pathExists) {
495
+ logger.warn('✼ Your input might be a local file.');
496
+ tauriConf.pake.windows[0].url_type = 'local';
497
+ const fileName = path.basename(url);
498
+ const dirName = path.dirname(url);
499
+ const distDir = path.join(npmDirectory, 'dist');
500
+ const distBakDir = path.join(npmDirectory, 'dist_bak');
501
+ if (!iterCopyFile) {
502
+ const urlPath = path.join(distDir, fileName);
503
+ await fsExtra.copy(url, urlPath);
504
+ }
505
+ else {
506
+ fsExtra.moveSync(distDir, distBakDir, { overwrite: true });
507
+ fsExtra.copySync(dirName, distDir, { overwrite: true });
508
+ // ignore it, because about_pake.html have be erased.
509
+ // const filesToCopyBack = ['cli.js', 'about_pake.html'];
510
+ const filesToCopyBack = ['cli.js'];
511
+ await Promise.all(filesToCopyBack.map(file => fsExtra.copy(path.join(distBakDir, file), path.join(distDir, file))));
512
+ }
513
+ tauriConf.pake.windows[0].url = fileName;
514
+ tauriConf.pake.windows[0].url_type = 'local';
515
+ }
516
+ else {
517
+ tauriConf.pake.windows[0].url_type = 'web';
518
+ // Set the secure domain for calling window.__TAURI__ to the application domain that has been set.
519
+ tauriConf.tauri.security.dangerousRemoteDomainIpcAccess = [
520
+ {
521
+ domain: new URL(url).hostname,
522
+ windows: ['pake'],
523
+ enableTauriAPI: true,
524
+ },
525
+ ];
526
+ }
527
+ if (safeDomain.length > 0) {
528
+ tauriConf.tauri.security.dangerousRemoteDomainIpcAccess = [
529
+ ...tauriConf.tauri.security.dangerousRemoteDomainIpcAccess,
530
+ ...safeDomain.map(domain => ({
531
+ domain,
532
+ windows: ['pake'],
533
+ enableTauriAPI: true,
534
+ })),
535
+ ];
536
+ }
537
+ const platformMap = {
538
+ win32: 'windows',
539
+ linux: 'linux',
540
+ darwin: 'macos',
541
+ };
542
+ const currentPlatform = platformMap[platform];
543
+ if (userAgent.length > 0) {
544
+ tauriConf.pake.user_agent[currentPlatform] = userAgent;
545
+ }
546
+ tauriConf.pake.menu[currentPlatform] = showMenu;
547
+ tauriConf.pake.system_tray[currentPlatform] = showSystemTray;
548
+ // Processing targets are currently only open to Linux.
549
+ if (platform === 'linux') {
550
+ delete tauriConf.tauri.bundle.deb.files;
551
+ const validTargets = ['all', 'deb', 'appimage'];
552
+ if (validTargets.includes(options.targets)) {
553
+ tauriConf.tauri.bundle.targets = options.targets === 'all' ? ['deb', 'appimage'] : [options.targets];
554
+ }
555
+ else {
556
+ logger.warn(`✼ The target must be one of ${validTargets.join(', ')}, the default 'deb' will be used.`);
557
+ }
558
+ }
559
+ // Set icon.
560
+ const platformIconMap = {
561
+ win32: {
562
+ fileExt: '.ico',
563
+ path: `png/${name.toLowerCase()}_256.ico`,
564
+ defaultIcon: 'png/icon_256.ico',
565
+ message: 'Windows icon must be .ico and 256x256px.',
566
+ },
567
+ linux: {
568
+ fileExt: '.png',
569
+ path: `png/${name.toLowerCase()}_512.png`,
570
+ defaultIcon: 'png/icon_512.png',
571
+ message: 'Linux icon must be .png and 512x512px.',
572
+ },
573
+ darwin: {
574
+ fileExt: '.icns',
575
+ path: `icons/${name.toLowerCase()}.icns`,
576
+ defaultIcon: 'icons/icon.icns',
577
+ message: 'macOS icon must be .icns type.',
578
+ },
579
+ };
580
+ const iconInfo = platformIconMap[platform];
581
+ const exists = await fsExtra.pathExists(options.icon);
582
+ if (exists) {
583
+ let updateIconPath = true;
584
+ let customIconExt = path.extname(options.icon).toLowerCase();
585
+ if (customIconExt !== iconInfo.fileExt) {
586
+ updateIconPath = false;
587
+ logger.warn(`✼ ${iconInfo.message}, but you give ${customIconExt}`);
588
+ tauriConf.tauri.bundle.icon = [iconInfo.defaultIcon];
589
+ }
590
+ else {
591
+ const iconPath = path.join(npmDirectory, 'src-tauri/', iconInfo.path);
592
+ tauriConf.tauri.bundle.resources = [iconInfo.path];
593
+ await fsExtra.copy(options.icon, iconPath);
594
+ }
595
+ if (updateIconPath) {
596
+ tauriConf.tauri.bundle.icon = [options.icon];
597
+ }
598
+ else {
599
+ logger.warn(`✼ Icon will remain as default.`);
600
+ }
601
+ }
602
+ else {
603
+ logger.warn('✼ Custom icon path may be invalid, default icon will be used instead.');
604
+ tauriConf.tauri.bundle.icon = [iconInfo.defaultIcon];
605
+ }
606
+ // Set tray icon path.
607
+ let trayIconPath = platform === 'darwin' ? 'png/icon_512.png' : tauriConf.tauri.bundle.icon[0];
608
+ if (systemTrayIcon.length > 0) {
609
+ try {
610
+ await fsExtra.pathExists(systemTrayIcon);
611
+ // 需要判断图标格式,默认只支持ico和png两种
612
+ let iconExt = path.extname(systemTrayIcon).toLowerCase();
613
+ if (iconExt == '.png' || iconExt == '.ico') {
614
+ const trayIcoPath = path.join(npmDirectory, `src-tauri/png/${name.toLowerCase()}${iconExt}`);
615
+ trayIconPath = `png/${name.toLowerCase()}${iconExt}`;
616
+ await fsExtra.copy(systemTrayIcon, trayIcoPath);
617
+ }
618
+ else {
619
+ logger.warn(`✼ System tray icon must be .ico or .png, but you provided ${iconExt}.`);
620
+ logger.warn(`✼ Default system tray icon will be used.`);
621
+ }
622
+ }
623
+ catch {
624
+ logger.warn(`✼ ${systemTrayIcon} not exists!`);
625
+ logger.warn(`✼ Default system tray icon will remain unchanged.`);
626
+ }
627
+ }
628
+ tauriConf.tauri.systemTray.iconPath = trayIconPath;
629
+ const injectFilePath = path.join(npmDirectory, `src-tauri/src/inject/custom.js`);
630
+ // inject js or css files
631
+ if (inject?.length > 0) {
632
+ if (!inject.every(item => item.endsWith('.css') || item.endsWith('.js'))) {
633
+ logger.error('The injected file must be in either CSS or JS format.');
634
+ return;
635
+ }
636
+ const files = inject.map(filepath => path.isAbsolute(filepath) ? filepath : path.join(process.cwd(), filepath));
637
+ tauriConf.pake.inject = files;
638
+ await combineFiles(files, injectFilePath);
639
+ }
640
+ else {
641
+ tauriConf.pake.inject = [];
642
+ await fsExtra.writeFile(injectFilePath, '');
643
+ }
644
+ // Save config file.
645
+ const platformConfigPaths = {
646
+ win32: 'tauri.windows.conf.json',
647
+ darwin: 'tauri.macos.conf.json',
648
+ linux: 'tauri.linux.conf.json',
649
+ };
650
+ const configPath = path.join(tauriConfigDirectory, platformConfigPaths[platform]);
651
+ const bundleConf = { tauri: { bundle: tauriConf.tauri.bundle } };
652
+ await fsExtra.outputJSON(configPath, bundleConf, { spaces: 4 });
653
+ const pakeConfigPath = path.join(tauriConfigDirectory, 'pake.json');
654
+ await fsExtra.outputJSON(pakeConfigPath, tauriConf.pake, { spaces: 4 });
655
+ let tauriConf2 = JSON.parse(JSON.stringify(tauriConf));
656
+ delete tauriConf2.pake;
657
+ delete tauriConf2.tauri.bundle;
658
+ const configJsonPath = path.join(tauriConfigDirectory, 'tauri.conf.json');
659
+ await fsExtra.outputJSON(configJsonPath, tauriConf2, { spaces: 4 });
660
660
  }
661
661
 
662
- class BaseBuilder {
663
- constructor(options) {
664
- this.options = options;
665
- }
666
- async prepare() {
667
- const tauriSrcPath = path.join(npmDirectory, 'src-tauri');
668
- const tauriTargetPath = path.join(tauriSrcPath, 'target');
669
- const tauriTargetPathExists = await fsExtra.pathExists(tauriTargetPath);
670
- if (!IS_MAC && !tauriTargetPathExists) {
671
- logger.warn('✼ The first use requires installing system dependencies.');
672
- logger.warn('✼ See more in https://tauri.app/v1/guides/getting-started/prerequisites.');
673
- }
674
- if (!checkRustInstalled()) {
675
- const res = await prompts({
676
- type: 'confirm',
677
- message: 'Rust not detected. Install now?',
678
- name: 'value',
679
- });
680
- if (res.value) {
681
- await installRust();
682
- }
683
- else {
684
- logger.error('✕ Rust required to package your webapp.');
685
- process.exit(0);
686
- }
687
- }
688
- const isChina = await isChinaDomain('www.npmjs.com');
689
- const spinner = getSpinner('Installing package...');
690
- const rustProjectDir = path.join(tauriSrcPath, '.cargo');
691
- const projectConf = path.join(rustProjectDir, 'config');
692
- await fsExtra.ensureDir(rustProjectDir);
693
- if (isChina) {
694
- logger.info('✺ Located in China, using npm/rsProxy CN mirror.');
695
- const projectCnConf = path.join(tauriSrcPath, 'rust_proxy.toml');
696
- await fsExtra.copy(projectCnConf, projectConf);
697
- await shellExec(`cd "${npmDirectory}" && npm install --registry=https://registry.npmmirror.com`);
698
- }
699
- else {
700
- await shellExec(`cd "${npmDirectory}" && npm install`);
701
- }
702
- spinner.succeed(chalk.green('Package installed!'));
703
- if (!tauriTargetPathExists) {
704
- logger.warn('✼ The first packaging may be slow, please be patient and wait, it will be faster afterwards.');
705
- }
706
- }
707
- async build(url) {
708
- await this.buildAndCopy(url, this.options.targets);
709
- }
710
- async start(url) {
711
- await mergeConfig(url, this.options, tauriConfig);
712
- }
713
- async buildAndCopy(url, target) {
714
- const { name } = this.options;
715
- await mergeConfig(url, this.options, tauriConfig);
716
- // Build app
717
- const spinner = getSpinner('Building app...');
718
- setTimeout(() => spinner.stop(), 3000);
719
- await shellExec(`cd "${npmDirectory}" && ${this.getBuildCommand()}`);
720
- // Copy app
721
- const fileName = this.getFileName();
722
- const fileType = this.getFileType(target);
723
- const appPath = this.getBuildAppPath(npmDirectory, fileName, fileType);
724
- const distPath = path.resolve(`${name}.${fileType}`);
725
- await fsExtra.copy(appPath, distPath);
726
- await fsExtra.remove(appPath);
727
- logger.success('✔ Build success!');
728
- logger.success('✔ App installer located in', distPath);
729
- }
730
- getFileType(target) {
731
- return target;
732
- }
733
- getBuildCommand() {
734
- // the debug option should support `--debug` and `--release`
735
- return this.options.debug ? 'npm run build:debug' : 'npm run build';
736
- }
737
- getBasePath() {
738
- return 'src-tauri/target/release/bundle/';
739
- }
740
- getBuildAppPath(npmDirectory, fileName, fileType) {
741
- return path.join(npmDirectory, this.getBasePath(), fileType.toLowerCase(), `${fileName}.${fileType}`);
742
- }
662
+ class BaseBuilder {
663
+ constructor(options) {
664
+ this.options = options;
665
+ }
666
+ async prepare() {
667
+ const tauriSrcPath = path.join(npmDirectory, 'src-tauri');
668
+ const tauriTargetPath = path.join(tauriSrcPath, 'target');
669
+ const tauriTargetPathExists = await fsExtra.pathExists(tauriTargetPath);
670
+ if (!IS_MAC && !tauriTargetPathExists) {
671
+ logger.warn('✼ The first use requires installing system dependencies.');
672
+ logger.warn('✼ See more in https://tauri.app/v1/guides/getting-started/prerequisites.');
673
+ }
674
+ if (!checkRustInstalled()) {
675
+ const res = await prompts({
676
+ type: 'confirm',
677
+ message: 'Rust not detected. Install now?',
678
+ name: 'value',
679
+ });
680
+ if (res.value) {
681
+ await installRust();
682
+ }
683
+ else {
684
+ logger.error('✕ Rust required to package your webapp.');
685
+ process.exit(0);
686
+ }
687
+ }
688
+ const isChina = await isChinaDomain('www.npmjs.com');
689
+ const spinner = getSpinner('Installing package...');
690
+ const rustProjectDir = path.join(tauriSrcPath, '.cargo');
691
+ const projectConf = path.join(rustProjectDir, 'config');
692
+ await fsExtra.ensureDir(rustProjectDir);
693
+ if (isChina) {
694
+ logger.info('✺ Located in China, using npm/rsProxy CN mirror.');
695
+ const projectCnConf = path.join(tauriSrcPath, 'rust_proxy.toml');
696
+ await fsExtra.copy(projectCnConf, projectConf);
697
+ await shellExec(`cd "${npmDirectory}" && npm install --registry=https://registry.npmmirror.com`);
698
+ }
699
+ else {
700
+ await shellExec(`cd "${npmDirectory}" && npm install`);
701
+ }
702
+ spinner.succeed(chalk.green('Package installed!'));
703
+ if (!tauriTargetPathExists) {
704
+ logger.warn('✼ The first packaging may be slow, please be patient and wait, it will be faster afterwards.');
705
+ }
706
+ }
707
+ async build(url) {
708
+ await this.buildAndCopy(url, this.options.targets);
709
+ }
710
+ async start(url) {
711
+ await mergeConfig(url, this.options, tauriConfig);
712
+ }
713
+ async buildAndCopy(url, target) {
714
+ const { name } = this.options;
715
+ await mergeConfig(url, this.options, tauriConfig);
716
+ // Build app
717
+ const spinner = getSpinner('Building app...');
718
+ setTimeout(() => spinner.stop(), 3000);
719
+ await shellExec(`cd "${npmDirectory}" && ${this.getBuildCommand()}`);
720
+ // Copy app
721
+ const fileName = this.getFileName();
722
+ const fileType = this.getFileType(target);
723
+ const appPath = this.getBuildAppPath(npmDirectory, fileName, fileType);
724
+ const distPath = path.resolve(`${name}.${fileType}`);
725
+ await fsExtra.copy(appPath, distPath);
726
+ await fsExtra.remove(appPath);
727
+ logger.success('✔ Build success!');
728
+ logger.success('✔ App installer located in', distPath);
729
+ }
730
+ getFileType(target) {
731
+ return target;
732
+ }
733
+ getBuildCommand() {
734
+ // the debug option should support `--debug` and `--release`
735
+ return this.options.debug ? 'npm run build:debug' : 'npm run build';
736
+ }
737
+ getBasePath() {
738
+ return 'src-tauri/target/release/bundle/';
739
+ }
740
+ getBuildAppPath(npmDirectory, fileName, fileType) {
741
+ return path.join(npmDirectory, this.getBasePath(), fileType.toLowerCase(), `${fileName}.${fileType}`);
742
+ }
743
743
  }
744
744
 
745
- class MacBuilder extends BaseBuilder {
746
- constructor(options) {
747
- super(options);
748
- this.options.targets = 'dmg';
749
- }
750
- getFileName() {
751
- const { name } = this.options;
752
- let arch;
753
- if (this.options.multiArch) {
754
- arch = 'universal';
755
- }
756
- else {
757
- arch = process.arch === 'arm64' ? 'aarch64' : process.arch;
758
- }
759
- return `${name}_${tauriConfig.package.version}_${arch}`;
760
- }
761
- getBuildCommand() {
762
- return this.options.multiArch ? 'npm run build:mac' : super.getBuildCommand();
763
- }
764
- getBasePath() {
765
- return this.options.multiArch
766
- ? 'src-tauri/target/universal-apple-darwin/release/bundle'
767
- : super.getBasePath();
768
- }
745
+ class MacBuilder extends BaseBuilder {
746
+ constructor(options) {
747
+ super(options);
748
+ this.options.targets = 'dmg';
749
+ }
750
+ getFileName() {
751
+ const { name } = this.options;
752
+ let arch;
753
+ if (this.options.multiArch) {
754
+ arch = 'universal';
755
+ }
756
+ else {
757
+ arch = process.arch === 'arm64' ? 'aarch64' : process.arch;
758
+ }
759
+ return `${name}_${tauriConfig.package.version}_${arch}`;
760
+ }
761
+ getBuildCommand() {
762
+ return this.options.multiArch ? 'npm run build:mac' : super.getBuildCommand();
763
+ }
764
+ getBasePath() {
765
+ return this.options.multiArch
766
+ ? 'src-tauri/target/universal-apple-darwin/release/bundle'
767
+ : super.getBasePath();
768
+ }
769
769
  }
770
770
 
771
- class WinBuilder extends BaseBuilder {
772
- constructor(options) {
773
- super(options);
774
- this.options.targets = 'msi';
775
- }
776
- getFileName() {
777
- const { name } = this.options;
778
- const { arch } = process;
779
- const language = tauriConfig.tauri.bundle.windows.wix.language[0];
780
- return `${name}_${tauriConfig.package.version}_${arch}_${language}`;
781
- }
771
+ class WinBuilder extends BaseBuilder {
772
+ constructor(options) {
773
+ super(options);
774
+ this.options.targets = 'msi';
775
+ }
776
+ getFileName() {
777
+ const { name } = this.options;
778
+ const { arch } = process;
779
+ const language = tauriConfig.tauri.bundle.windows.wix.language[0];
780
+ return `${name}_${tauriConfig.package.version}_${arch}_${language}`;
781
+ }
782
782
  }
783
783
 
784
- class LinuxBuilder extends BaseBuilder {
785
- constructor(options) {
786
- super(options);
787
- }
788
- getFileName() {
789
- const { name } = this.options;
790
- const arch = process.arch === 'x64' ? 'amd64' : process.arch;
791
- return `${name}_${tauriConfig.package.version}_${arch}`;
792
- }
793
- // Customize it, considering that there are all targets.
794
- async build(url) {
795
- const targetTypes = ['deb', 'appimage'];
796
- for (const target of targetTypes) {
797
- if (this.options.targets === target || this.options.targets === 'all') {
798
- await this.buildAndCopy(url, target);
799
- }
800
- }
801
- }
802
- getFileType(target) {
803
- if (target === 'appimage') {
804
- return 'AppImage';
805
- }
806
- return super.getFileType(target);
807
- }
784
+ class LinuxBuilder extends BaseBuilder {
785
+ constructor(options) {
786
+ super(options);
787
+ }
788
+ getFileName() {
789
+ const { name } = this.options;
790
+ const arch = process.arch === 'x64' ? 'amd64' : process.arch;
791
+ return `${name}_${tauriConfig.package.version}_${arch}`;
792
+ }
793
+ // Customize it, considering that there are all targets.
794
+ async build(url) {
795
+ const targetTypes = ['deb', 'appimage'];
796
+ for (const target of targetTypes) {
797
+ if (this.options.targets === target || this.options.targets === 'all') {
798
+ await this.buildAndCopy(url, target);
799
+ }
800
+ }
801
+ }
802
+ getFileType(target) {
803
+ if (target === 'appimage') {
804
+ return 'AppImage';
805
+ }
806
+ return super.getFileType(target);
807
+ }
808
808
  }
809
809
 
810
- const { platform } = process;
811
- const buildersMap = {
812
- darwin: MacBuilder,
813
- win32: WinBuilder,
814
- linux: LinuxBuilder,
815
- };
816
- class BuilderProvider {
817
- static create(options) {
818
- const Builder = buildersMap[platform];
819
- if (!Builder) {
820
- throw new Error('The current system is not supported!');
821
- }
822
- return new Builder(options);
823
- }
810
+ const { platform } = process;
811
+ const buildersMap = {
812
+ darwin: MacBuilder,
813
+ win32: WinBuilder,
814
+ linux: LinuxBuilder,
815
+ };
816
+ class BuilderProvider {
817
+ static create(options) {
818
+ const Builder = buildersMap[platform];
819
+ if (!Builder) {
820
+ throw new Error('The current system is not supported!');
821
+ }
822
+ return new Builder(options);
823
+ }
824
824
  }
825
825
 
826
- const DEFAULT_PAKE_OPTIONS = {
827
- icon: '',
828
- height: 780,
829
- width: 1200,
830
- fullscreen: false,
831
- resizable: true,
832
- transparent: false,
833
- userAgent: '',
834
- showMenu: false,
835
- showSystemTray: false,
836
- multiArch: false,
837
- targets: 'deb',
838
- iterCopyFile: false,
839
- systemTrayIcon: '',
840
- debug: false,
841
- inject: [],
842
- safeDomain: [],
826
+ const DEFAULT_PAKE_OPTIONS = {
827
+ icon: '',
828
+ height: 780,
829
+ width: 1200,
830
+ fullscreen: false,
831
+ resizable: true,
832
+ transparent: false,
833
+ userAgent: '',
834
+ showMenu: false,
835
+ showSystemTray: false,
836
+ multiArch: false,
837
+ targets: 'deb',
838
+ iterCopyFile: false,
839
+ systemTrayIcon: '',
840
+ debug: false,
841
+ inject: [],
842
+ safeDomain: [],
843
843
  };
844
844
 
845
- async function checkUpdateTips() {
846
- updateNotifier({ pkg: packageJson, updateCheckInterval: 1000 * 60 }).notify({ isGlobal: true });
845
+ async function checkUpdateTips() {
846
+ updateNotifier({ pkg: packageJson, updateCheckInterval: 1000 * 60 }).notify({ isGlobal: true });
847
847
  }
848
848
 
849
- async function handleIcon(options) {
850
- if (options.icon) {
851
- if (options.icon.startsWith('http')) {
852
- return downloadIcon(options.icon);
853
- }
854
- else {
855
- return path.resolve(options.icon);
856
- }
857
- }
858
- else {
859
- logger.warn('✼ No icon given, default in use. For a custom icon, use --icon option.');
860
- const iconPath = IS_WIN
861
- ? 'src-tauri/png/icon_256.ico'
862
- : IS_LINUX
863
- ? 'src-tauri/png/icon_512.png'
864
- : 'src-tauri/icons/icon.icns';
865
- return path.join(npmDirectory, iconPath);
866
- }
867
- }
868
- async function downloadIcon(iconUrl) {
869
- const spinner = getSpinner('Downloading icon...');
870
- try {
871
- const iconResponse = await axios.get(iconUrl, { responseType: 'arraybuffer' });
872
- const iconData = await iconResponse.data;
873
- if (!iconData) {
874
- return null;
875
- }
876
- const fileDetails = await fileTypeFromBuffer(iconData);
877
- if (!fileDetails) {
878
- return null;
879
- }
880
- const { path: tempPath } = await dir();
881
- let iconPath = `${tempPath}/icon.${fileDetails.ext}`;
882
- // Fix this for linux
883
- if (IS_LINUX) {
884
- iconPath = 'png/linux_temp.png';
885
- await fsExtra.outputFile(`${npmDirectory}/src-tauri/${iconPath}`, iconData);
886
- }
887
- else {
888
- await fsExtra.outputFile(iconPath, iconData);
889
- }
890
- await fsExtra.outputFile(iconPath, iconData);
891
- spinner.succeed(chalk.green('Icon downloaded successfully!'));
892
- return iconPath;
893
- }
894
- catch (error) {
895
- spinner.fail(chalk.red('Icon download failed!'));
896
- if (error.response && error.response.status === 404) {
897
- return null;
898
- }
899
- throw error;
900
- }
849
+ async function handleIcon(options) {
850
+ if (options.icon) {
851
+ if (options.icon.startsWith('http')) {
852
+ return downloadIcon(options.icon);
853
+ }
854
+ else {
855
+ return path.resolve(options.icon);
856
+ }
857
+ }
858
+ else {
859
+ logger.warn('✼ No icon given, default in use. For a custom icon, use --icon option.');
860
+ const iconPath = IS_WIN
861
+ ? 'src-tauri/png/icon_256.ico'
862
+ : IS_LINUX
863
+ ? 'src-tauri/png/icon_512.png'
864
+ : 'src-tauri/icons/icon.icns';
865
+ return path.join(npmDirectory, iconPath);
866
+ }
867
+ }
868
+ async function downloadIcon(iconUrl) {
869
+ const spinner = getSpinner('Downloading icon...');
870
+ try {
871
+ const iconResponse = await axios.get(iconUrl, { responseType: 'arraybuffer' });
872
+ const iconData = await iconResponse.data;
873
+ if (!iconData) {
874
+ return null;
875
+ }
876
+ const fileDetails = await fileTypeFromBuffer(iconData);
877
+ if (!fileDetails) {
878
+ return null;
879
+ }
880
+ const { path: tempPath } = await dir();
881
+ let iconPath = `${tempPath}/icon.${fileDetails.ext}`;
882
+ // Fix this for linux
883
+ if (IS_LINUX) {
884
+ iconPath = 'png/linux_temp.png';
885
+ await fsExtra.outputFile(`${npmDirectory}/src-tauri/${iconPath}`, iconData);
886
+ }
887
+ else {
888
+ await fsExtra.outputFile(iconPath, iconData);
889
+ }
890
+ await fsExtra.outputFile(iconPath, iconData);
891
+ spinner.succeed(chalk.green('Icon downloaded successfully!'));
892
+ return iconPath;
893
+ }
894
+ catch (error) {
895
+ spinner.fail(chalk.red('Icon download failed!'));
896
+ if (error.response && error.response.status === 404) {
897
+ return null;
898
+ }
899
+ throw error;
900
+ }
901
901
  }
902
902
 
903
- // Extracts the domain from a given URL.
904
- function getDomain(inputUrl) {
905
- try {
906
- const url = new URL(inputUrl);
907
- // Use PSL to parse domain names.
908
- const parsed = psl.parse(url.hostname);
909
- // If domain is available, split it and return the SLD.
910
- if ('domain' in parsed && parsed.domain) {
911
- return parsed.domain.split('.')[0];
912
- }
913
- else {
914
- return null;
915
- }
916
- }
917
- catch (error) {
918
- return null;
919
- }
920
- }
921
- // Appends 'https://' protocol to the URL if not present.
922
- function appendProtocol(inputUrl) {
923
- try {
924
- new URL(inputUrl);
925
- return inputUrl;
926
- }
927
- catch {
928
- return `https://${inputUrl}`;
929
- }
930
- }
931
- // Normalizes the URL by ensuring it has a protocol and is valid.
932
- function normalizeUrl(urlToNormalize) {
933
- const urlWithProtocol = appendProtocol(urlToNormalize);
934
- if (isUrl(urlWithProtocol)) {
935
- return urlWithProtocol;
936
- }
937
- else {
938
- throw new Error(`Your url "${urlWithProtocol}" is invalid`);
939
- }
903
+ // Extracts the domain from a given URL.
904
+ function getDomain(inputUrl) {
905
+ try {
906
+ const url = new URL(inputUrl);
907
+ // Use PSL to parse domain names.
908
+ const parsed = psl.parse(url.hostname);
909
+ // If domain is available, split it and return the SLD.
910
+ if ('domain' in parsed && parsed.domain) {
911
+ return parsed.domain.split('.')[0];
912
+ }
913
+ else {
914
+ return null;
915
+ }
916
+ }
917
+ catch (error) {
918
+ return null;
919
+ }
920
+ }
921
+ // Appends 'https://' protocol to the URL if not present.
922
+ function appendProtocol(inputUrl) {
923
+ try {
924
+ new URL(inputUrl);
925
+ return inputUrl;
926
+ }
927
+ catch {
928
+ return `https://${inputUrl}`;
929
+ }
930
+ }
931
+ // Normalizes the URL by ensuring it has a protocol and is valid.
932
+ function normalizeUrl(urlToNormalize) {
933
+ const urlWithProtocol = appendProtocol(urlToNormalize);
934
+ if (isUrl(urlWithProtocol)) {
935
+ return urlWithProtocol;
936
+ }
937
+ else {
938
+ throw new Error(`Your url "${urlWithProtocol}" is invalid`);
939
+ }
940
940
  }
941
941
 
942
- function resolveAppName(name, platform) {
943
- const domain = getDomain(name) || 'pake';
944
- return platform !== 'linux' ? capitalizeFirstLetter(domain) : domain;
945
- }
946
- function isValidName(name, platform) {
947
- const platformRegexMapping = {
948
- linux: /^[a-z0-9]+(-[a-z0-9]+)*$/,
949
- default: /^[a-zA-Z0-9]+$/,
950
- };
951
- const reg = platformRegexMapping[platform] || platformRegexMapping.default;
952
- return !!name && reg.test(name);
953
- }
954
- async function handleOptions(options, url) {
955
- const { platform } = process;
956
- const isActions = process.env.GITHUB_ACTIONS;
957
- let name = options.name;
958
- const pathExists = await fsExtra.pathExists(url);
959
- if (!options.name) {
960
- const defaultName = pathExists ? '' : resolveAppName(url, platform);
961
- const promptMessage = 'Enter your application name';
962
- const namePrompt = await promptText(promptMessage, defaultName);
963
- name = namePrompt || defaultName;
964
- }
965
- if (!isValidName(name, platform)) {
966
- const LINUX_NAME_ERROR = `✕ name should only include lowercase letters, numbers, and dashes, and must contain at least one lowercase letter. Examples: com-123-xxx, 123pan, pan123, weread, we-read.`;
967
- const DEFAULT_NAME_ERROR = `✕ Name should only include letters and numbers, and must contain at least one letter. Examples: 123pan, 123Pan, Pan123, weread, WeRead, WERead.`;
968
- const errorMsg = platform === 'linux' ? LINUX_NAME_ERROR : DEFAULT_NAME_ERROR;
969
- logger.error(errorMsg);
970
- if (isActions) {
971
- name = resolveAppName(url, platform);
972
- logger.warn(`✼ Inside github actions, use the default name: ${name}`);
973
- }
974
- else {
975
- process.exit(1);
976
- }
977
- }
978
- const appOptions = {
979
- ...options,
980
- name,
981
- identifier: getIdentifier(url),
982
- };
983
- appOptions.icon = await handleIcon(appOptions);
984
- return appOptions;
942
+ function resolveAppName(name, platform) {
943
+ const domain = getDomain(name) || 'pake';
944
+ return platform !== 'linux' ? capitalizeFirstLetter(domain) : domain;
945
+ }
946
+ function isValidName(name, platform) {
947
+ const platformRegexMapping = {
948
+ linux: /^[a-z0-9]+(-[a-z0-9]+)*$/,
949
+ default: /^[a-zA-Z0-9]+$/,
950
+ };
951
+ const reg = platformRegexMapping[platform] || platformRegexMapping.default;
952
+ return !!name && reg.test(name);
953
+ }
954
+ async function handleOptions(options, url) {
955
+ const { platform } = process;
956
+ const isActions = process.env.GITHUB_ACTIONS;
957
+ let name = options.name;
958
+ const pathExists = await fsExtra.pathExists(url);
959
+ if (!options.name) {
960
+ const defaultName = pathExists ? '' : resolveAppName(url, platform);
961
+ const promptMessage = 'Enter your application name';
962
+ const namePrompt = await promptText(promptMessage, defaultName);
963
+ name = namePrompt || defaultName;
964
+ }
965
+ if (!isValidName(name, platform)) {
966
+ const LINUX_NAME_ERROR = `✕ name should only include lowercase letters, numbers, and dashes, and must contain at least one lowercase letter. Examples: com-123-xxx, 123pan, pan123, weread, we-read.`;
967
+ const DEFAULT_NAME_ERROR = `✕ Name should only include letters and numbers, and must contain at least one letter. Examples: 123pan, 123Pan, Pan123, weread, WeRead, WERead.`;
968
+ const errorMsg = platform === 'linux' ? LINUX_NAME_ERROR : DEFAULT_NAME_ERROR;
969
+ logger.error(errorMsg);
970
+ if (isActions) {
971
+ name = resolveAppName(url, platform);
972
+ logger.warn(`✼ Inside github actions, use the default name: ${name}`);
973
+ }
974
+ else {
975
+ process.exit(1);
976
+ }
977
+ }
978
+ const appOptions = {
979
+ ...options,
980
+ name,
981
+ identifier: getIdentifier(url),
982
+ };
983
+ appOptions.icon = await handleIcon(appOptions);
984
+ return appOptions;
985
985
  }
986
986
 
987
- function validateNumberInput(value) {
988
- const parsedValue = Number(value);
989
- if (isNaN(parsedValue)) {
990
- throw new InvalidArgumentError('Not a number.');
991
- }
992
- return parsedValue;
993
- }
994
- function validateUrlInput(url) {
995
- const isFile = fs.existsSync(url);
996
- if (!isFile) {
997
- try {
998
- return normalizeUrl(url);
999
- }
1000
- catch (error) {
1001
- throw new InvalidArgumentError(error.message);
1002
- }
1003
- }
1004
- return url;
987
+ function validateNumberInput(value) {
988
+ const parsedValue = Number(value);
989
+ if (isNaN(parsedValue)) {
990
+ throw new InvalidArgumentError('Not a number.');
991
+ }
992
+ return parsedValue;
993
+ }
994
+ function validateUrlInput(url) {
995
+ const isFile = fs.existsSync(url);
996
+ if (!isFile) {
997
+ try {
998
+ return normalizeUrl(url);
999
+ }
1000
+ catch (error) {
1001
+ throw new InvalidArgumentError(error.message);
1002
+ }
1003
+ }
1004
+ return url;
1005
1005
  }
1006
1006
 
1007
- const { green, yellow } = chalk;
1007
+ const { green, yellow } = chalk;
1008
1008
  const logo = `${chalk.green(' ____ _')}
1009
1009
  ${green('| _ \\ __ _| | _____')}
1010
1010
  ${green('| |_) / _` | |/ / _ \\')}
1011
1011
  ${green('| __/ (_| | < __/')} ${yellow('https://github.com/tw93/pake')}
1012
1012
  ${green('|_| \\__,_|_|\\_\\___| can turn any webpage into a desktop app with Rust.')}
1013
- `;
1014
- program
1015
- .addHelpText('beforeAll', logo)
1016
- .usage(`[url] [options]`)
1017
- .showHelpAfterError();
1018
- program
1019
- .argument('[url]', 'The web URL you want to package', validateUrlInput)
1020
- .option('--name <string>', 'Application name')
1021
- .option('--icon <string>', 'Application icon', DEFAULT_PAKE_OPTIONS.icon)
1022
- .option('--width <number>', 'Window width', validateNumberInput, DEFAULT_PAKE_OPTIONS.width)
1023
- .option('--height <number>', 'Window height', validateNumberInput, DEFAULT_PAKE_OPTIONS.height)
1024
- .option('--transparent', 'Only for Mac, hide title bar', DEFAULT_PAKE_OPTIONS.transparent)
1025
- .option('--fullscreen', 'Start in full screen', DEFAULT_PAKE_OPTIONS.fullscreen)
1026
- .option('--user-agent <string>', 'Custom user agent', DEFAULT_PAKE_OPTIONS.userAgent)
1027
- .option('--show-menu', 'Show menu in app', DEFAULT_PAKE_OPTIONS.showMenu)
1028
- .option('--show-system-tray', 'Show system tray in app', DEFAULT_PAKE_OPTIONS.showSystemTray)
1029
- .option('--system-tray-icon <string>', 'Custom system tray icon', DEFAULT_PAKE_OPTIONS.systemTrayIcon)
1030
- .option('--iter-copy-file', 'Copy files when URL is a local file', DEFAULT_PAKE_OPTIONS.iterCopyFile)
1031
- .option('--multi-arch', 'Only for Mac, supports both Intel and M1', DEFAULT_PAKE_OPTIONS.multiArch)
1032
- .option('--targets <string>', 'Only for Linux, option "deb" or "appimage"', DEFAULT_PAKE_OPTIONS.targets)
1033
- .option('--inject [injects...]', 'Injection of .js or .css Files', DEFAULT_PAKE_OPTIONS.inject)
1034
- .option('--safe-domain [domains...]', 'Domains that Require Security Configuration"', DEFAULT_PAKE_OPTIONS.safeDomain)
1035
- .option('--debug', 'Debug mode', DEFAULT_PAKE_OPTIONS.debug)
1036
- .version(packageJson.version, '-v, --version', 'Output the current version')
1037
- .action(async (url, options) => {
1038
- await checkUpdateTips();
1039
- if (!url) {
1040
- program.outputHelp(str => {
1041
- return str
1042
- .split('\n')
1043
- .filter(line => !/((-h,|--help)|((-v|-V),|--version))\s+.+$/.test(line))
1044
- .join('\n');
1045
- });
1046
- process.exit(0);
1047
- }
1048
- log.setDefaultLevel('info');
1049
- if (options.debug) {
1050
- log.setLevel('debug');
1051
- }
1052
- const appOptions = await handleOptions(options, url);
1053
- log.debug('PakeAppOptions', appOptions);
1054
- const builder = BuilderProvider.create(appOptions);
1055
- await builder.prepare();
1056
- await builder.build(url);
1057
- });
1013
+ `;
1014
+ program
1015
+ .addHelpText('beforeAll', logo)
1016
+ .usage(`[url] [options]`)
1017
+ .showHelpAfterError();
1018
+ program
1019
+ .argument('[url]', 'The web URL you want to package', validateUrlInput)
1020
+ .option('--name <string>', 'Application name')
1021
+ .option('--icon <string>', 'Application icon', DEFAULT_PAKE_OPTIONS.icon)
1022
+ .option('--width <number>', 'Window width', validateNumberInput, DEFAULT_PAKE_OPTIONS.width)
1023
+ .option('--height <number>', 'Window height', validateNumberInput, DEFAULT_PAKE_OPTIONS.height)
1024
+ .option('--transparent', 'Only for Mac, hide title bar', DEFAULT_PAKE_OPTIONS.transparent)
1025
+ .option('--fullscreen', 'Start in full screen', DEFAULT_PAKE_OPTIONS.fullscreen)
1026
+ .option('--user-agent <string>', 'Custom user agent', DEFAULT_PAKE_OPTIONS.userAgent)
1027
+ .option('--show-menu', 'Show menu in app', DEFAULT_PAKE_OPTIONS.showMenu)
1028
+ .option('--show-system-tray', 'Show system tray in app', DEFAULT_PAKE_OPTIONS.showSystemTray)
1029
+ .option('--system-tray-icon <string>', 'Custom system tray icon', DEFAULT_PAKE_OPTIONS.systemTrayIcon)
1030
+ .option('--iter-copy-file', 'Copy files when URL is a local file', DEFAULT_PAKE_OPTIONS.iterCopyFile)
1031
+ .option('--multi-arch', 'Only for Mac, supports both Intel and M1', DEFAULT_PAKE_OPTIONS.multiArch)
1032
+ .option('--targets <string>', 'Only for Linux, option "deb" or "appimage"', DEFAULT_PAKE_OPTIONS.targets)
1033
+ .option('--inject [injects...]', 'Injection of .js or .css Files', DEFAULT_PAKE_OPTIONS.inject)
1034
+ .option('--safe-domain [domains...]', 'Domains that Require Security Configuration"', DEFAULT_PAKE_OPTIONS.safeDomain)
1035
+ .option('--debug', 'Debug mode', DEFAULT_PAKE_OPTIONS.debug)
1036
+ .version(packageJson.version, '-v, --version', 'Output the current version')
1037
+ .action(async (url, options) => {
1038
+ await checkUpdateTips();
1039
+ if (!url) {
1040
+ program.outputHelp(str => {
1041
+ return str
1042
+ .split('\n')
1043
+ .filter(line => !/((-h,|--help)|((-v|-V),|--version))\s+.+$/.test(line))
1044
+ .join('\n');
1045
+ });
1046
+ process.exit(0);
1047
+ }
1048
+ log.setDefaultLevel('info');
1049
+ if (options.debug) {
1050
+ log.setLevel('debug');
1051
+ }
1052
+ const appOptions = await handleOptions(options, url);
1053
+ log.debug('PakeAppOptions', appOptions);
1054
+ const builder = BuilderProvider.create(appOptions);
1055
+ await builder.prepare();
1056
+ await builder.build(url);
1057
+ });
1058
1058
  program.parse();