tt-minigame-ide-cli 1.0.3-beta.0 → 2.0.0-alpha.1

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.
Files changed (67) hide show
  1. package/README.md +5 -98
  2. package/bin/tmg.js +4 -161
  3. package/dist/cli.js +1 -0
  4. package/dist/index.js +1 -0
  5. package/dist/miniprogram-utils/src/constants/error.d.ts +41 -0
  6. package/dist/miniprogram-utils/src/constants/index.d.ts +217 -0
  7. package/dist/miniprogram-utils/src/constants/project.d.ts +3 -0
  8. package/dist/miniprogram-utils/src/constants/slardar-events/update-events.d.ts +24 -0
  9. package/dist/miniprogram-utils/src/data/app.d.ts +30 -0
  10. package/dist/miniprogram-utils/src/data/ext.d.ts +6 -0
  11. package/dist/miniprogram-utils/src/data/jsons.d.ts +23 -0
  12. package/dist/miniprogram-utils/src/data/project.d.ts +124 -0
  13. package/dist/miniprogram-utils/src/electron-monitor/common/tea-sdk.d.ts +17 -0
  14. package/dist/miniprogram-utils/src/formation.d.ts +17 -0
  15. package/dist/miniprogram-utils/src/network/axios.d.ts +28 -0
  16. package/dist/tt-ide-cli/src/features/audit.d.ts +9 -0
  17. package/dist/tt-ide-cli/src/features/cli-login.d.ts +1 -0
  18. package/dist/tt-ide-cli/src/features/config.d.ts +3 -0
  19. package/dist/tt-ide-cli/src/features/create.d.ts +7 -0
  20. package/dist/tt-ide-cli/src/features/login.d.ts +18 -0
  21. package/dist/tt-ide-cli/src/features/meta.d.ts +23 -0
  22. package/dist/tt-ide-cli/src/features/microgame/cloud-compile.d.ts +75 -0
  23. package/dist/tt-ide-cli/src/features/microgame/index.d.ts +3 -0
  24. package/dist/tt-ide-cli/src/features/microgame/meta.d.ts +1 -0
  25. package/dist/tt-ide-cli/src/features/microgame/utils/file-system.d.ts +13 -0
  26. package/dist/tt-ide-cli/src/features/microgame/utils/package.d.ts +22 -0
  27. package/dist/tt-ide-cli/src/features/microgame/utils/settings.d.ts +48 -0
  28. package/dist/tt-ide-cli/src/features/microgame/utils/source.type.d.ts +35 -0
  29. package/dist/tt-ide-cli/src/features/npm.d.ts +10 -0
  30. package/dist/tt-ide-cli/src/features/open.d.ts +3 -0
  31. package/dist/tt-ide-cli/src/features/packages.d.ts +53 -0
  32. package/dist/tt-ide-cli/src/features/preview.d.ts +80 -0
  33. package/dist/tt-ide-cli/src/features/third-party.d.ts +9 -0
  34. package/dist/tt-ide-cli/src/index.d.ts +22 -0
  35. package/dist/tt-ide-cli/src/monitor/cli-monitor.d.ts +15 -0
  36. package/dist/tt-ide-cli/src/monitor/constants.d.ts +7 -0
  37. package/dist/tt-ide-cli/src/monitor/index.d.ts +2 -0
  38. package/dist/tt-ide-cli/src/types.d.ts +44 -0
  39. package/dist/tt-ide-cli/src/utils/constants.d.ts +3 -0
  40. package/dist/tt-ide-cli/src/utils/cookie.d.ts +6 -0
  41. package/dist/tt-ide-cli/src/utils/logger.d.ts +19 -0
  42. package/dist/tt-ide-cli/src/utils/metrics.d.ts +67 -0
  43. package/dist/tt-ide-cli/src/utils/qrcode.d.ts +64 -0
  44. package/dist/tt-ide-cli/src/utils/util.d.ts +56 -0
  45. package/dist/tt-minigame-ide-cli/src/cli.d.ts +1 -0
  46. package/dist/tt-minigame-ide-cli/src/index.d.ts +1 -0
  47. package/dist/tt-minigame-ide-cli/src/types.d.ts +43 -0
  48. package/package.json +49 -26
  49. package/.yarnrc +0 -1
  50. package/LICENSE +0 -21
  51. package/README.en.md +0 -104
  52. package/lib/auth.js +0 -145
  53. package/lib/build-npm.js +0 -22
  54. package/lib/create.js +0 -106
  55. package/lib/index.d.ts +0 -23
  56. package/lib/index.js +0 -79
  57. package/lib/preview.js +0 -92
  58. package/lib/upload.js +0 -133
  59. package/lib/util/check.js +0 -84
  60. package/lib/util/config.js +0 -41
  61. package/lib/util/cookie.js +0 -36
  62. package/lib/util/helper.js +0 -245
  63. package/lib/util/logger.js +0 -54
  64. package/lib/util/qrcode.js +0 -34
  65. package/lib/util/request.js +0 -396
  66. package/lib/util/version.js +0 -27
  67. package/lib/version.js +0 -44
package/lib/index.js DELETED
@@ -1,79 +0,0 @@
1
- const _preview = require('./preview');
2
- const _upload = require('./upload');
3
- const _create = require('./create');
4
- const _auth = require('./auth');
5
- const buildNpm = require('./build-npm');
6
- const config = require('./util/config');
7
- const cookieHandler = require('./util/cookie');
8
-
9
- function create(projectName, { force = false }) {
10
- return _create(projectName, {
11
- force,
12
- });
13
- }
14
-
15
- function loginByEmail(email, password, customOptions) {
16
- const options = {
17
- type: 'direct',
18
- email,
19
- password,
20
- ...customOptions,
21
- };
22
-
23
- return _auth(options);
24
- }
25
-
26
- function login({ type = '', proxy = '' }) {
27
- if (type === 'mobile' || type === 'email') {
28
- return _auth({ [type]: true, proxy });
29
- } else {
30
- return _auth({ proxy });
31
- }
32
- }
33
-
34
- function preview({
35
- entry = '',
36
- copy = false,
37
- force = false,
38
- small = false,
39
- proxy = '',
40
- tempDir = null
41
- }) {
42
- return _preview(entry, {
43
- copy,
44
- force,
45
- small,
46
- proxy,
47
- tempDir,
48
- });
49
- }
50
-
51
- function upload({ entry = '', version, changeLog, proxy = '', copy = false, tempDir = null }) {
52
- return _upload(entry, {
53
- appVersion: version,
54
- appChangelog: changeLog,
55
- proxy,
56
- copy,
57
- tempDir
58
- });
59
- }
60
-
61
- function setConfig(customConfig) {
62
- console.log('configconfigconfig=:', customConfig);
63
- return config.setConfig(customConfig);
64
- }
65
-
66
- async function checkSession() {
67
- return await cookieHandler.checkSession();
68
- }
69
-
70
- module.exports = {
71
- create,
72
- loginByEmail,
73
- login,
74
- preview,
75
- upload,
76
- buildNpm,
77
- setConfig,
78
- checkSession,
79
- };
package/lib/preview.js DELETED
@@ -1,92 +0,0 @@
1
- // Preview project
2
- const fs = require('fs-extra');
3
- const path = require('path');
4
- const chalk = require('chalk');
5
- const { hashElement } = require('folder-hash');
6
- const { outputResult, clearConsole } = require('./util/logger');
7
- const { checkBeforeUpload } = require('./util/check');
8
- const { zipFile, savePreviewResult, getCachedPreviewResult } = require('./util/helper');
9
- const { uploadProject, getCompileProgress, getQrCode } = require('./util/request');
10
- const { generateQrCode } = require('./util/qrcode');
11
-
12
- async function preview(entry, options) {
13
- const cwd = options.cwd || process.cwd();
14
- if (!entry || entry === '.') {
15
- entry = cwd;
16
- } else {
17
- entry = path.resolve(cwd, entry);
18
- }
19
- const dirHash = await hashElement(entry, { folders: { exclude: ['node_modules'] } });
20
- const cacheDisabled = options.force || options.disableCache;
21
- if (!cacheDisabled) {
22
- // check local cache
23
- const cacheRet = getCachedPreviewResult('native', dirHash.hash);
24
- if (cacheRet) {
25
- generateQrCode(cacheRet, options);
26
- console.log(chalk.cyan(`Since local files have not changed, use the cache result\nUse option ${chalk.yellow('-f')} to ignore cache`));
27
- return;
28
- }
29
- }
30
-
31
- const { success, msg, appId } = await checkBeforeUpload(entry);
32
- if (!success) {
33
- const errMsg = `[CLI PREVIEW ERROR]: ${msg}`;
34
- console.log(chalk.red(errMsg));
35
- throw new Error(errMsg);
36
- return;
37
- }
38
-
39
- const tempDir = options.tempDir || path.join(__dirname, '../temp');
40
- await fs.emptyDir(tempDir);
41
- const { filePath, gameConfig } = await zipFile(entry, tempDir);
42
- if (!filePath) {
43
- const errMsg = `[CLI PREVIEW ERROR]`;
44
- console.log(chalk.red(errMsg));
45
- throw new Error(errMsg);
46
- return;
47
- }
48
- await uploadProject({
49
- type: 'preview',
50
- appId,
51
- zipPath: filePath,
52
- proxy: options.proxy,
53
- gameConfig
54
- });
55
-
56
- outputResult('info', 'WAIT', 'Compiling...\n');
57
- return await new Promise((resolve, reject) => {
58
- const timer = setInterval(async () => {
59
- const { success, msg, done } = await getCompileProgress(appId, options.proxy);
60
- if (!success) {
61
- const errMsg = `[CLI PREVIEW ERROR]: ${msg}`;
62
- console.log(chalk.red(errMsg));
63
- clearInterval(timer);
64
- reject(errMsg);
65
- return;
66
- }
67
- if (success && done) {
68
- clearInterval(timer);
69
- const ret = await getQrCode(appId, options.proxy);
70
- if (ret.success) {
71
- clearConsole();
72
- outputResult('success', `DONE`, `Scan the QR Code for remote preview\n`);
73
- generateQrCode(ret.url, options);
74
- // save preview result
75
- savePreviewResult(ret.url, 'native', dirHash.hash);
76
- resolve(ret.url);
77
- } else {
78
- console.log(chalk.red(`[CLI PREVIEW ERROR]: ${ret.msg}`));
79
- reject(ret.msg);
80
- }
81
- }
82
- }, 1500);
83
- });
84
- }
85
-
86
- module.exports = (...args) => {
87
- return preview(...args).catch(err => {
88
- const errMsg = `[CLI PREVIEW ERROR]: ${err}`;
89
- console.log(chalk.red(errMsg));
90
- throw new Error(errMsg);
91
- });
92
- }
package/lib/upload.js DELETED
@@ -1,133 +0,0 @@
1
- // Upload project
2
- const fs = require('fs-extra');
3
- const path = require('path');
4
- const chalk = require('chalk');
5
- const {
6
- outputResult,
7
- clearConsole
8
- } = require('./util/logger');
9
- const {
10
- checkBeforeUpload,
11
- isValidAppVersion
12
- } = require('./util/check');
13
- const {
14
- zipFile
15
- } = require('./util/helper');
16
- const {
17
- uploadProject,
18
- getCompileProgress,
19
- checkUserPermissions,
20
- getQrCode,
21
- checkUploadVersion,
22
- } = require('./util/request');
23
- const {
24
- generateQrCode
25
- } = require('./util/qrcode');
26
-
27
- async function upload(entry, options) {
28
- const cwd = options.cwd || process.cwd();
29
- if (!entry) {
30
- entry = cwd
31
- } else if (path.isAbsolute(entry)) {
32
- // skip if entry if absolute path
33
- } else {
34
- // resolve the relative entry with cwd
35
- entry = path.resolve(cwd, entry);
36
- }
37
-
38
- if (!isValidAppVersion(options.appVersion)) {
39
- const errMsg = `[CLI UPLOAD ERROR]: App version ${options.appVersion} is not valid, expected [major].[minor].[patch]`;
40
- console.log(chalk.red(errMsg));
41
- throw new Error(errMsg);
42
- }
43
-
44
- const {
45
- success: beforeSuccess,
46
- msg: beforeMsg,
47
- appId,
48
- } = await checkBeforeUpload(entry);
49
- if (!beforeSuccess) {
50
- const errMsg = `[CLI UPLOAD ERROR]: ${beforeMsg}`;
51
- console.log(chalk.red(errMsg));
52
- throw new Error(errMsg);
53
- }
54
-
55
- const {
56
- success: checkVersionSuccess,
57
- msg: checkVersionMsg,
58
- } = await checkUploadVersion(appId, options.appVersion);
59
- if (!checkVersionSuccess) {
60
- const errMsg = `[CLI UPLOAD ERROR]: ${checkVersionMsg}`;
61
- console.log(chalk.red(errMsg));
62
- throw new Error(errMsg);
63
- }
64
-
65
- const tempDir = options.tempDir || path.join(__dirname, '../temp');
66
- await fs.emptyDir(tempDir);
67
-
68
- const {
69
- success: authSuccess,
70
- msg: authMsg
71
- } = await checkUserPermissions(appId, options.proxy);
72
- if (!authSuccess) {
73
- const errMsg = `[CLI UPLOAD ERROR]: ${authMsg}`;
74
- console.log(chalk.red(errMsg));
75
- throw new Error(errMsg);
76
- }
77
-
78
- const { filePath, gameConfig } = await zipFile(entry, tempDir);
79
- if (!filePath) {
80
- const errMsg = `[CLI UPLOAD ERROR]`;
81
- console.log(chalk.red(errMsg));
82
- throw new Error(errMsg);
83
- }
84
- await uploadProject({
85
- type: 'upload',
86
- appId,
87
- zipPath: filePath,
88
- versionInfo: options.appVersion,
89
- updateInfo: options.appChangelog,
90
- proxy: options.proxy,
91
- gameConfig,
92
- });
93
-
94
- outputResult('info', 'WAIT', 'Compiling...\n');
95
- return new Promise((resolve, reject) => {
96
- const timer = setInterval(async () => {
97
- const {
98
- success,
99
- msg,
100
- done
101
- } = await getCompileProgress(appId, options.proxy);
102
- if (!success) {
103
- const errMsg = `[CLI UPLOAD ERROR]: ${msg}`;
104
- console.log(chalk.red(errMsg));
105
- clearInterval(timer);
106
- reject(errMsg);
107
- }
108
- if (success && done) {
109
- clearConsole();
110
- outputResult('success', `v${options.appVersion}`, ` 🎉 Successfully uploaded project`);
111
- const ret = await getQrCode(appId, options.proxy, 'latest');
112
- if (ret.success) {
113
- outputResult('success', `DONE`, `Scan the QR Code for remote preview\n`);
114
- generateQrCode(ret.url, options);
115
- resolve(ret.url);
116
- } else {
117
- const errMsg = `[CLI UPLOAD ERROR]: ${ret.msg}`;
118
- console.log(chalk.red(errMsg));
119
- reject(ret.msg);
120
- }
121
- clearInterval(timer);
122
- }
123
- }, 1500);
124
- });
125
- }
126
-
127
- module.exports = (...args) => {
128
- return upload(...args).catch(err => {
129
- const errMsg = `[CLI UPLOAD ERROR]: ${err}`;
130
- console.log(chalk.red(errMsg));
131
- throw new Error(errMsg);
132
- });
133
- }
package/lib/util/check.js DELETED
@@ -1,84 +0,0 @@
1
- const fs = require('fs-extra');
2
- const chalk = require('chalk');
3
- const path = require('path');
4
- const semver = require('semver');
5
- const { checkRemoteVersion } = require('./request');
6
- const { getUserCookies } = require('./cookie');
7
- const { getLatestVersionFromLocal, saveLatestVersionToLocal, getVersion } = require('./version');
8
-
9
- function isValidPhoneNumber(number) {
10
- return /^1[3-9]\d{9}$/.test(number);
11
- }
12
-
13
- function isValidVerificationCode(number) {
14
- return /^\d{4}$/.test(number);
15
- }
16
-
17
- function isValidEmail(email) {
18
- return /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(email);
19
- }
20
-
21
- function isValidAppId(id) {
22
- return /^tt[0-9a-f]{16}([0-9a-f]{2})?$/.test(id);
23
- }
24
-
25
- function isValidAppVersion(version) {
26
- return /^\d+\.\d+\.\d+$/.test(version);
27
- }
28
-
29
- async function checkBeforeUpload(entry) {
30
- const configPath = path.join(entry, 'project.config.json');
31
- const exists = await fs.pathExists(configPath);
32
- if (!exists) {
33
- return {
34
- success: false,
35
- msg: 'Invalid project: project.config.json file not found'
36
- }
37
- }
38
- const appConfig = await fs.readFile(configPath, 'utf-8');
39
- const appConfigJSON = JSON.parse(appConfig);
40
- const appId = appConfigJSON.ttappid || appConfigJSON.appid;
41
- if (!isValidAppId(appId)) {
42
- return { success: false, msg: `AppId ${chalk.cyan(appId)} is not valid` };
43
- }
44
- if (!getUserCookies()) {
45
- console.log(chalk.red());
46
- return {
47
- success: false,
48
- msg: `This feature requires login, please login via ${chalk.cyan(
49
- 'tmg login'
50
- )} command`,
51
- };
52
- }
53
- return { success: true, appId };
54
- }
55
- // 该方法暂无调用
56
- async function checkNeedUpdate() {
57
- let needUpdate = false;
58
- const versionCache = await getLatestVersionFromLocal();
59
- const daysPassed = (Date.now() - versionCache.time || 0) / (60 * 60 * 1000 * 24);
60
- if (daysPassed > 1 || !versionCache.version) {
61
- const { version } = await checkRemoteVersion();
62
- versionCache.version = version || '0.0.0';
63
- saveLatestVersionToLocal(version, Date.now());
64
- }
65
- const currentVersion = getVersion();
66
- if (semver.gt(versionCache.version, currentVersion)) {
67
- needUpdate = true;
68
- }
69
- return {
70
- needUpdate,
71
- latest: versionCache.version,
72
- current: currentVersion
73
- }
74
- }
75
-
76
- module.exports = {
77
- isValidPhoneNumber,
78
- isValidEmail,
79
- isValidVerificationCode,
80
- isValidAppId,
81
- isValidAppVersion,
82
- checkBeforeUpload,
83
- checkNeedUpdate
84
- }
@@ -1,41 +0,0 @@
1
- const path = require('path');
2
- const fs = require('fs-extra');
3
- const os = require('os');
4
- let customConfig = {};
5
-
6
- function setConfig(config = {}) {
7
- return customConfig = {
8
- ...customConfig,
9
- ...config
10
- };
11
- }
12
-
13
- function createProjectConfigFile(projectName, projectDir) {
14
- const configJson = `{
15
- "setting": {
16
- "urlCheck": true,
17
- "es6": true,
18
- "postcss": true,
19
- "minified": true,
20
- "newFeature": true
21
- },
22
- "miniprogramRoot": "./",
23
- "appid": "testappId",
24
- "projectname": "${projectName}"
25
- }`;
26
- const filePath = path.resolve(projectDir, 'project.config.json');
27
- return fs.writeFile(filePath, configJson);
28
- }
29
-
30
- function getStoragePath() {
31
- if (customConfig.storagePath) {
32
- return customConfig.storagePath;
33
- }
34
- return path.join(os.homedir(), `.tmg-cli/`);
35
- }
36
-
37
- module.exports = {
38
- setConfig,
39
- createProjectConfigFile,
40
- getStoragePath
41
- };
@@ -1,36 +0,0 @@
1
- // const os = require('os');
2
- const fs = require('fs-extra');
3
- const path = require('path');
4
- const { getStoragePath } = require('./config');
5
- let cookieStr = '';
6
-
7
- async function saveUserCookies(cookies) {
8
- const cookieSavedPath = path.join(getStoragePath(), '.cookies');
9
- fs.ensureFileSync(cookieSavedPath);
10
- if (!cookies || cookies.length < 1) return;
11
- cookieStr = cookies.map(cookie => cookie.split(';')[0]).join(';');
12
- try {
13
- fs.writeFile(path.join(cookieSavedPath), cookieStr);
14
- }
15
- catch (err) {
16
- console.error(err);
17
- }
18
- }
19
-
20
-
21
- function getUserCookies() {
22
- const cookieSavedPath = path.join(getStoragePath(), '.cookies');
23
- return cookieStr || fs.readFileSync(cookieSavedPath, 'utf-8').trim();
24
- }
25
-
26
- async function checkSession() {
27
- const cookieSavedPath = path.join(getStoragePath(), '.cookies');
28
- const cookieExists = await fs.pathExists(cookieSavedPath);
29
- return cookieExists;
30
- }
31
-
32
- module.exports = {
33
- saveUserCookies,
34
- getUserCookies,
35
- checkSession
36
- }
@@ -1,245 +0,0 @@
1
- const archiver = require('archiver');
2
- const path = require('path');
3
- const fs = require('fs-extra');
4
- const glob = require('glob');
5
- const {
6
- getStoragePath
7
- } = require('./config');
8
- const previewFilePath = path.join(getStoragePath(), 'preview.json');
9
- fs.ensureFileSync(previewFilePath);
10
-
11
- function mixEncode(data) {
12
- const str = data.toString();
13
- const buff = [];
14
- let i, len;
15
- for (i = 0, len = str.length; i < len; i++) {
16
- buff.push(str.charCodeAt(i));
17
- }
18
- const results = buff.map(b => b ^ 5);
19
- const encode = [];
20
- for (i = 0, len = results.length; i < len; i++) {
21
- encode.push(results[i].toString(16));
22
- }
23
- return encode.join('');
24
- }
25
-
26
- async function zipFile(sourcePath, targetPath) {
27
- const subpackageInfoPath = path.join(sourcePath, 'game.json');
28
- const projectConfigJson = fs.readJSONSync(subpackageInfoPath);
29
- const subPackagesArr = projectConfigJson.subPackages || projectConfigJson.subpackages;
30
- const zipFileRet = {
31
- filePath: null,
32
- gameConfig: projectConfigJson,
33
- };
34
- if (subPackagesArr && subPackagesArr.length > 0) {
35
- const ifSubPackageUploadable = await verifySubPackageSize(projectConfigJson, sourcePath);
36
- if (ifSubPackageUploadable) {
37
- zipFileRet.filePath = await normalZipFile(sourcePath, targetPath, true);
38
- }
39
- } else {
40
- zipFileRet.filePath = await normalZipFile(sourcePath, targetPath, false);
41
- }
42
- return zipFileRet;
43
- }
44
-
45
- /**
46
- * @description 校验分包大小, 小游戏和小程序的不同在于子包不同
47
- */
48
- async function verifySubPackageSize(projectConfigJson, sourcePath) {
49
- let subPackageTotalSize = 0; // 子包+主包
50
- // 做大小比较全拿字节数,精确
51
- const packageSizeConfig = {
52
- mainPackageMaxSize: 4 * 1024 * 1024,
53
- subPackageSize: Infinity,
54
- totalSize: 20 * 1024 * 1024,
55
- };
56
- // console.log('校验', projectConfigJson, packageSizeConfig);
57
- // 开放数据域文件校验,可以认为开放数据域也作为一个子包
58
- if (projectConfigJson.openDataContext) {
59
- const openDataContextPath = path.join(sourcePath, projectConfigJson.openDataContext);
60
- const openDataContextSize = await getFolderSize(openDataContextPath);
61
- if (openDataContextSize > packageSizeConfig.subPackageSize) {
62
- console.error(
63
- `开放数据域文件大小为 ${getFormattedSize(
64
- openDataContextSize,
65
- )} MB, 超过 ${getFormattedSize(packageSizeConfig.subPackageSize)} MB,请调整包大小后再进行上传`,
66
- );
67
- return false;
68
- }
69
- subPackageTotalSize += openDataContextSize;
70
- }
71
- const totalPackageSize = await getFolderSize(sourcePath);
72
- if (totalPackageSize > packageSizeConfig.totalSize) {
73
- console.error(
74
- `小游戏包大小为 ${getFormattedSize(
75
- totalPackageSize,
76
- )} MB, 超过 20 MB,请调整包大小后再进行上传`,
77
- );
78
- return false;
79
- }
80
- const subPackagesArr = projectConfigJson.subPackages || projectConfigJson.subpackages;
81
- // 遍历子包数组,比较大小
82
- for (let subPackage of subPackagesArr) {
83
- const subPackagePath = path.join(sourcePath, subPackage.root);
84
- const subPackageSize = await getFolderSize(subPackagePath);
85
- if (subPackageSize > packageSizeConfig.subPackageSize) {
86
- console.error(
87
- `${subPackage.root}子包大小为 ${getFormattedSize(
88
- subPackageSize,
89
- )}MB, 超过${getFormattedSize(packageSizeConfig.subPackageSize)}MB,请调整包大小后再进行上传`,
90
- );
91
- return false;
92
- } else {
93
- console.log(
94
- `${subPackage.root}子包大小为 ${getFormattedSize(
95
- subPackageSize,
96
- )}MB, 符合上传 / 预览要求`,
97
- );
98
- }
99
- subPackageTotalSize += subPackageSize;
100
- }
101
-
102
- const mainPackageSize = totalPackageSize - subPackageTotalSize;
103
- if (mainPackageSize > packageSizeConfig.mainPackageMaxSize) {
104
- console.error(
105
- `主包大小为 ${getFormattedSize(mainPackageSize)}MB, 超过 4 MB,请调整包大小后再进行上传`,
106
- );
107
- return false;
108
- }
109
- console.log(`主包大小为 ${getFormattedSize(mainPackageSize)} MB, 符合上传 / 预览要求`)
110
- return true;
111
- }
112
-
113
- async function normalZipFile(sourcePath, targetPath, isSubPackage) {
114
-
115
- const packageSize = 8;
116
- const zipPath = path.join(targetPath, `${path.basename(sourcePath)}.zip`);
117
- return new Promise(function (resolve, reject) {
118
- const output = fs.createWriteStream(zipPath);
119
- const archive = archiver('zip');
120
-
121
- output.on('close', function () {
122
- // zip包生成以后,填写appId,更新日志,上传,打包
123
- if (!isSubPackage) {
124
- const stats = fs.statSync(zipPath)
125
- const fileSizeInBytes = stats["size"];
126
- const fileSizeMb = fileSizeInBytes / 1000000.0;
127
- if (fileSizeMb > packageSize) {
128
- return reject(`zip file is larger than ${packageSize}MB`)
129
- }
130
- }
131
- return resolve(zipPath);
132
- });
133
-
134
- archive.on('warning', function (err) {
135
- if (err.code === 'ENOENT') {
136
- // log warning
137
- } else {
138
- return reject(err)
139
- }
140
- });
141
-
142
- archive.on('error', function (err) {
143
- return reject(err)
144
- });
145
-
146
- archive.pipe(output);
147
-
148
- archive.glob('**/*', {
149
- cwd: sourcePath,
150
- ignore: ['.*/**/*', 'node_modules/**/*']
151
- }, {})
152
-
153
- archive.finalize(function (err, bytes) {
154
- if (err) {
155
- return reject(err);
156
- }
157
- });
158
- });
159
- }
160
-
161
- function compileErrFormat(errMsg = '') {
162
- errMsg = errMsg.split('\n').filter(item => !item.trim().startsWith('at'));
163
- return errMsg.join('\n');
164
- }
165
-
166
- function getPackageName() {
167
- return require(`../../package.json`).name;
168
- }
169
-
170
- function savePreviewResult(url, type, hash) {
171
- try {
172
- const currentResult = JSON.parse(fs.readFileSync(previewFilePath, 'utf-8') || '{}');
173
- currentResult[type] = url;
174
- currentResult.time = Date.now();
175
- currentResult.hash = hash;
176
- fs.writeFileSync(previewFilePath, JSON.stringify(currentResult));
177
- } catch (_) {
178
- // do not report such error
179
- }
180
- }
181
-
182
- /**
183
- * @description 输入字节数,返回MB字符串
184
- * @param [size] - number
185
- */
186
- function getFormattedSize(size) {
187
- const formattedSize = (size / 1024 / 1024).toFixed(2);
188
- return formattedSize;
189
- }
190
-
191
- function getCachedPreviewResult(type, hash) {
192
- try {
193
- const currentResult = JSON.parse(fs.readFileSync(previewFilePath, 'utf-8') || '{}');
194
- if (currentResult.hash === hash && currentResult[type]) {
195
- const cacheTime = currentResult.time;
196
- const daysPassed = (Date.now() - cacheTime || 0) / (60 * 60 * 1000 * 24);
197
- if (daysPassed < 1) {
198
- return currentResult[type];
199
- }
200
- }
201
- } catch (_) {
202
- // do not report such error
203
- }
204
- }
205
-
206
- function getFolderSize(folderPath, options = {}) {
207
- const stat = fs.statSync(folderPath);
208
- if (stat.isFile()) {
209
- return Promise.resolve(stat.size);
210
- }
211
- return new Promise((resolve, reject) => {
212
- glob(
213
- '**',
214
- {
215
- cwd: folderPath,
216
- ignore: options.ignore || ['**/.*', '**/node_modules/**', '**/**.js.map'],
217
- absolute: true,
218
- },
219
- (err, matches) => {
220
- if (err) {
221
- return reject(err);
222
- }
223
- try {
224
- let totalSize = 0;
225
- matches.forEach(file => {
226
- const stat = fs.statSync(file);
227
- if (!stat.isDirectory()) totalSize += stat.size;
228
- });
229
- resolve(totalSize);
230
- } catch (err) {
231
- reject(err);
232
- }
233
- },
234
- );
235
- });
236
- }
237
-
238
- module.exports = {
239
- mixEncode,
240
- zipFile,
241
- compileErrFormat,
242
- getPackageName,
243
- savePreviewResult,
244
- getCachedPreviewResult
245
- }