pake-cli 2.2.5 โ†’ 2.3.0

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.dev.js DELETED
@@ -1,1055 +0,0 @@
1
- import chalk from 'chalk';
2
- import { InvalidArgumentError, program } from 'commander';
3
- import log from 'loglevel';
4
- import path from 'path';
5
- import fsExtra from 'fs-extra';
6
- import prompts from 'prompts';
7
- import shelljs from 'shelljs';
8
- import crypto from 'crypto';
9
- import ora from 'ora';
10
- import { fileURLToPath } from 'url';
11
- import dns from 'dns';
12
- import http from 'http';
13
- import { promisify } from 'util';
14
- import fs from 'fs';
15
- import updateNotifier from 'update-notifier';
16
- import axios from 'axios';
17
- import { dir } from 'tmp-promise';
18
- import { fileTypeFromBuffer } from 'file-type';
19
- import psl from 'psl';
20
- import isUrl from 'is-url';
21
-
22
- var name = "pake-cli";
23
- var version = "2.1.12";
24
- var description = "๐Ÿคฑ๐Ÿป Turn any webpage into a desktop app with Rust. ๐Ÿคฑ๐Ÿป ๅพˆ็ฎ€ๅ•็š„็”จ Rust ๆ‰“ๅŒ…็ฝ‘้กต็”Ÿๆˆๅพˆๅฐ็š„ๆกŒ้ข Appใ€‚";
25
- var engines = {
26
- node: ">=16.0.0"
27
- };
28
- var bin = {
29
- pake: "./cli.js"
30
- };
31
- var repository = {
32
- type: "git",
33
- url: "https://github.com/tw93/pake.git"
34
- };
35
- var author = {
36
- name: "Tw93",
37
- email: "tw93@qq.com"
38
- };
39
- var keywords = [
40
- "pake",
41
- "pake-cli",
42
- "rust",
43
- "tauri",
44
- "no-electron",
45
- "productivity"
46
- ];
47
- var files = [
48
- "dist",
49
- "src-tauri",
50
- "cli.js"
51
- ];
52
- var scripts = {
53
- start: "npm run dev",
54
- dev: "npm run tauri dev",
55
- build: "npm run tauri build --release",
56
- "build:debug": "npm run tauri build -- --debug",
57
- "build:mac": "npm run tauri build -- --target universal-apple-darwin",
58
- "build:all-unix": "chmod +x ./script/build.sh && ./script/build.sh",
59
- "build:all-windows": "pwsh ./script/build.ps1",
60
- analyze: "cd src-tauri && cargo bloat --release --crates",
61
- tauri: "tauri",
62
- cli: "cross-env NODE_ENV=development rollup -cw",
63
- "cli:build": "cross-env NODE_ENV=production rollup -c",
64
- prepublishOnly: "npm run cli:build"
65
- };
66
- var type = "module";
67
- var exports = "./dist/pake.js";
68
- var license = "MIT";
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",
77
- "is-url": "^1.2.4",
78
- loglevel: "^1.8.1",
79
- ora: "^6.1.2",
80
- prompts: "^2.4.2",
81
- psl: "^1.9.0",
82
- shelljs: "^0.8.5",
83
- "tmp-promise": "^3.0.3",
84
- "update-notifier": "^6.0.2"
85
- };
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-terser": "^0.1.0",
91
- "@types/fs-extra": "^9.0.13",
92
- "@types/is-url": "^1.2.30",
93
- "@types/page-icon": "^0.3.4",
94
- "@types/prompts": "^2.4.1",
95
- "@types/psl": "^1.1.0",
96
- "@types/shelljs": "^0.8.11",
97
- "@types/tmp": "^0.2.3",
98
- "@types/update-notifier": "^6.0.1",
99
- "app-root-path": "^3.1.0",
100
- "cross-env": "^7.0.3",
101
- rollup: "^3.3.0",
102
- "rollup-plugin-typescript2": "^0.34.1",
103
- tslib: "^2.4.1",
104
- typescript: "^4.9.3"
105
- };
106
- var packageJson = {
107
- name: name,
108
- version: version,
109
- description: description,
110
- engines: engines,
111
- bin: bin,
112
- repository: repository,
113
- author: author,
114
- keywords: keywords,
115
- files: files,
116
- scripts: scripts,
117
- type: type,
118
- exports: exports,
119
- license: license,
120
- dependencies: dependencies,
121
- devDependencies: devDependencies
122
- };
123
-
124
- var windows = [
125
- {
126
- url: "https://zbook.lol/",
127
- transparent: true,
128
- fullscreen: false,
129
- width: 1200,
130
- height: 780,
131
- resizable: true,
132
- url_type: "web"
133
- }
134
- ];
135
- var user_agent = {
136
- macos: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Safari/605.1.15",
137
- linux: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36",
138
- windows: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"
139
- };
140
- var menu = {
141
- macos: false,
142
- linux: false,
143
- windows: false
144
- };
145
- var system_tray = {
146
- macos: false,
147
- linux: true,
148
- windows: true
149
- };
150
- var inject = [
151
- "/Users/guyifeng/workspace/seeyon/pake-patch/index.js",
152
- "/Users/guyifeng/workspace/seeyon/pake-patch/index.css"
153
- ];
154
- var pakeConf = {
155
- windows: windows,
156
- user_agent: user_agent,
157
- menu: menu,
158
- system_tray: system_tray,
159
- inject: inject
160
- };
161
-
162
- var tauri$3 = {
163
- security: {
164
- csp: null,
165
- dangerousRemoteDomainIpcAccess: [
166
- {
167
- domain: "zbook.lol",
168
- windows: [
169
- "pake"
170
- ],
171
- enableTauriAPI: true
172
- },
173
- {
174
- domain: "zbook.eu.org",
175
- windows: [
176
- "pake"
177
- ],
178
- enableTauriAPI: true
179
- }
180
- ]
181
- },
182
- updater: {
183
- active: false
184
- },
185
- systemTray: {
186
- iconPath: "png/icon_512.png",
187
- iconAsTemplate: true
188
- },
189
- allowlist: {
190
- all: true,
191
- fs: {
192
- all: true,
193
- scope: [
194
- "$DOWNLOAD/*"
195
- ]
196
- }
197
- }
198
- };
199
- var build = {
200
- withGlobalTauri: true,
201
- devPath: "../dist",
202
- distDir: "../dist",
203
- beforeBuildCommand: "",
204
- beforeDevCommand: ""
205
- };
206
- var CommonConf = {
207
- tauri: tauri$3,
208
- "package": {
209
- productName: "zBook",
210
- version: "1.0.0"
211
- },
212
- build: build
213
- };
214
-
215
- var tauri$2 = {
216
- bundle: {
217
- icon: [
218
- "png/weread_256.ico",
219
- "png/weread_32.ico"
220
- ],
221
- identifier: "com.pake.weread",
222
- active: true,
223
- category: "DeveloperTool",
224
- copyright: "",
225
- externalBin: [
226
- ],
227
- longDescription: "",
228
- resources: [
229
- "png/weread_32.ico"
230
- ],
231
- shortDescription: "",
232
- targets: [
233
- "msi"
234
- ],
235
- windows: {
236
- certificateThumbprint: null,
237
- digestAlgorithm: "sha256",
238
- timestampUrl: "",
239
- wix: {
240
- language: [
241
- "en-US"
242
- ],
243
- template: "assets/main.wxs"
244
- }
245
- }
246
- }
247
- };
248
- var WinConf = {
249
- tauri: tauri$2
250
- };
251
-
252
- var tauri$1 = {
253
- bundle: {
254
- icon: [
255
- "icons/weread.icns"
256
- ],
257
- identifier: "com.pake.weread",
258
- active: true,
259
- category: "DeveloperTool",
260
- copyright: "",
261
- externalBin: [
262
- ],
263
- longDescription: "",
264
- macOS: {
265
- entitlements: null,
266
- exceptionDomain: "",
267
- frameworks: [
268
- ],
269
- providerShortName: null,
270
- signingIdentity: null
271
- },
272
- resources: [
273
- ],
274
- shortDescription: "",
275
- targets: [
276
- "dmg"
277
- ]
278
- }
279
- };
280
- var MacConf = {
281
- tauri: tauri$1
282
- };
283
-
284
- var tauri = {
285
- bundle: {
286
- icon: [
287
- "png/weread_512.png"
288
- ],
289
- identifier: "com.pake.weread",
290
- active: true,
291
- category: "DeveloperTool",
292
- copyright: "",
293
- deb: {
294
- depends: [
295
- "curl",
296
- "wget"
297
- ],
298
- files: {
299
- "/usr/share/applications/com-pake-weread.desktop": "assets/com-pake-weread.desktop"
300
- }
301
- },
302
- externalBin: [
303
- ],
304
- longDescription: "",
305
- resources: [
306
- ],
307
- shortDescription: "",
308
- targets: [
309
- "deb",
310
- "appimage"
311
- ]
312
- }
313
- };
314
- var LinuxConf = {
315
- tauri: tauri
316
- };
317
-
318
- const platformConfigs = {
319
- win32: WinConf,
320
- darwin: MacConf,
321
- linux: LinuxConf,
322
- };
323
- const { platform: platform$2 } = process;
324
- // @ts-ignore
325
- const platformConfig = platformConfigs[platform$2];
326
- let tauriConfig = {
327
- tauri: {
328
- ...CommonConf.tauri,
329
- bundle: platformConfig.tauri.bundle,
330
- },
331
- package: CommonConf.package,
332
- build: CommonConf.build,
333
- pake: pakeConf,
334
- };
335
-
336
- // Generates an identifier based on the given URL.
337
- function getIdentifier(url) {
338
- const postFixHash = crypto.createHash('md5').update(url).digest('hex').substring(0, 6);
339
- return `com.pake.${postFixHash}`;
340
- }
341
- async function promptText(message, initial) {
342
- const response = await prompts({
343
- type: 'text',
344
- name: 'content',
345
- message,
346
- initial,
347
- });
348
- return response.content;
349
- }
350
- function capitalizeFirstLetter(string) {
351
- return string.charAt(0).toUpperCase() + string.slice(1);
352
- }
353
- function getSpinner(text) {
354
- const loadingType = {
355
- interval: 80,
356
- frames: ['โœฆ', 'โœถ', 'โœบ', 'โœต', 'โœธ', 'โœน', 'โœบ'],
357
- };
358
- return ora({
359
- text: `${chalk.cyan(text)}\n`,
360
- spinner: loadingType,
361
- color: 'cyan',
362
- }).start();
363
- }
364
-
365
- const { platform: platform$1 } = process;
366
- const IS_MAC = platform$1 === 'darwin';
367
- const IS_WIN = platform$1 === 'win32';
368
- const IS_LINUX = platform$1 === 'linux';
369
-
370
- // Convert the current module URL to a file path
371
- const currentModulePath = fileURLToPath(import.meta.url);
372
- // Resolve the parent directory of the current module
373
- const npmDirectory = process.env.DEV === 'true' ? process.cwd() : path.join(path.dirname(currentModulePath), '..');
374
-
375
- function shellExec(command) {
376
- return new Promise((resolve, reject) => {
377
- shelljs.exec(command, { async: true, silent: false, cwd: npmDirectory }, code => {
378
- if (code === 0) {
379
- resolve(0);
380
- }
381
- else {
382
- reject(new Error(`${code}`));
383
- }
384
- });
385
- });
386
- }
387
-
388
- const logger = {
389
- info(...msg) {
390
- log.info(...msg.map(m => chalk.white(m)));
391
- },
392
- debug(...msg) {
393
- log.debug(...msg);
394
- },
395
- error(...msg) {
396
- log.error(...msg.map(m => chalk.red(m)));
397
- },
398
- warn(...msg) {
399
- log.info(...msg.map(m => chalk.yellow(m)));
400
- },
401
- success(...msg) {
402
- log.info(...msg.map(m => chalk.green(m)));
403
- },
404
- };
405
-
406
- const resolve = promisify(dns.resolve);
407
- const ping = async (host) => {
408
- const lookup = promisify(dns.lookup);
409
- const ip = await lookup(host);
410
- const start = new Date();
411
- // Prevent timeouts from affecting user experience.
412
- const requestPromise = new Promise((resolve, reject) => {
413
- const req = http.get(`http://${ip.address}`, res => {
414
- const delay = new Date().getTime() - start.getTime();
415
- res.resume();
416
- resolve(delay);
417
- });
418
- req.on('error', err => {
419
- reject(err);
420
- });
421
- });
422
- const timeoutPromise = new Promise((_, reject) => {
423
- setTimeout(() => {
424
- reject(new Error('Request timed out after 3 seconds'));
425
- }, 1000);
426
- });
427
- return Promise.race([requestPromise, timeoutPromise]);
428
- };
429
- async function isChinaDomain(domain) {
430
- try {
431
- const [ip] = await resolve(domain);
432
- return await isChinaIP(ip, domain);
433
- }
434
- catch (error) {
435
- logger.debug(`${domain} can't be parse!`);
436
- return true;
437
- }
438
- }
439
- async function isChinaIP(ip, domain) {
440
- try {
441
- const delay = await ping(ip);
442
- logger.debug(`${domain} latency is ${delay} ms`);
443
- return delay > 1000;
444
- }
445
- catch (error) {
446
- logger.debug(`ping ${domain} failed!`);
447
- return true;
448
- }
449
- }
450
-
451
- async function installRust() {
452
- const isInChina = await isChinaDomain('sh.rustup.rs');
453
- const rustInstallScriptForMac = isInChina
454
- ? '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'
455
- : "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y";
456
- const rustInstallScriptForWindows = 'winget install --id Rustlang.Rustup';
457
- const spinner = getSpinner('Downloading Rust...');
458
- try {
459
- await shellExec(IS_WIN ? rustInstallScriptForWindows : rustInstallScriptForMac);
460
- spinner.succeed(chalk.green('Rust installed successfully!'));
461
- }
462
- catch (error) {
463
- console.error('Error installing Rust:', error.message);
464
- spinner.fail(chalk.red('Rust installation failed!'));
465
- process.exit(1);
466
- }
467
- }
468
- function checkRustInstalled() {
469
- return shelljs.exec('rustc --version', { silent: true }).code === 0;
470
- }
471
-
472
- async function combineFiles(files, output) {
473
- const contents = files.map(file => {
474
- const fileContent = fs.readFileSync(file);
475
- if (file.endsWith('.css')) {
476
- return "window.addEventListener('DOMContentLoaded', (_event) => { const css = `" + fileContent + "`; const style = document.createElement('style'); style.innerHTML = css; document.head.appendChild(style); });";
477
- }
478
- return "window.addEventListener('DOMContentLoaded', (_event) => { " + fileContent + " });";
479
- });
480
- fs.writeFileSync(output, contents.join('\n'));
481
- return files;
482
- }
483
-
484
- async function mergeConfig(url, options, tauriConf) {
485
- const { width, height, fullscreen, transparent, userAgent, showMenu, showSystemTray, systemTrayIcon, iterCopyFile, identifier, name, resizable = true, inject, safeDomain, } = options;
486
- const { platform } = process;
487
- // Set Windows parameters.
488
- const tauriConfWindowOptions = {
489
- width,
490
- height,
491
- fullscreen,
492
- transparent,
493
- resizable,
494
- };
495
- Object.assign(tauriConf.pake.windows[0], { url, ...tauriConfWindowOptions });
496
- tauriConf.package.productName = name;
497
- tauriConf.tauri.bundle.identifier = identifier;
498
- //Judge the type of URL, whether it is a file or a website.
499
- const pathExists = await fsExtra.pathExists(url);
500
- if (pathExists) {
501
- logger.warn('โœผ Your input might be a local file.');
502
- tauriConf.pake.windows[0].url_type = 'local';
503
- const fileName = path.basename(url);
504
- const dirName = path.dirname(url);
505
- const distDir = path.join(npmDirectory, 'dist');
506
- const distBakDir = path.join(npmDirectory, 'dist_bak');
507
- if (!iterCopyFile) {
508
- const urlPath = path.join(distDir, fileName);
509
- await fsExtra.copy(url, urlPath);
510
- }
511
- else {
512
- fsExtra.moveSync(distDir, distBakDir, { overwrite: true });
513
- fsExtra.copySync(dirName, distDir, { overwrite: true });
514
- const filesToCopyBack = ['cli.js', 'about_pake.html'];
515
- await Promise.all(filesToCopyBack.map(file => fsExtra.copy(path.join(distBakDir, file), path.join(distDir, file))));
516
- }
517
- tauriConf.pake.windows[0].url = fileName;
518
- tauriConf.pake.windows[0].url_type = 'local';
519
- }
520
- else {
521
- tauriConf.pake.windows[0].url_type = 'web';
522
- // Set the secure domain for calling window.__TAURI__ to the application domain that has been set.
523
- tauriConf.tauri.security.dangerousRemoteDomainIpcAccess = [
524
- {
525
- domain: new URL(url).hostname,
526
- windows: ['pake'],
527
- enableTauriAPI: true,
528
- },
529
- ];
530
- }
531
- if (safeDomain.length > 0) {
532
- tauriConf.tauri.security.dangerousRemoteDomainIpcAccess = [
533
- ...tauriConf.tauri.security.dangerousRemoteDomainIpcAccess,
534
- ...safeDomain.map(domain => ({
535
- domain,
536
- windows: ['pake'],
537
- enableTauriAPI: true,
538
- })),
539
- ];
540
- }
541
- const platformMap = {
542
- win32: 'windows',
543
- linux: 'linux',
544
- darwin: 'macos',
545
- };
546
- const currentPlatform = platformMap[platform];
547
- if (userAgent.length > 0) {
548
- tauriConf.pake.user_agent[currentPlatform] = userAgent;
549
- }
550
- tauriConf.pake.menu[currentPlatform] = showMenu;
551
- tauriConf.pake.system_tray[currentPlatform] = showSystemTray;
552
- // Processing targets are currently only open to Linux.
553
- if (platform === 'linux') {
554
- delete tauriConf.tauri.bundle.deb.files;
555
- const validTargets = ['all', 'deb', 'appimage'];
556
- if (validTargets.includes(options.targets)) {
557
- tauriConf.tauri.bundle.targets = options.targets === 'all' ? ['deb', 'appimage'] : [options.targets];
558
- }
559
- else {
560
- logger.warn(`โœผ The target must be one of ${validTargets.join(', ')}, the default 'deb' will be used.`);
561
- }
562
- }
563
- // Set icon.
564
- const platformIconMap = {
565
- win32: {
566
- fileExt: '.ico',
567
- path: `png/${name.toLowerCase()}_256.ico`,
568
- defaultIcon: 'png/icon_256.ico',
569
- message: 'Windows icon must be .ico and 256x256px.',
570
- },
571
- linux: {
572
- fileExt: '.png',
573
- path: `png/${name.toLowerCase()}_512.png`,
574
- defaultIcon: 'png/icon_512.png',
575
- message: 'Linux icon must be .png and 512x512px.',
576
- },
577
- darwin: {
578
- fileExt: '.icns',
579
- path: `icons/${name.toLowerCase()}.icns`,
580
- defaultIcon: 'icons/icon.icns',
581
- message: 'macOS icon must be .icns type.',
582
- },
583
- };
584
- const iconInfo = platformIconMap[platform];
585
- const exists = await fsExtra.pathExists(options.icon);
586
- if (exists) {
587
- let updateIconPath = true;
588
- let customIconExt = path.extname(options.icon).toLowerCase();
589
- if (customIconExt !== iconInfo.fileExt) {
590
- updateIconPath = false;
591
- logger.warn(`โœผ ${iconInfo.message}, but you give ${customIconExt}`);
592
- tauriConf.tauri.bundle.icon = [iconInfo.defaultIcon];
593
- }
594
- else {
595
- const iconPath = path.join(npmDirectory, 'src-tauri/', iconInfo.path);
596
- tauriConf.tauri.bundle.resources = [iconInfo.path];
597
- await fsExtra.copy(options.icon, iconPath);
598
- }
599
- if (updateIconPath) {
600
- tauriConf.tauri.bundle.icon = [options.icon];
601
- }
602
- else {
603
- logger.warn(`โœผ Icon will remain as default.`);
604
- }
605
- }
606
- else {
607
- logger.warn('โœผ Custom icon path may be invalid, default icon will be used instead.');
608
- tauriConf.tauri.bundle.icon = [iconInfo.defaultIcon];
609
- }
610
- // Set tray icon path.
611
- let trayIconPath = platform === 'darwin' ? 'png/icon_512.png' : tauriConf.tauri.bundle.icon[0];
612
- if (systemTrayIcon.length > 0) {
613
- try {
614
- await fsExtra.pathExists(systemTrayIcon);
615
- // ้œ€่ฆๅˆคๆ–ญๅ›พๆ ‡ๆ ผๅผ๏ผŒ้ป˜่ฎคๅชๆ”ฏๆŒicoๅ’Œpngไธค็ง
616
- let iconExt = path.extname(systemTrayIcon).toLowerCase();
617
- if (iconExt == '.png' || iconExt == '.ico') {
618
- const trayIcoPath = path.join(npmDirectory, `src-tauri/png/${name.toLowerCase()}${iconExt}`);
619
- trayIconPath = `png/${name.toLowerCase()}${iconExt}`;
620
- await fsExtra.copy(systemTrayIcon, trayIcoPath);
621
- }
622
- else {
623
- logger.warn(`โœผ System tray icon must be .ico or .png, but you provided ${iconExt}.`);
624
- logger.warn(`โœผ Default system tray icon will be used.`);
625
- }
626
- }
627
- catch {
628
- logger.warn(`โœผ ${systemTrayIcon} not exists!`);
629
- logger.warn(`โœผ Default system tray icon will remain unchanged.`);
630
- }
631
- }
632
- tauriConf.tauri.systemTray.iconPath = trayIconPath;
633
- const injectFilePath = path.join(npmDirectory, `src-tauri/src/inject/_INJECT_.js`);
634
- // inject js or css files
635
- if (inject?.length > 0) {
636
- if (!inject.every(item => item.endsWith('.css') || item.endsWith('.js'))) {
637
- logger.error('The injected file must be in either CSS or JS format.');
638
- return;
639
- }
640
- const files = inject.map(filepath => path.isAbsolute(filepath) ? filepath : path.join(process.cwd(), filepath));
641
- tauriConf.pake.inject = files;
642
- await combineFiles(files, injectFilePath);
643
- }
644
- else {
645
- tauriConf.pake.inject = [];
646
- await fsExtra.writeFile(injectFilePath, '');
647
- }
648
- // Save config file.
649
- const platformConfigPaths = {
650
- win32: 'src-tauri/tauri.windows.conf.json',
651
- darwin: 'src-tauri/tauri.macos.conf.json',
652
- linux: 'src-tauri/tauri.linux.conf.json',
653
- };
654
- const configPath = path.join(npmDirectory, platformConfigPaths[platform]);
655
- const bundleConf = { tauri: { bundle: tauriConf.tauri.bundle } };
656
- await fsExtra.writeJson(configPath, bundleConf, { spaces: 4 });
657
- const pakeConfigPath = path.join(npmDirectory, 'src-tauri/pake.json');
658
- await fsExtra.writeJson(pakeConfigPath, tauriConf.pake, { spaces: 4 });
659
- let tauriConf2 = JSON.parse(JSON.stringify(tauriConf));
660
- delete tauriConf2.pake;
661
- delete tauriConf2.tauri.bundle;
662
- const configJsonPath = path.join(npmDirectory, 'src-tauri/tauri.conf.json');
663
- await fsExtra.writeJson(configJsonPath, tauriConf2, { spaces: 4 });
664
- }
665
-
666
- class BaseBuilder {
667
- constructor(options) {
668
- this.options = options;
669
- }
670
- async prepare() {
671
- const tauriSrcPath = path.join(npmDirectory, 'src-tauri');
672
- const tauriTargetPath = path.join(tauriSrcPath, 'target');
673
- const tauriTargetPathExists = await fsExtra.pathExists(tauriTargetPath);
674
- if (!IS_MAC && !tauriTargetPathExists) {
675
- logger.warn('โœผ The first use requires installing system dependencies.');
676
- logger.warn('โœผ See more in https://tauri.app/v1/guides/getting-started/prerequisites.');
677
- }
678
- if (!checkRustInstalled()) {
679
- const res = await prompts({
680
- type: 'confirm',
681
- message: 'Rust not detected. Install now?',
682
- name: 'value',
683
- });
684
- if (res.value) {
685
- await installRust();
686
- }
687
- else {
688
- logger.error('โœ• Rust required to package your webapp.');
689
- process.exit(0);
690
- }
691
- }
692
- const isChina = await isChinaDomain('www.npmjs.com');
693
- const spinner = getSpinner('Installing package...');
694
- const rustProjectDir = path.join(tauriSrcPath, '.cargo');
695
- const projectConf = path.join(rustProjectDir, 'config');
696
- await fsExtra.ensureDir(rustProjectDir);
697
- if (isChina) {
698
- logger.info('โœบ Located in China, using npm/rsProxy CN mirror.');
699
- const projectCnConf = path.join(tauriSrcPath, 'rust_proxy.toml');
700
- await fsExtra.copy(projectCnConf, projectConf);
701
- await shellExec(`cd "${npmDirectory}" && npm install --registry=https://registry.npmmirror.com`);
702
- }
703
- else {
704
- await shellExec(`cd "${npmDirectory}" && npm install`);
705
- }
706
- spinner.succeed(chalk.green('Package installed!'));
707
- if (!tauriTargetPathExists) {
708
- logger.warn('โœผ The first packaging may be slow, please be patient and wait, it will be faster afterwards.');
709
- }
710
- }
711
- async build(url) {
712
- await this.buildAndCopy(url, this.options.targets);
713
- }
714
- async start(url) {
715
- await mergeConfig(url, this.options, tauriConfig);
716
- }
717
- async buildAndCopy(url, target) {
718
- const { name } = this.options;
719
- await mergeConfig(url, this.options, tauriConfig);
720
- // Build app
721
- const spinner = getSpinner('Building app...');
722
- setTimeout(() => spinner.stop(), 3000);
723
- await shellExec(`cd "${npmDirectory}" && ${this.getBuildCommand()}`);
724
- // Copy app
725
- const fileName = this.getFileName();
726
- const fileType = this.getFileType(target);
727
- const appPath = this.getBuildAppPath(npmDirectory, fileName, fileType);
728
- const distPath = path.resolve(`${name}.${fileType}`);
729
- await fsExtra.copy(appPath, distPath);
730
- await fsExtra.remove(appPath);
731
- logger.success('โœ” Build success!');
732
- logger.success('โœ” App installer located in', distPath);
733
- }
734
- getFileType(target) {
735
- return target;
736
- }
737
- getBuildCommand() {
738
- // the debug option should support `--debug` and `--release`
739
- return this.options.debug ? 'npm run build:debug' : 'npm run build';
740
- }
741
- getBasePath() {
742
- return 'src-tauri/target/release/bundle/';
743
- }
744
- getBuildAppPath(npmDirectory, fileName, fileType) {
745
- return path.join(npmDirectory, this.getBasePath(), fileType.toLowerCase(), `${fileName}.${fileType}`);
746
- }
747
- }
748
-
749
- class MacBuilder extends BaseBuilder {
750
- constructor(options) {
751
- super(options);
752
- this.options.targets = 'dmg';
753
- }
754
- getFileName() {
755
- const { name } = this.options;
756
- let arch;
757
- if (this.options.multiArch) {
758
- arch = 'universal';
759
- }
760
- else {
761
- arch = process.arch === 'arm64' ? 'aarch64' : process.arch;
762
- }
763
- return `${name}_${tauriConfig.package.version}_${arch}`;
764
- }
765
- getBuildCommand() {
766
- return this.options.multiArch ? 'npm run build:mac' : super.getBuildCommand();
767
- }
768
- getBasePath() {
769
- return this.options.multiArch
770
- ? 'src-tauri/target/universal-apple-darwin/release/bundle'
771
- : super.getBasePath();
772
- }
773
- }
774
-
775
- class WinBuilder extends BaseBuilder {
776
- constructor(options) {
777
- super(options);
778
- this.options.targets = 'msi';
779
- }
780
- getFileName() {
781
- const { name } = this.options;
782
- const { arch } = process;
783
- const language = tauriConfig.tauri.bundle.windows.wix.language[0];
784
- return `${name}_${tauriConfig.package.version}_${arch}_${language}`;
785
- }
786
- }
787
-
788
- class LinuxBuilder extends BaseBuilder {
789
- constructor(options) {
790
- super(options);
791
- }
792
- getFileName() {
793
- const { name } = this.options;
794
- const arch = process.arch === 'x64' ? 'amd64' : process.arch;
795
- return `${name}_${tauriConfig.package.version}_${arch}`;
796
- }
797
- // Customize it, considering that there are all targets.
798
- async build(url) {
799
- const targetTypes = ['deb', 'appimage'];
800
- for (const target of targetTypes) {
801
- if (this.options.targets === target || this.options.targets === 'all') {
802
- await this.buildAndCopy(url, target);
803
- }
804
- }
805
- }
806
- getFileType(target) {
807
- if (target === 'appimage') {
808
- return 'AppImage';
809
- }
810
- return super.getFileType(target);
811
- }
812
- }
813
-
814
- const { platform } = process;
815
- const buildersMap = {
816
- darwin: MacBuilder,
817
- win32: WinBuilder,
818
- linux: LinuxBuilder,
819
- };
820
- class BuilderProvider {
821
- static create(options) {
822
- const Builder = buildersMap[platform];
823
- if (!Builder) {
824
- throw new Error('The current system is not supported!');
825
- }
826
- return new Builder(options);
827
- }
828
- }
829
-
830
- const DEFAULT_PAKE_OPTIONS = {
831
- icon: '',
832
- height: 780,
833
- width: 1200,
834
- fullscreen: false,
835
- resizable: true,
836
- transparent: false,
837
- userAgent: '',
838
- showMenu: false,
839
- showSystemTray: false,
840
- multiArch: false,
841
- targets: 'deb',
842
- iterCopyFile: false,
843
- systemTrayIcon: '',
844
- debug: false,
845
- inject: [],
846
- safeDomain: [],
847
- };
848
-
849
- async function checkUpdateTips() {
850
- updateNotifier({ pkg: packageJson, updateCheckInterval: 1000 * 60 }).notify({ isGlobal: true });
851
- }
852
-
853
- async function handleIcon(options) {
854
- if (options.icon) {
855
- if (options.icon.startsWith('http')) {
856
- return downloadIcon(options.icon);
857
- }
858
- else {
859
- return path.resolve(options.icon);
860
- }
861
- }
862
- else {
863
- logger.warn('โœผ No icon given, default in use. For a custom icon, use --icon option.');
864
- const iconPath = IS_WIN
865
- ? 'src-tauri/png/icon_256.ico'
866
- : IS_LINUX
867
- ? 'src-tauri/png/icon_512.png'
868
- : 'src-tauri/icons/icon.icns';
869
- return path.join(npmDirectory, iconPath);
870
- }
871
- }
872
- async function downloadIcon(iconUrl) {
873
- const spinner = getSpinner('Downloading icon...');
874
- try {
875
- const iconResponse = await axios.get(iconUrl, { responseType: 'arraybuffer' });
876
- const iconData = await iconResponse.data;
877
- if (!iconData) {
878
- return null;
879
- }
880
- const fileDetails = await fileTypeFromBuffer(iconData);
881
- if (!fileDetails) {
882
- return null;
883
- }
884
- const { path: tempPath } = await dir();
885
- const iconPath = `${tempPath}/icon.${fileDetails.ext}`;
886
- await fsExtra.outputFile(iconPath, iconData);
887
- spinner.succeed(chalk.green('Icon downloaded successfully!'));
888
- return iconPath;
889
- }
890
- catch (error) {
891
- spinner.fail(chalk.red('Icon download failed!'));
892
- if (error.response && error.response.status === 404) {
893
- return null;
894
- }
895
- throw error;
896
- }
897
- }
898
-
899
- // Extracts the domain from a given URL.
900
- function getDomain(inputUrl) {
901
- try {
902
- const url = new URL(inputUrl);
903
- // Use PSL to parse domain names.
904
- const parsed = psl.parse(url.hostname);
905
- // If domain is available, split it and return the SLD.
906
- if ('domain' in parsed && parsed.domain) {
907
- return parsed.domain.split('.')[0];
908
- }
909
- else {
910
- return null;
911
- }
912
- }
913
- catch (error) {
914
- return null;
915
- }
916
- }
917
- // Appends 'https://' protocol to the URL if not present.
918
- function appendProtocol(inputUrl) {
919
- try {
920
- new URL(inputUrl);
921
- return inputUrl;
922
- }
923
- catch {
924
- return `https://${inputUrl}`;
925
- }
926
- }
927
- // Normalizes the URL by ensuring it has a protocol and is valid.
928
- function normalizeUrl(urlToNormalize) {
929
- const urlWithProtocol = appendProtocol(urlToNormalize);
930
- if (isUrl(urlWithProtocol)) {
931
- return urlWithProtocol;
932
- }
933
- else {
934
- throw new Error(`Your url "${urlWithProtocol}" is invalid`);
935
- }
936
- }
937
-
938
- function resolveAppName(name, platform) {
939
- const domain = getDomain(name) || 'pake';
940
- return platform !== 'linux' ? capitalizeFirstLetter(domain) : domain;
941
- }
942
- function isValidName(name, platform) {
943
- const platformRegexMapping = {
944
- linux: /^[a-z0-9]+(-[a-z0-9]+)*$/,
945
- default: /^[a-zA-Z0-9]+$/,
946
- };
947
- const reg = platformRegexMapping[platform] || platformRegexMapping.default;
948
- return !!name && reg.test(name);
949
- }
950
- async function handleOptions(options, url) {
951
- const { platform } = process;
952
- const isActions = process.env.GITHUB_ACTIONS;
953
- let name = options.name;
954
- const pathExists = await fsExtra.pathExists(url);
955
- if (!options.name) {
956
- const defaultName = pathExists ? '' : resolveAppName(url, platform);
957
- const promptMessage = 'Enter your application name';
958
- const namePrompt = await promptText(promptMessage, defaultName);
959
- name = namePrompt || defaultName;
960
- }
961
- if (!isValidName(name, platform)) {
962
- 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.`;
963
- 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.`;
964
- const errorMsg = platform === 'linux' ? LINUX_NAME_ERROR : DEFAULT_NAME_ERROR;
965
- logger.error(errorMsg);
966
- if (isActions) {
967
- name = resolveAppName(url, platform);
968
- logger.warn(`โœผ Inside github actions, use the default name: ${name}`);
969
- }
970
- else {
971
- process.exit(1);
972
- }
973
- }
974
- const appOptions = {
975
- ...options,
976
- name,
977
- identifier: getIdentifier(url),
978
- };
979
- appOptions.icon = await handleIcon(appOptions);
980
- return appOptions;
981
- }
982
-
983
- function validateNumberInput(value) {
984
- const parsedValue = Number(value);
985
- if (isNaN(parsedValue)) {
986
- throw new InvalidArgumentError('Not a number.');
987
- }
988
- return parsedValue;
989
- }
990
- function validateUrlInput(url) {
991
- const isFile = fs.existsSync(url);
992
- if (!isFile) {
993
- try {
994
- return normalizeUrl(url);
995
- }
996
- catch (error) {
997
- throw new InvalidArgumentError(error.message);
998
- }
999
- }
1000
- return url;
1001
- }
1002
-
1003
- const { green, yellow } = chalk;
1004
- const logo = `${chalk.green(' ____ _')}
1005
- ${green('| _ \\ __ _| | _____')}
1006
- ${green('| |_) / _` | |/ / _ \\')}
1007
- ${green('| __/ (_| | < __/')} ${yellow('https://github.com/tw93/pake')}
1008
- ${green('|_| \\__,_|_|\\_\\___| can turn any webpage into a desktop app with Rust.')}
1009
- `;
1010
- program
1011
- .addHelpText('beforeAll', logo)
1012
- .usage(`[url] [options]`)
1013
- .showHelpAfterError();
1014
- program
1015
- .argument('[url]', 'The web URL you want to package', validateUrlInput)
1016
- .option('--name <string>', 'Application name')
1017
- .option('--icon <string>', 'Application icon', DEFAULT_PAKE_OPTIONS.icon)
1018
- .option('--width <number>', 'Window width', validateNumberInput, DEFAULT_PAKE_OPTIONS.width)
1019
- .option('--height <number>', 'Window height', validateNumberInput, DEFAULT_PAKE_OPTIONS.height)
1020
- .option('--transparent', 'Only for Mac, hide title bar', DEFAULT_PAKE_OPTIONS.transparent)
1021
- .option('--fullscreen', 'Start in full screen', DEFAULT_PAKE_OPTIONS.fullscreen)
1022
- .option('--user-agent <string>', 'Custom user agent', DEFAULT_PAKE_OPTIONS.userAgent)
1023
- .option('--show-menu', 'Show menu in app', DEFAULT_PAKE_OPTIONS.showMenu)
1024
- .option('--show-system-tray', 'Show system tray in app', DEFAULT_PAKE_OPTIONS.showSystemTray)
1025
- .option('--system-tray-icon <string>', 'Custom system tray icon', DEFAULT_PAKE_OPTIONS.systemTrayIcon)
1026
- .option('--iter-copy-file', 'Copy files when URL is a local file', DEFAULT_PAKE_OPTIONS.iterCopyFile)
1027
- .option('--multi-arch', 'Only for Mac, supports both Intel and M1', DEFAULT_PAKE_OPTIONS.multiArch)
1028
- .option('--targets <string>', 'Only for Linux, option "deb" or "appimage"', DEFAULT_PAKE_OPTIONS.targets)
1029
- .option('--inject [injects...]', 'inject .js or .css for this app', DEFAULT_PAKE_OPTIONS.inject)
1030
- .option('--safe-domain [domains...]', 'domains that can call window.__TAURI__ and use ipc', DEFAULT_PAKE_OPTIONS.safeDomain)
1031
- .option('--debug', 'Debug mode', DEFAULT_PAKE_OPTIONS.debug)
1032
- .version(packageJson.version, '-v, --version', 'Output the current version')
1033
- .action(async (url, options) => {
1034
- await checkUpdateTips();
1035
- if (!url) {
1036
- program.outputHelp(str => {
1037
- return str
1038
- .split('\n')
1039
- .filter(line => !/((-h,|--help)|((-v|-V),|--version))\s+.+$/.test(line))
1040
- .join('\n');
1041
- });
1042
- process.exit(0);
1043
- }
1044
- log.setDefaultLevel('info');
1045
- if (options.debug) {
1046
- log.setLevel('debug');
1047
- }
1048
- const appOptions = await handleOptions(options, url);
1049
- log.debug('PakeAppOptions', appOptions);
1050
- const builder = BuilderProvider.create(appOptions);
1051
- await builder.prepare();
1052
- await builder.build(url);
1053
- });
1054
- program.parse();
1055
- //# sourceMappingURL=cli.dev.js.map