1
0
mirror of https://gitcode.com/github-mirrors/react-native-update-cli.git synced 2025-09-18 02:16:11 +08:00
Code Issues Packages Projects Releases Wiki Activity GitHub Gitee

Compare commits

..

34 Commits

Author SHA1 Message Date
sunnylqm
fbad603d05 sort key 2025-03-14 13:42:09 +08:00
sunnylqm
a1231f6a73 add deps 2025-03-14 13:42:09 +08:00
sunnylqm
f32b201778 init 2025-03-14 13:42:09 +08:00
Sunny Luo
613f39a59e Delete yarn.lock 2025-03-14 13:37:56 +08:00
sunnylqm
94c06e9908 add timeout for version query 2025-02-26 16:11:40 +08:00
sunnylqm
ac1a000a3b v1.41.0-beta.1 2025-02-21 11:43:24 +08:00
sunnylqm
4e51f291ca Refactor project configuration and dependencies
- Move IS_CRESC logic to constants module
- Update package.json with new type definitions
- Simplify global variable usage
- Update bun.lock with latest package versions
- Improve type safety and configuration management
2025-02-19 22:53:24 +08:00
sunnylqm
04b5d12daa deps 2025-02-19 22:24:54 +08:00
sunnylqm
67644b5c11 v1.41.0-beta.0 2025-02-19 22:06:24 +08:00
sunnylqm
546faef83f more cresc config 2025-02-18 22:37:09 +08:00
sunnylqm
e713f4bbd1 Bump package version to 1.40.1 2025-02-15 23:14:41 +08:00
sunnylqm
5a6463de33 Remove debug console.log in zip utility 2025-02-15 23:14:11 +08:00
sunnylqm
1fb308af94 Refactor i18n locales from JSON to TypeScript modules 2025-02-15 22:51:26 +08:00
sunnylqm
f10d4d3004 Add option to disable Hermes for React Native bundle 2025-02-15 21:40:28 +08:00
sunnylqm
0f44de772f init i18n 2025-02-15 00:38:55 +08:00
Sunny Luo
814a9d10fb Update package.json 2025-02-13 17:17:31 +08:00
sunnylqm
c08c5c0b07 fix taro cli path 2025-02-13 16:13:48 +08:00
sunnylqm
dc8c134ff0 v1.40.0-beta.0 2025-02-13 16:07:25 +08:00
sunnylqm
1d1e6cde0f support taro 2025-02-13 16:02:04 +08:00
sunny.luo
f16aff5674 Improve file filtering during bundle packing
# Conflicts:
#	package.json
#	src/bundle.js
2025-02-10 17:22:00 +08:00
Sunny Luo
d7da311c5e Update package.json 2025-02-09 16:15:04 +08:00
波仔糕
abef760f43 add logic to remove soucemap and merge sourcemap params (#9)
* add logic to remove soucemap and merge sourcemap params

* Update bundle.js

---------

Co-authored-by: Sunny Luo <sunnylqm@gmail.com>
2025-02-09 16:14:45 +08:00
Sunny Luo
467ef0c60d Update package.json 2025-01-23 23:15:22 +08:00
波仔糕
0b08c7760d Support sentry (#8)
* add logic to support sentry

* udpate

* change reference path

* support git commits and version info

* udate

* add try catch for require.resolve

* update upload sourcemap workflow
2025-01-23 22:02:13 +08:00
sunnylqm
b24b27d100 ts 2025-01-11 20:23:25 +08:00
sunnylqm
4f0784172f fix expo cli 2025-01-11 20:20:16 +08:00
sunnylqm
26725200b7 bump 2025-01-11 15:47:29 +08:00
sunnylqm
8bd31b8dc1 fix get 2025-01-11 15:45:28 +08:00
Sunny Luo
59f2421067 Update package.json 2025-01-09 21:00:29 +08:00
sunnylqm
8f0ca60d24 fix error message 2025-01-09 20:58:06 +08:00
Sunny Luo
6fcdb988c8 Merge pull request #6 from bozaigao/master
implement getAppInfo and uploadApp methods
2025-01-07 14:19:42 +08:00
HeYanbo
040f723305 implement getAppInfo and uploadApp methods 2025-01-07 13:52:28 +08:00
sunnylqm
12bddc446d Enhance package.json: add lint script and update devDependencies 2025-01-05 21:22:14 +08:00
sunnylqm
ba3d88627a support harmony 2025-01-05 21:16:52 +08:00
25 changed files with 1903 additions and 356 deletions

39
biome.json Normal file
View File

@@ -0,0 +1,39 @@
{
"files": {
"ignore": ["lib"]
},
"linter": {
"enabled": true,
"rules": {
"recommended": true,
"suspicious": {
"noExplicitAny": "off",
"noAssignInExpressions": "off",
"noDoubleEquals": "off"
},
"style": {
"noNonNullAssertion": "off"
},
"a11y": {
"useValidAnchor": "off"
},
"performance": {
"noDelete": "off"
}
}
},
"formatter": {
"enabled": true,
"formatWithErrors": false,
"indentStyle": "space",
"indentWidth": 2,
"lineEnding": "lf",
"lineWidth": 80,
"attributePosition": "auto"
},
"javascript": {
"formatter": {
"quoteStyle": "single"
}
}
}

1002
bun.lock Normal file

File diff suppressed because it is too large Load Diff

BIN
bun.lockb

Binary file not shown.

View File

@@ -33,6 +33,8 @@
}, },
"uploadIpa": {}, "uploadIpa": {},
"uploadApk": {}, "uploadApk": {},
"uploadApp": {},
"parseApp": {},
"parseIpa": {}, "parseIpa": {},
"parseApk": {}, "parseApk": {},
"packages": { "packages": {
@@ -143,6 +145,18 @@
}, },
"sourcemap": { "sourcemap": {
"default": false "default": false
},
"taro": {
"default": false
},
"expo": {
"default": false
},
"rncli": {
"default": false
},
"disableHermes": {
"default": false
} }
} }
}, },

View File

@@ -1,10 +1,11 @@
{ {
"name": "react-native-update-cli", "name": "react-native-update-cli",
"version": "1.36.0", "version": "1.42.0",
"description": "Command tools for javaScript updater with `pushy` service for react native apps.", "description": "Command tools for javaScript updater with `pushy` service for react native apps.",
"main": "index.js", "main": "index.js",
"bin": { "bin": {
"pushy": "lib/index.js" "pushy": "lib/index.js",
"cresc": "lib/index.js"
}, },
"files": [ "files": [
"lib", "lib",
@@ -13,7 +14,8 @@
], ],
"scripts": { "scripts": {
"build": "swc src -d lib --strip-leading-paths", "build": "swc src -d lib --strip-leading-paths",
"prepare": "npm run build && chmod +x lib/index.js" "prepare": "npm run build && chmod +x lib/index.js",
"lint": "tsc --noEmit & biome check --write ."
}, },
"repository": { "repository": {
"type": "git", "type": "git",
@@ -23,6 +25,7 @@
"react-native", "react-native",
"ios", "ios",
"android", "android",
"harmony",
"update" "update"
], ],
"author": "reactnativecn", "author": "reactnativecn",
@@ -44,6 +47,8 @@
"form-data": "^4.0.1", "form-data": "^4.0.1",
"fs-extra": "8", "fs-extra": "8",
"gradle-to-js": "^2.0.1", "gradle-to-js": "^2.0.1",
"i18next": "^24.2.2",
"isomorphic-git": "^1.29.0",
"isomorphic-unzip": "^1.1.5", "isomorphic-unzip": "^1.1.5",
"node-fetch": "^2.6.1", "node-fetch": "^2.6.1",
"plist": "^3.1.0", "plist": "^3.1.0",
@@ -61,11 +66,19 @@
"node": ">= 10" "node": ">= 10"
}, },
"devDependencies": { "devDependencies": {
"@biomejs/biome": "^1.9.4",
"@swc/cli": "^0.5.1", "@swc/cli": "^0.5.1",
"@swc/core": "^1.9.3", "@swc/core": "^1.9.3",
"@types/filesize-parser": "^1.5.3",
"@types/fs-extra": "^11.0.4",
"@types/node": "^22.9.3", "@types/node": "^22.9.3",
"oxlint": "^0.13.1", "@types/node-fetch": "^2.6.12",
"@types/progress": "^2.0.7",
"@types/semver": "^7.5.8",
"@types/tcp-ping": "^0.1.6",
"@types/update-notifier": "^6.0.8",
"@types/yauzl": "^2.10.3",
"@types/yazl": "^2.4.6",
"typescript": "^5.7.2" "typescript": "^5.7.2"
}, }
"packageManager": "yarn@1.22.22"
} }

View File

@@ -6,8 +6,8 @@ import ProgressBar from 'progress';
import packageJson from '../package.json'; import packageJson from '../package.json';
import tcpp from 'tcp-ping'; import tcpp from 'tcp-ping';
import filesizeParser from 'filesize-parser'; import filesizeParser from 'filesize-parser';
import { pricingPageUrl } from './utils'; import { pricingPageUrl, credentialFile, IS_CRESC } from './utils/constants';
import { Session } from 'types'; import type { Session } from 'types';
import FormData from 'form-data'; import FormData from 'form-data';
const tcpPing = util.promisify(tcpp.ping); const tcpPing = util.promisify(tcpp.ping);
@@ -15,87 +15,85 @@ const tcpPing = util.promisify(tcpp.ping);
let session: Session | undefined; let session: Session | undefined;
let savedSession: Session | undefined; let savedSession: Session | undefined;
const defaultEndpoint = 'https://update.reactnative.cn/api'; const defaultEndpoint = IS_CRESC
let host = process.env.PUSHY_REGISTRY || defaultEndpoint; ? 'https://api.cresc.dev'
: 'https://update.reactnative.cn/api';
const host =
process.env.PUSHY_REGISTRY || process.env.RNU_API || defaultEndpoint;
const userAgent = `react-native-update-cli/${packageJson.version}`; const userAgent = `react-native-update-cli/${packageJson.version}`;
export const getSession = function () { export const getSession = () => session;
return session;
};
export const replaceSession = function (newSession: { token: string }) { export const replaceSession = (newSession: { token: string }) => {
session = newSession; session = newSession;
}; };
export const loadSession = async function () { export const loadSession = async () => {
if (fs.existsSync('.update')) { if (fs.existsSync(credentialFile)) {
try { try {
replaceSession(JSON.parse(fs.readFileSync('.update', 'utf8'))); replaceSession(JSON.parse(fs.readFileSync(credentialFile, 'utf8')));
savedSession = session; savedSession = session;
} catch (e) { } catch (e) {
console.error( console.error(
'Failed to parse file `.update`. Try to remove it manually.', `Failed to parse file ${credentialFile}. Try to remove it manually.`,
); );
throw e; throw e;
} }
} }
}; };
export const saveSession = function () { export const saveSession = () => {
// Only save on change. // Only save on change.
if (session !== savedSession) { if (session !== savedSession) {
const current = session; const current = session;
const data = JSON.stringify(current, null, 4); const data = JSON.stringify(current, null, 4);
fs.writeFileSync('.update', data, 'utf8'); fs.writeFileSync(credentialFile, data, 'utf8');
savedSession = current; savedSession = current;
} }
}; };
export const closeSession = function () { export const closeSession = () => {
if (fs.existsSync('.update')) { if (fs.existsSync(credentialFile)) {
fs.unlinkSync('.update'); fs.unlinkSync(credentialFile);
savedSession = undefined; savedSession = undefined;
} }
session = undefined; session = undefined;
host = process.env.PUSHY_REGISTRY || defaultEndpoint;
}; };
async function query(url: string, options: fetch.RequestInit) { async function query(url: string, options: fetch.RequestInit) {
const resp = await fetch(url, options); const resp = await fetch(url, options);
const text = await resp.text(); const text = await resp.text();
let json; let json: any;
try { try {
json = JSON.parse(text); json = JSON.parse(text);
} catch (e) { } catch (e) {}
if (resp.statusText.includes('Unauthorized')) {
throw new Error('登录信息已过期,请使用 pushy login 命令重新登录');
} else {
throw new Error(`Server error: ${resp.statusText}`);
}
}
if (resp.status !== 200) { if (resp.status !== 200) {
throw new Error(`${resp.status}: ${resp.statusText}`); const message = json?.message || resp.statusText;
if (resp.status === 401) {
throw new Error('登录信息已过期,请使用 pushy login 命令重新登录');
}
throw new Error(message);
} }
return json; return json;
} }
function queryWithoutBody(method: string) { function queryWithoutBody(method: string) {
return function (api: string) { return (api: string) =>
return query(host + api, { query(host + api, {
method, method,
headers: { headers: {
'User-Agent': userAgent, 'User-Agent': userAgent,
'X-AccessToken': session ? session.token : '', 'X-AccessToken': session ? session.token : '',
}, },
}); });
};
} }
function queryWithBody(method: string) { function queryWithBody(method: string) {
return function (api: string, body: Record<string, any>) { return (api: string, body: Record<string, any>) =>
return query(host + api, { query(host + api, {
method, method,
headers: { headers: {
'User-Agent': userAgent, 'User-Agent': userAgent,
@@ -104,7 +102,6 @@ function queryWithBody(method: string) {
}, },
body: JSON.stringify(body), body: JSON.stringify(body),
}); });
};
} }
export const get = queryWithoutBody('GET'); export const get = queryWithoutBody('GET');
@@ -127,7 +124,7 @@ export async function uploadFile(fn: string, key?: string) {
timeout: 1000, timeout: 1000,
}); });
// console.log({pingResult}); // console.log({pingResult});
if (isNaN(pingResult.avg) || pingResult.avg > 150) { if (Number.isNaN(pingResult.avg) || pingResult.avg > 150) {
realUrl = backupUrl; realUrl = backupUrl;
} }
} }
@@ -143,7 +140,7 @@ export async function uploadFile(fn: string, key?: string) {
); );
} }
const bar = new ProgressBar(' 上传中 [:bar] :percent :etas', { const bar = new ProgressBar(' Uploading [:bar] :percent :etas', {
complete: '=', complete: '=',
incomplete: ' ', incomplete: ' ',
total: fileSize, total: fileSize,
@@ -151,11 +148,11 @@ export async function uploadFile(fn: string, key?: string) {
const form = new FormData(); const form = new FormData();
Object.entries(formData).forEach(([k, v]) => { for (const [k, v] of Object.entries(formData)) {
form.append(k, v); form.append(k, v);
}); }
const fileStream = fs.createReadStream(fn); const fileStream = fs.createReadStream(fn);
fileStream.on('data', function (data) { fileStream.on('data', (data) => {
bar.tick(data.length); bar.tick(data.length);
}); });

View File

@@ -1,22 +1,24 @@
import { question } from './utils'; import { question } from './utils';
import fs from 'fs'; import fs from 'node:fs';
import Table from 'tty-table'; import Table from 'tty-table';
import { post, get, doDelete } from './api'; import { post, get, doDelete } from './api';
import type { Platform } from './types';
const validPlatforms = { const validPlatforms = {
ios: 1, ios: 1,
android: 1, android: 1,
harmony: 1,
}; };
export function checkPlatform(platform) { export function checkPlatform(platform: Platform) {
if (!validPlatforms[platform]) { if (!validPlatforms[platform]) {
throw new Error(`无法识别的平台 '${platform}'`); throw new Error(`无法识别的平台 '${platform}'`);
} }
return platform; return platform;
} }
export function getSelectedApp(platform) { export function getSelectedApp(platform: Platform) {
checkPlatform(platform); checkPlatform(platform);
if (!fs.existsSync('update.json')) { if (!fs.existsSync('update.json')) {
@@ -33,7 +35,7 @@ export function getSelectedApp(platform) {
return updateInfo[platform]; return updateInfo[platform];
} }
export async function listApp(platform) { export async function listApp(platform: Platform) {
const { data } = await get('/app/list'); const { data } = await get('/app/list');
const list = platform ? data.filter((v) => v.platform === platform) : data; const list = platform ? data.filter((v) => v.platform === platform) : data;
@@ -57,12 +59,12 @@ export async function listApp(platform) {
return list; return list;
} }
export async function chooseApp(platform) { export async function chooseApp(platform: Platform) {
const list = await listApp(platform); const list = await listApp(platform);
while (true) { while (true) {
const id = await question('输入应用 id:'); const id = await question('输入应用 id:');
const app = list.find((v) => v.id === (id | 0)); const app = list.find((v) => v.id === Number(id));
if (app) { if (app) {
return app; return app;
} }
@@ -74,7 +76,7 @@ export const commands = {
const name = options.name || (await question('应用名称:')); const name = options.name || (await question('应用名称:'));
const { downloadUrl } = options; const { downloadUrl } = options;
const platform = checkPlatform( const platform = checkPlatform(
options.platform || (await question('平台(ios/android):')), options.platform || (await question('平台(ios/android/harmony):')),
); );
const { id } = await post('/app/create', { name, platform }); const { id } = await post('/app/create', { name, platform });
console.log(`已成功创建应用id: ${id}`); console.log(`已成功创建应用id: ${id}`);
@@ -83,7 +85,7 @@ export const commands = {
options: { platform, downloadUrl }, options: { platform, downloadUrl },
}); });
}, },
deleteApp: async function ({ args, options }) { deleteApp: async ({ args, options }) => {
const { platform } = options; const { platform } = options;
const id = args[0] || chooseApp(platform); const id = args[0] || chooseApp(platform);
if (!id) { if (!id) {
@@ -92,15 +94,17 @@ export const commands = {
await doDelete(`/app/${id}`); await doDelete(`/app/${id}`);
console.log('操作成功'); console.log('操作成功');
}, },
apps: async function ({ options }) { apps: async ({ options }) => {
const { platform } = options; const { platform } = options;
listApp(platform); listApp(platform);
}, },
selectApp: async function ({ args, options }) { selectApp: async ({ args, options }) => {
const platform = checkPlatform( const platform = checkPlatform(
options.platform || (await question('平台(ios/android):')), options.platform || (await question('平台(ios/android/harmony):')),
); );
const id = args[0] ? parseInt(args[0]) : (await chooseApp(platform)).id; const id = args[0]
? Number.parseInt(args[0])
: (await chooseApp(platform)).id;
let updateInfo = {}; let updateInfo = {};
if (fs.existsSync('update.json')) { if (fs.existsSync('update.json')) {

View File

@@ -1,17 +1,20 @@
import path from 'node:path'; import path from 'node:path';
import { getRNVersion, translateOptions } from './utils'; import { translateOptions } from './utils';
import * as fs from 'fs-extra'; import * as fs from 'fs-extra';
import { ZipFile } from 'yazl'; import { ZipFile } from 'yazl';
import { open as openZipFile } from 'yauzl'; import { open as openZipFile } from 'yauzl';
import { question, printVersionCommand } from './utils'; import { question, checkPlugins } from './utils';
import { checkPlatform } from './app'; import { checkPlatform } from './app';
import { spawn, spawnSync } from 'node:child_process'; import { spawn, spawnSync } from 'node:child_process';
import semverSatisfies from 'semver/functions/satisfies';
const g2js = require('gradle-to-js/lib/parser'); const g2js = require('gradle-to-js/lib/parser');
import os from 'os'; import os from 'node:os';
const properties = require('properties'); const properties = require('properties');
const path = require('path'); import { depVersions } from './utils/dep-versions';
let bsdiff, hdiff, diff; let bsdiff;
let hdiff;
let diff;
try { try {
bsdiff = require('node-bsdiff').diff; bsdiff = require('node-bsdiff').diff;
} catch (e) {} } catch (e) {}
@@ -20,16 +23,35 @@ try {
hdiff = require('node-hdiffpatch').diff; hdiff = require('node-hdiffpatch').diff;
} catch (e) {} } catch (e) {}
async function runReactNativeBundleCommand( async function runReactNativeBundleCommand({
bundleName, bundleName,
development, dev,
entryFile, entryFile,
outputFolder, outputFolder,
platform, platform,
sourcemapOutput, sourcemapOutput,
config, config,
) { disableHermes,
let gradleConfig = {}; cli,
}: {
bundleName: string;
dev: string;
entryFile: string;
outputFolder: string;
platform: string;
sourcemapOutput: string;
config?: string;
disableHermes?: boolean;
cli: {
taro?: boolean;
expo?: boolean;
rncli?: boolean;
};
}) {
let gradleConfig: {
crunchPngs?: boolean;
enableHermes?: boolean;
} = {};
if (platform === 'android') { if (platform === 'android') {
gradleConfig = await checkGradleConfig(); gradleConfig = await checkGradleConfig();
if (gradleConfig.crunchPngs !== false) { if (gradleConfig.crunchPngs !== false) {
@@ -39,9 +61,9 @@ async function runReactNativeBundleCommand(
} }
} }
let reactNativeBundleArgs = []; const reactNativeBundleArgs: string[] = [];
let envArgs = process.env.PUSHY_ENV_ARGS; const envArgs = process.env.PUSHY_ENV_ARGS;
if (envArgs) { if (envArgs) {
Array.prototype.push.apply( Array.prototype.push.apply(
@@ -52,15 +74,33 @@ async function runReactNativeBundleCommand(
fs.emptyDirSync(outputFolder); fs.emptyDirSync(outputFolder);
let cliPath; let cliPath: string | undefined;
let usingExpo = false; let usingExpo = false;
try {
cliPath = require.resolve('@expo/cli', { const getExpoCli = () => {
paths: [process.cwd()], try {
}); cliPath = require.resolve('@expo/cli', {
usingExpo = true; paths: [process.cwd()],
} catch (e) { });
const expoCliVersion = JSON.parse(
fs
.readFileSync(
require.resolve('@expo/cli/package.json', {
paths: [process.cwd()],
}),
)
.toString(),
).version;
// expo cli 0.10.17 (expo 49) 开始支持 bundle:embed
if (semverSatisfies(expoCliVersion, '>= 0.10.17')) {
usingExpo = true;
} else {
cliPath = undefined;
}
} catch (e) {}
};
const getRnCli = () => {
try { try {
// rn >= 0.75 // rn >= 0.75
cliPath = require.resolve('@react-native-community/cli/build/bin.js', { cliPath = require.resolve('@react-native-community/cli/build/bin.js', {
@@ -72,14 +112,49 @@ async function runReactNativeBundleCommand(
paths: [process.cwd()], paths: [process.cwd()],
}); });
} }
};
const getTaroCli = () => {
try {
cliPath = require.resolve('@tarojs/cli/bin/taro', {
paths: [process.cwd()],
});
} catch (e) {}
};
if (cli.expo) {
getExpoCli();
} else if (cli.taro) {
getTaroCli();
} else if (cli.rncli) {
getRnCli();
} }
const bundleCommand = usingExpo ? 'export:embed' : platform === 'harmony' ? 'bundle-harmony' : 'bundle';
if (platform == 'harmony') { if (!cliPath) {
getExpoCli();
if (!usingExpo) {
getRnCli();
}
}
const bundleParams = await checkPlugins();
const isSentry = bundleParams.sentry;
let bundleCommand = 'bundle';
if (usingExpo) {
bundleCommand = 'export:embed';
} else if (platform === 'harmony') {
bundleCommand = 'bundle-harmony';
} else if (cli.taro) {
bundleCommand = 'build';
}
if (platform === 'harmony') {
Array.prototype.push.apply(reactNativeBundleArgs, [ Array.prototype.push.apply(reactNativeBundleArgs, [
cliPath, cliPath,
bundleCommand, bundleCommand,
'--dev', '--dev',
development, dev,
'--entry-file', '--entry-file',
entryFile, entryFile,
]); ]);
@@ -91,8 +166,7 @@ async function runReactNativeBundleCommand(
if (config) { if (config) {
reactNativeBundleArgs.push('--config', config); reactNativeBundleArgs.push('--config', config);
} }
} } else {
else{
Array.prototype.push.apply(reactNativeBundleArgs, [ Array.prototype.push.apply(reactNativeBundleArgs, [
cliPath, cliPath,
bundleCommand, bundleCommand,
@@ -100,24 +174,26 @@ async function runReactNativeBundleCommand(
outputFolder, outputFolder,
'--bundle-output', '--bundle-output',
path.join(outputFolder, bundleName), path.join(outputFolder, bundleName),
'--dev',
development,
'--entry-file',
entryFile,
'--platform', '--platform',
platform, platform,
'--reset-cache', '--reset-cache',
]); ]);
if (cli.taro) {
reactNativeBundleArgs.push(...['--type', 'rn']);
} else {
reactNativeBundleArgs.push(...['--dev', dev, '--entry-file', entryFile]);
}
if (sourcemapOutput) { if (sourcemapOutput) {
reactNativeBundleArgs.push('--sourcemap-output', sourcemapOutput); reactNativeBundleArgs.push('--sourcemap-output', sourcemapOutput);
} }
if (config) { if (config) {
reactNativeBundleArgs.push('--config', config); reactNativeBundleArgs.push('--config', config);
} }
} }
const reactNativeBundleProcess = spawn('node', reactNativeBundleArgs); const reactNativeBundleProcess = spawn('node', reactNativeBundleArgs);
console.log( console.log(
`Running bundle command: node ${reactNativeBundleArgs.join(' ')}`, `Running bundle command: node ${reactNativeBundleArgs.join(' ')}`,
@@ -140,17 +216,22 @@ async function runReactNativeBundleCommand(
), ),
); );
} else { } else {
let hermesEnabled = false; let hermesEnabled: boolean | undefined = false;
if (platform === 'android') { if (disableHermes) {
const gradlePropeties = await new Promise((resolve) => { hermesEnabled = false;
console.log('Hermes disabled');
} else if (platform === 'android') {
const gradlePropeties = await new Promise<{
hermesEnabled?: boolean;
}>((resolve) => {
properties.parse( properties.parse(
'./android/gradle.properties', './android/gradle.properties',
{ path: true }, { path: true },
function (error, props) { (error: any, props: { hermesEnabled?: boolean }) => {
if (error) { if (error) {
console.error(error); console.error(error);
resolve(null); resolve({});
} }
resolve(props); resolve(props);
@@ -166,7 +247,7 @@ async function runReactNativeBundleCommand(
fs.existsSync('ios/Pods/hermes-engine') fs.existsSync('ios/Pods/hermes-engine')
) { ) {
hermesEnabled = true; hermesEnabled = true;
}else if (platform === 'harmony') { } else if (platform === 'harmony') {
await copyHarmonyBundle(outputFolder); await copyHarmonyBundle(outputFolder);
} }
if (hermesEnabled) { if (hermesEnabled) {
@@ -174,6 +255,7 @@ async function runReactNativeBundleCommand(
bundleName, bundleName,
outputFolder, outputFolder,
sourcemapOutput, sourcemapOutput,
!isSentry,
); );
} }
resolve(null); resolve(null);
@@ -182,18 +264,23 @@ async function runReactNativeBundleCommand(
}); });
} }
async function copyHarmonyBundle(outputFolder) { async function copyHarmonyBundle(outputFolder: string) {
const harmonyRawPath = 'harmony/entry/src/main/resources/rawfile'; const harmonyRawPath = 'harmony/entry/src/main/resources/rawfile';
try { try {
await fs.ensureDir(harmonyRawPath);
try {
await fs.access(harmonyRawPath, fs.constants.W_OK);
} catch (error) {
await fs.chmod(harmonyRawPath, 0o755);
}
await fs.remove(path.join(harmonyRawPath, 'update.json'));
await fs.copy('update.json', path.join(harmonyRawPath, 'update.json'));
await fs.ensureDir(outputFolder); await fs.ensureDir(outputFolder);
await fs.copy(harmonyRawPath, outputFolder); await fs.copy(harmonyRawPath, outputFolder);
} catch (error: any) {
console.log( console.error('copyHarmonyBundle 错误:', error);
`Successfully copied from ${harmonyRawPath} to ${outputFolder}`, throw new Error(`复制文件失败: ${error.message}`);
);
} catch (error) {
console.error('Error in copyHarmonyBundle:', error);
} }
} }
@@ -205,7 +292,7 @@ function getHermesOSBin() {
async function checkGradleConfig() { async function checkGradleConfig() {
let enableHermes = false; let enableHermes = false;
let crunchPngs; let crunchPngs: boolean | undefined;
try { try {
const gradleConfig = await g2js.parseFile('android/app/build.gradle'); const gradleConfig = await g2js.parseFile('android/app/build.gradle');
crunchPngs = gradleConfig.android.buildTypes.release.crunchPngs; crunchPngs = gradleConfig.android.buildTypes.release.crunchPngs;
@@ -229,11 +316,12 @@ async function checkGradleConfig() {
} }
async function compileHermesByteCode( async function compileHermesByteCode(
bundleName, bundleName: string,
outputFolder, outputFolder: string,
sourcemapOutput, sourcemapOutput: string,
shouldCleanSourcemap: boolean,
) { ) {
console.log(`Hermes enabled, now compiling to hermes bytecode:\n`); console.log('Hermes enabled, now compiling to hermes bytecode:\n');
// >= rn 0.69 // >= rn 0.69
const rnDir = path.dirname( const rnDir = path.dirname(
require.resolve('react-native', { require.resolve('react-native', {
@@ -259,13 +347,11 @@ async function compileHermesByteCode(
if (sourcemapOutput) { if (sourcemapOutput) {
fs.copyFileSync( fs.copyFileSync(
sourcemapOutput, sourcemapOutput,
path.join(outputFolder, bundleName + '.txt.map'), path.join(outputFolder, `${bundleName}.txt.map`),
); );
args.push('-output-source-map'); args.push('-output-source-map');
} }
console.log( console.log(`Running hermesc: ${hermesCommand} ${args.join(' ')}`);
'Running hermesc: ' + hermesCommand + ' ' + args.join(' ') + '\n',
);
spawnSync(hermesCommand, args, { spawnSync(hermesCommand, args, {
stdio: 'ignore', stdio: 'ignore',
}); });
@@ -275,13 +361,13 @@ async function compileHermesByteCode(
if (!fs.existsSync(composerPath)) { if (!fs.existsSync(composerPath)) {
return; return;
} }
console.log(`Composing source map`); console.log('Composing source map');
spawnSync( spawnSync(
'node', 'node',
[ [
composerPath, composerPath,
path.join(outputFolder, bundleName + '.txt.map'), path.join(outputFolder, `${bundleName}.txt.map`),
path.join(outputFolder, bundleName + '.map'), path.join(outputFolder, `${bundleName}.map`),
'-o', '-o',
sourcemapOutput, sourcemapOutput,
], ],
@@ -290,22 +376,120 @@ async function compileHermesByteCode(
}, },
); );
} }
fs.removeSync(path.join(outputFolder, bundleName + '.txt.map')); if (shouldCleanSourcemap) {
fs.removeSync(path.join(outputFolder, `${bundleName}.txt.map`));
}
} }
async function pack(dir, output) { async function copyDebugidForSentry(
bundleName: string,
outputFolder: string,
sourcemapOutput: string,
) {
if (sourcemapOutput) {
let copyDebugidPath;
try {
copyDebugidPath = require.resolve(
'@sentry/react-native/scripts/copy-debugid.js',
{
paths: [process.cwd()],
},
);
} catch (error) {
console.error(
'无法找到 Sentry copy-debugid.js 脚本文件,请确保已正确安装 @sentry/react-native',
);
return;
}
if (!fs.existsSync(copyDebugidPath)) {
return;
}
console.log('Copying debugid');
spawnSync(
'node',
[
copyDebugidPath,
path.join(outputFolder, `${bundleName}.txt.map`),
path.join(outputFolder, `${bundleName}.map`),
],
{
stdio: 'ignore',
},
);
}
fs.removeSync(path.join(outputFolder, `${bundleName}.txt.map`));
}
async function uploadSourcemapForSentry(
bundleName: string,
outputFolder: string,
sourcemapOutput: string,
version: string,
) {
if (sourcemapOutput) {
let sentryCliPath;
try {
sentryCliPath = require.resolve('@sentry/cli/bin/sentry-cli', {
paths: [process.cwd()],
});
} catch (error) {
console.error('无法找到 Sentry CLI 工具,请确保已正确安装 @sentry/cli');
return;
}
if (!fs.existsSync(sentryCliPath)) {
return;
}
spawnSync(
'node',
[sentryCliPath, 'releases', 'set-commits', version, '--auto'],
{
stdio: 'inherit',
},
);
console.log(`Sentry release created for version: ${version}`);
console.log('Uploading sourcemap');
spawnSync(
'node',
[
sentryCliPath,
'releases',
'files',
version,
'upload-sourcemaps',
'--strip-prefix',
path.join(process.cwd(), outputFolder),
path.join(outputFolder, bundleName),
path.join(outputFolder, `${bundleName}.map`),
],
{
stdio: 'inherit',
},
);
}
}
const ignorePackingFileNames = ['.', '..', 'index.bundlejs.map'];
const ignorePackingExtensions = ['DS_Store'];
async function pack(dir: string, output: string) {
console.log('Packing'); console.log('Packing');
fs.ensureDirSync(path.dirname(output)); fs.ensureDirSync(path.dirname(output));
await new Promise((resolve, reject) => { await new Promise<void>((resolve, reject) => {
const zipfile = new ZipFile(); const zipfile = new ZipFile();
function addDirectory(root, rel) { function addDirectory(root: string, rel: string) {
if (rel) { if (rel) {
zipfile.addEmptyDirectory(rel); zipfile.addEmptyDirectory(rel);
} }
const childs = fs.readdirSync(root); const childs = fs.readdirSync(root);
for (const name of childs) { for (const name of childs) {
if (name === '.' || name === '..' || name === 'index.bundlejs.map') { if (
ignorePackingFileNames.includes(name) ||
ignorePackingExtensions.some((ext) => name.endsWith(`.${ext}`))
) {
continue; continue;
} }
const fullPath = path.join(root, name); const fullPath = path.join(root, name);
@@ -315,30 +499,28 @@ async function pack(dir, output) {
zipfile.addFile(fullPath, rel + name); zipfile.addFile(fullPath, rel + name);
} else if (stat.isDirectory()) { } else if (stat.isDirectory()) {
//console.log('adding: ' + rel+name+'/'); //console.log('adding: ' + rel+name+'/');
addDirectory(fullPath, rel + name + '/'); addDirectory(fullPath, `${rel}${name}/`);
} }
} }
} }
addDirectory(dir, ''); addDirectory(dir, '');
zipfile.outputStream.on('error', (err) => reject(err)); zipfile.outputStream.on('error', (err: any) => reject(err));
zipfile.outputStream zipfile.outputStream.pipe(fs.createWriteStream(output)).on('close', () => {
.pipe(fs.createWriteStream(output)) resolve();
.on('close', function () { });
resolve();
});
zipfile.end(); zipfile.end();
}); });
console.log('ppk热更包已生成并保存到: ' + output); console.log(`ppk热更包已生成并保存到: ${output}`);
} }
function readEntire(entry, zipFile) { export function readEntire(entry: string, zipFile: ZipFile) {
const buffers = []; const buffers: Buffer[] = [];
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
zipFile.openReadStream(entry, (err, stream) => { zipFile.openReadStream(entry, (err: any, stream: any) => {
stream.pipe({ stream.pipe({
write(chunk) { write(chunk: Buffer) {
buffers.push(chunk); buffers.push(chunk);
}, },
end() { end() {
@@ -353,12 +535,12 @@ function readEntire(entry, zipFile) {
}); });
} }
function basename(fn) { function basename(fn: string) {
const m = /^(.+\/)[^\/]+\/?$/.exec(fn); const m = /^(.+\/)[^\/]+\/?$/.exec(fn);
return m && m[1]; return m?.[1];
} }
async function diffFromPPK(origin, next, output) { async function diffFromPPK(origin: string, next: string, output: string) {
fs.ensureDirSync(path.dirname(output)); fs.ensureDirSync(path.dirname(output));
const originEntries = {}; const originEntries = {};
@@ -372,7 +554,10 @@ async function diffFromPPK(origin, next, output) {
// isFile // isFile
originMap[entry.crc32] = entry.fileName; originMap[entry.crc32] = entry.fileName;
if (entry.fileName === 'index.bundlejs' || entry.fileName === 'bundle.harmony.js') { if (
entry.fileName === 'index.bundlejs' ||
entry.fileName === 'bundle.harmony.js'
) {
// This is source. // This is source.
return readEntire(entry, zipFile).then((v) => (originSource = v)); return readEntire(entry, zipFile).then((v) => (originSource = v));
} }
@@ -381,7 +566,7 @@ async function diffFromPPK(origin, next, output) {
if (!originSource) { if (!originSource) {
throw new Error( throw new Error(
`Bundle file not found! Please use default bundle file name and path.`, 'Bundle file not found! Please use default bundle file name and path.',
); );
} }
@@ -393,16 +578,14 @@ async function diffFromPPK(origin, next, output) {
zipfile.outputStream.on('error', (err) => { zipfile.outputStream.on('error', (err) => {
throw err; throw err;
}); });
zipfile.outputStream zipfile.outputStream.pipe(fs.createWriteStream(output)).on('close', () => {
.pipe(fs.createWriteStream(output)) resolve();
.on('close', function () { });
resolve();
});
}); });
const addedEntry = {}; const addedEntry = {};
function addEntry(fn) { function addEntry(fn: string) {
//console.log(fn); //console.log(fn);
if (!fn || addedEntry[fn]) { if (!fn || addedEntry[fn]) {
return; return;
@@ -434,7 +617,7 @@ async function diffFromPPK(origin, next, output) {
); );
//console.log('End diff'); //console.log('End diff');
}); });
}else if (entry.fileName === 'bundle.harmony.js') { } else if (entry.fileName === 'bundle.harmony.js') {
//console.log('Found bundle'); //console.log('Found bundle');
return readEntire(entry, nextZipfile).then((newSource) => { return readEntire(entry, nextZipfile).then((newSource) => {
//console.log('Begin diff'); //console.log('Begin diff');
@@ -466,7 +649,7 @@ async function diffFromPPK(origin, next, output) {
addEntry(basename(entry.fileName)); addEntry(basename(entry.fileName));
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
nextZipfile.openReadStream(entry, function (err, readStream) { nextZipfile.openReadStream(entry, (err, readStream) => {
if (err) { if (err) {
return reject(err); return reject(err);
} }
@@ -482,9 +665,9 @@ async function diffFromPPK(origin, next, output) {
const deletes = {}; const deletes = {};
for (let k in originEntries) { for (const k in originEntries) {
if (!newEntries[k]) { if (!newEntries[k]) {
console.log('Delete ' + k); console.log(`Delete ${k}`);
deletes[k] = 1; deletes[k] = 1;
} }
} }
@@ -499,11 +682,11 @@ async function diffFromPPK(origin, next, output) {
} }
async function diffFromPackage( async function diffFromPackage(
origin, origin: string,
next, next: string,
output, output: string,
originBundleName, originBundleName: string,
transformPackagePath = (v) => v, transformPackagePath = (v: string) => v,
) { ) {
fs.ensureDirSync(path.dirname(output)); fs.ensureDirSync(path.dirname(output));
@@ -512,7 +695,7 @@ async function diffFromPackage(
let originSource; let originSource;
await enumZipEntries(origin, (entry, zipFile) => { await enumZipEntries(origin, (entry: any, zipFile: any) => {
if (!/\/$/.test(entry.fileName)) { if (!/\/$/.test(entry.fileName)) {
const fn = transformPackagePath(entry.fileName); const fn = transformPackagePath(entry.fileName);
if (!fn) { if (!fn) {
@@ -533,7 +716,7 @@ async function diffFromPackage(
if (!originSource) { if (!originSource) {
throw new Error( throw new Error(
`Bundle file not found! Please use default bundle file name and path.`, 'Bundle file not found! Please use default bundle file name and path.',
); );
} }
@@ -545,11 +728,9 @@ async function diffFromPackage(
zipfile.outputStream.on('error', (err) => { zipfile.outputStream.on('error', (err) => {
throw err; throw err;
}); });
zipfile.outputStream zipfile.outputStream.pipe(fs.createWriteStream(output)).on('close', () => {
.pipe(fs.createWriteStream(output)) resolve();
.on('close', function () { });
resolve();
});
}); });
await enumZipEntries(next, (entry, nextZipfile) => { await enumZipEntries(next, (entry, nextZipfile) => {
@@ -576,7 +757,7 @@ async function diffFromPackage(
); );
//console.log('End diff'); //console.log('End diff');
}); });
}else { } else {
// If same file. // If same file.
if (originEntries[entry.fileName] === entry.crc32) { if (originEntries[entry.fileName] === entry.crc32) {
copies[entry.fileName] = ''; copies[entry.fileName] = '';
@@ -589,7 +770,7 @@ async function diffFromPackage(
} }
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
nextZipfile.openReadStream(entry, function (err, readStream) { nextZipfile.openReadStream(entry, (err, readStream) => {
if (err) { if (err) {
return reject(err); return reject(err);
} }
@@ -608,55 +789,66 @@ async function diffFromPackage(
await writePromise; await writePromise;
} }
async function enumZipEntries(zipFn, callback, nestedPath = '') { export async function enumZipEntries(
zipFn: string,
callback: (entry: any, zipFile: any) => void,
nestedPath = '',
) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
openZipFile(zipFn, { lazyEntries: true }, async (err, zipfile) => { openZipFile(
if (err) { zipFn,
return reject(err); { lazyEntries: true },
} async (err: any, zipfile: ZipFile) => {
if (err) {
zipfile.on('end', resolve); return reject(err);
zipfile.on('error', reject);
zipfile.on('entry', async (entry) => {
const fullPath = nestedPath + entry.fileName;
try {
if (
!entry.fileName.endsWith('/') &&
entry.fileName.toLowerCase().endsWith('.hap')
) {
const tempDir = path.join(os.tmpdir(), 'nested_zip_' + Date.now());
await fs.ensureDir(tempDir);
const tempZipPath = path.join(tempDir, 'temp.zip');
await new Promise((res, rej) => {
zipfile.openReadStream(entry, async (err, readStream) => {
if (err) return rej(err);
const writeStream = fs.createWriteStream(tempZipPath);
readStream.pipe(writeStream);
writeStream.on('finish', res);
writeStream.on('error', rej);
});
});
await enumZipEntries(tempZipPath, callback, fullPath + '/');
await fs.remove(tempDir);
}
const result = callback(entry, zipfile, fullPath);
if (result && typeof result.then === 'function') {
await result;
}
} catch (error) {
console.error('处理文件时出错:', error);
} }
zipfile.readEntry(); zipfile.on('end', resolve);
}); zipfile.on('error', reject);
zipfile.on('entry', async (entry) => {
const fullPath = nestedPath + entry.fileName;
zipfile.readEntry(); try {
}); if (
!entry.fileName.endsWith('/') &&
entry.fileName.toLowerCase().endsWith('.hap')
) {
const tempDir = path.join(
os.tmpdir(),
`nested_zip_${Date.now()}`,
);
await fs.ensureDir(tempDir);
const tempZipPath = path.join(tempDir, 'temp.zip');
await new Promise((res, rej) => {
zipfile.openReadStream(entry, async (err, readStream) => {
if (err) return rej(err);
const writeStream = fs.createWriteStream(tempZipPath);
readStream.pipe(writeStream);
writeStream.on('finish', res);
writeStream.on('error', rej);
});
});
await enumZipEntries(tempZipPath, callback, `${fullPath}/`);
await fs.remove(tempDir);
}
const result = callback(entry, zipfile, fullPath);
if (result && typeof result.then === 'function') {
await result;
}
} catch (error) {
console.error('处理文件时出错:', error);
}
zipfile.readEntry();
});
zipfile.readEntry();
},
);
}); });
} }
@@ -692,53 +884,80 @@ function diffArgsCheck(args, options, diffFn) {
return { return {
origin, origin,
next, next,
realOutput: output.replace(/\$\{time\}/g, '' + Date.now()), realOutput: output.replace(/\$\{time\}/g, `${Date.now()}`),
}; };
} }
export const commands = { export const commands = {
bundle: async function ({ options }) { bundle: async function ({ options }) {
const platform = checkPlatform( const platform = checkPlatform(
options.platform || (await question('平台(ios/android):')), options.platform || (await question('平台(ios/android/harmony):')),
); );
let { bundleName, entryFile, intermediaDir, output, dev, sourcemap } = const {
translateOptions({ bundleName,
...options, entryFile,
platform, intermediaDir,
}); output,
dev,
sourcemap,
taro,
expo,
rncli,
disableHermes,
} = translateOptions({
...options,
platform,
});
const sourcemapOutput = path.join(intermediaDir, bundleName + '.map'); const bundleParams = await checkPlugins();
const sourcemapPlugin = bundleParams.sourcemap;
const isSentry = bundleParams.sentry;
const realOutput = output.replace(/\$\{time\}/g, '' + Date.now()); const sourcemapOutput = path.join(intermediaDir, `${bundleName}.map`);
const realOutput = output.replace(/\$\{time\}/g, `${Date.now()}`);
if (!platform) { if (!platform) {
throw new Error('Platform must be specified.'); throw new Error('Platform must be specified.');
} }
const { version, major, minor } = getRNVersion(); console.log(`Bundling with react-native: ${depVersions['react-native']}`);
console.log('Bundling with react-native: ', version); await runReactNativeBundleCommand({
await runReactNativeBundleCommand(
bundleName, bundleName,
dev, dev,
entryFile, entryFile,
intermediaDir, outputFolder: intermediaDir,
platform, platform,
sourcemap ? sourcemapOutput : '', sourcemapOutput: sourcemap || sourcemapPlugin ? sourcemapOutput : '',
); disableHermes,
cli: {
taro,
expo,
rncli,
},
});
await pack(path.resolve(intermediaDir), realOutput); await pack(path.resolve(intermediaDir), realOutput);
const v = await question('是否现在上传此热更包?(Y/N)'); const v = await question('是否现在上传此热更包?(Y/N)');
if (v.toLowerCase() === 'y') { if (v.toLowerCase() === 'y') {
await this.publish({ const versionName = await this.publish({
args: [realOutput], args: [realOutput],
options: { options: {
platform, platform,
}, },
}); });
if (isSentry) {
await copyDebugidForSentry(bundleName, intermediaDir, sourcemapOutput);
await uploadSourcemapForSentry(
bundleName,
intermediaDir,
sourcemapOutput,
versionName,
);
}
} }
}, },
@@ -812,7 +1031,7 @@ export const commands = {
await diffFromPackage(origin, next, realOutput, 'main.jsbundle', (v) => { await diffFromPackage(origin, next, realOutput, 'main.jsbundle', (v) => {
const m = /^Payload\/[^/]+\/(.+)$/.exec(v); const m = /^Payload\/[^/]+\/(.+)$/.exec(v);
return m && m[1]; return m?.[1];
}); });
console.log(`${realOutput} generated.`); console.log(`${realOutput} generated.`);
@@ -827,7 +1046,7 @@ export const commands = {
await diffFromPackage(origin, next, realOutput, 'main.jsbundle', (v) => { await diffFromPackage(origin, next, realOutput, 'main.jsbundle', (v) => {
const m = /^Payload\/[^/]+\/(.+)$/.exec(v); const m = /^Payload\/[^/]+\/(.+)$/.exec(v);
return m && m[1]; return m?.[1];
}); });
console.log(`${realOutput} generated.`); console.log(`${realOutput} generated.`);

View File

@@ -2,8 +2,21 @@
import { loadSession } from './api'; import { loadSession } from './api';
import updateNotifier from 'update-notifier'; import updateNotifier from 'update-notifier';
import { printVersionCommand } from './utils/index.js'; import { printVersionCommand } from './utils';
import pkg from '../package.json'; import pkg from '../package.json';
import i18next from 'i18next';
import en from './locales/en';
import zh from './locales/zh';
import { IS_CRESC } from './utils/constants';
i18next.init({
lng: IS_CRESC ? 'en' : 'zh',
// debug: process.env.NODE_ENV !== 'production',
resources: {
en,
zh,
},
});
updateNotifier({ pkg }).notify({ updateNotifier({ pkg }).notify({
isGlobal: true, isGlobal: true,
@@ -39,7 +52,7 @@ async function run() {
const argv = require('cli-arguments').parse(require('../cli.json')); const argv = require('cli-arguments').parse(require('../cli.json'));
global.NO_INTERACTIVE = argv.options['no-interactive']; global.NO_INTERACTIVE = argv.options['no-interactive'];
global.USE_ACC_OSS = argv.options['acc']; global.USE_ACC_OSS = argv.options.acc;
loadSession() loadSession()
.then(() => commands[argv.command](argv)) .then(() => commands[argv.command](argv))

1
src/locales/en.ts Normal file
View File

@@ -0,0 +1 @@
export default {};

1
src/locales/zh.ts Normal file
View File

@@ -0,0 +1 @@
export default {};

View File

@@ -3,10 +3,11 @@ import { question, saveToLocal } from './utils';
import { checkPlatform, getSelectedApp } from './app'; import { checkPlatform, getSelectedApp } from './app';
import { getApkInfo, getIpaInfo } from './utils'; import { getApkInfo, getIpaInfo, getAppInfo } from './utils';
import Table from 'tty-table'; import Table from 'tty-table';
import { depVersions } from './utils/dep-versions';
export async function listPackage(appId) { export async function listPackage(appId: string) {
const { data } = await get(`/app/${appId}/package/list?limit=1000`); const { data } = await get(`/app/${appId}/package/list?limit=1000`);
const header = [{ value: '原生包 Id' }, { value: '原生版本' }]; const header = [{ value: '原生包 Id' }, { value: '原生版本' }];
@@ -35,12 +36,12 @@ export async function listPackage(appId) {
return data; return data;
} }
export async function choosePackage(appId) { export async function choosePackage(appId: string) {
const list = await listPackage(appId); const list = await listPackage(appId);
while (true) { while (true) {
const id = await question('输入原生包 id:'); const id = await question('输入原生包 id:');
const app = list.find((v) => v.id === (id | 0)); const app = list.find((v) => v.id === Number(id));
if (app) { if (app) {
return app; return app;
} }
@@ -48,7 +49,7 @@ export async function choosePackage(appId) {
} }
export const commands = { export const commands = {
uploadIpa: async function ({ args }) { uploadIpa: async ({ args }: { args: string[] }) => {
const fn = args[0]; const fn = args[0];
if (!fn || !fn.endsWith('.ipa')) { if (!fn || !fn.endsWith('.ipa')) {
throw new Error('使用方法: pushy uploadIpa ipa后缀文件'); throw new Error('使用方法: pushy uploadIpa ipa后缀文件');
@@ -79,13 +80,14 @@ export const commands = {
name: versionName, name: versionName,
hash, hash,
buildTime, buildTime,
deps: depVersions,
}); });
saveToLocal(fn, `${appId}/package/${id}.ipa`); saveToLocal(fn, `${appId}/package/${id}.ipa`);
console.log( console.log(
`已成功上传ipa原生包id: ${id}, version: ${versionName}, buildTime: ${buildTime}`, `已成功上传ipa原生包id: ${id}, version: ${versionName}, buildTime: ${buildTime}`,
); );
}, },
uploadApk: async function ({ args }) { uploadApk: async ({ args }) => {
const fn = args[0]; const fn = args[0];
if (!fn || !fn.endsWith('.apk')) { if (!fn || !fn.endsWith('.apk')) {
throw new Error('使用方法: pushy uploadApk apk后缀文件'); throw new Error('使用方法: pushy uploadApk apk后缀文件');
@@ -116,29 +118,75 @@ export const commands = {
name: versionName, name: versionName,
hash, hash,
buildTime, buildTime,
deps: depVersions,
}); });
saveToLocal(fn, `${appId}/package/${id}.apk`); saveToLocal(fn, `${appId}/package/${id}.apk`);
console.log( console.log(
`已成功上传apk原生包id: ${id}, version: ${versionName}, buildTime: ${buildTime}`, `已成功上传apk原生包id: ${id}, version: ${versionName}, buildTime: ${buildTime}`,
); );
}, },
parseIpa: async function ({ args }) { uploadApp: async ({ args }) => {
const fn = args[0];
if (!fn || !fn.endsWith('.app')) {
throw new Error('使用方法: pushy uploadApp app后缀文件');
}
const {
versionName,
buildTime,
appId: appIdInPkg,
appKey: appKeyInPkg,
} = await getAppInfo(fn);
const { appId, appKey } = await getSelectedApp('harmony');
if (appIdInPkg && appIdInPkg != appId) {
throw new Error(
`appId不匹配当前app: ${appIdInPkg}, 当前update.json: ${appId}`,
);
}
if (appKeyInPkg && appKeyInPkg !== appKey) {
throw new Error(
`appKey不匹配当前app: ${appKeyInPkg}, 当前update.json: ${appKey}`,
);
}
const { hash } = await uploadFile(fn);
const { id } = await post(`/app/${appId}/package/create`, {
name: versionName,
hash,
buildTime,
deps: depVersions,
});
saveToLocal(fn, `${appId}/package/${id}.app`);
console.log(
`已成功上传app原生包id: ${id}, version: ${versionName}, buildTime: ${buildTime}`,
);
},
parseApp: async ({ args }) => {
const fn = args[0];
if (!fn || !fn.endsWith('.app')) {
throw new Error('使用方法: pushy parseApp app后缀文件');
}
console.log(await getAppInfo(fn));
},
parseIpa: async ({ args }) => {
const fn = args[0]; const fn = args[0];
if (!fn || !fn.endsWith('.ipa')) { if (!fn || !fn.endsWith('.ipa')) {
throw new Error('使用方法: pushy parseIpa ipa后缀文件'); throw new Error('使用方法: pushy parseIpa ipa后缀文件');
} }
console.log(await getIpaInfo(fn)); console.log(await getIpaInfo(fn));
}, },
parseApk: async function ({ args }) { parseApk: async ({ args }) => {
const fn = args[0]; const fn = args[0];
if (!fn || !fn.endsWith('.apk')) { if (!fn || !fn.endsWith('.apk')) {
throw new Error('使用方法: pushy parseApk apk后缀文件'); throw new Error('使用方法: pushy parseApk apk后缀文件');
} }
console.log(await getApkInfo(fn)); console.log(await getApkInfo(fn));
}, },
packages: async function ({ options }) { packages: async ({ options }) => {
const platform = checkPlatform( const platform = checkPlatform(
options.platform || (await question('平台(ios/android):')), options.platform || (await question('平台(ios/android/harmony):')),
); );
const { appId } = await getSelectedApp(platform); const { appId } = await getSelectedApp(platform);
await listPackage(appId); await listPackage(appId);

View File

@@ -6,3 +6,5 @@ declare global {
export interface Session { export interface Session {
token: string; token: string;
} }
export type Platform = 'ios' | 'android' | 'harmony';

View File

@@ -1,13 +1,13 @@
import { question } from './utils'; import { question } from './utils';
import { post, get, replaceSession, saveSession, closeSession } from './api'; import { post, get, replaceSession, saveSession, closeSession } from './api';
import crypto from 'crypto'; import crypto from 'node:crypto';
function md5(str) { function md5(str: string) {
return crypto.createHash('md5').update(str).digest('hex'); return crypto.createHash('md5').update(str).digest('hex');
} }
export const commands = { export const commands = {
login: async function ({ args }) { login: async ({ args }: { args: string[] }) => {
const email = args[0] || (await question('email:')); const email = args[0] || (await question('email:'));
const pwd = args[1] || (await question('password:', true)); const pwd = args[1] || (await question('password:', true));
const { token, info } = await post('/user/login', { const { token, info } = await post('/user/login', {
@@ -18,11 +18,11 @@ export const commands = {
await saveSession(); await saveSession();
console.log(`欢迎使用 pushy 热更新服务, ${info.name}.`); console.log(`欢迎使用 pushy 热更新服务, ${info.name}.`);
}, },
logout: async function () { logout: async () => {
await closeSession(); await closeSession();
console.log('已退出登录'); console.log('已退出登录');
}, },
me: async function () { me: async () => {
const me = await get('/user/me'); const me = await get('/user/me');
for (const k in me) { for (const k in me) {
if (k !== 'ok') { if (k !== 'ok') {

View File

@@ -0,0 +1,16 @@
const Zip = require('./zip')
class AppParser extends Zip {
/**
* parser for parsing .apk file
* @param {String | File | Blob} file // file's path in Node, instance of File or Blob in Browser
*/
constructor (file) {
super(file)
if (!(this instanceof AppParser)) {
return new AppParser(file)
}
}
}
module.exports = AppParser

View File

@@ -1,35 +1,43 @@
const ApkParser = require('./apk') const ApkParser = require('./apk');
const IpaParser = require('./ipa') const IpaParser = require('./ipa');
const supportFileTypes = ['ipa', 'apk'] const AppParser = require('./app');
const supportFileTypes = ['ipa', 'apk', 'app'];
class AppInfoParser { class AppInfoParser {
/** /**
* parser for parsing .ipa or .apk file * parser for parsing .ipa or .apk file
* @param {String | File | Blob} file // file's path in Node, instance of File or Blob in Browser * @param {String | File | Blob} file // file's path in Node, instance of File or Blob in Browser
*/ */
constructor (file) { constructor(file) {
if (!file) { if (!file) {
throw new Error('Param miss: file(file\'s path in Node, instance of File or Blob in browser).') throw new Error(
"Param miss: file(file's path in Node, instance of File or Blob in browser).",
);
} }
const splits = (file.name || file).split('.') const splits = (file.name || file).split('.');
const fileType = splits[splits.length - 1].toLowerCase() const fileType = splits[splits.length - 1].toLowerCase();
if (!supportFileTypes.includes(fileType)) { if (!supportFileTypes.includes(fileType)) {
throw new Error('Unsupported file type, only support .ipa or .apk file.') throw new Error(
'Unsupported file type, only support .ipa or .apk or .app file.',
);
} }
this.file = file this.file = file;
switch (fileType) { switch (fileType) {
case 'ipa': case 'ipa':
this.parser = new IpaParser(this.file) this.parser = new IpaParser(this.file);
break break;
case 'apk': case 'apk':
this.parser = new ApkParser(this.file) this.parser = new ApkParser(this.file);
break break;
case 'app':
this.parser = new AppParser(this.file);
break;
} }
} }
parse () { parse() {
return this.parser.parse() return this.parser.parse();
} }
} }
module.exports = AppInfoParser module.exports = AppInfoParser;

View File

@@ -1,20 +1,23 @@
const Unzip = require('isomorphic-unzip') const Unzip = require('isomorphic-unzip');
const { isBrowser, decodeNullUnicode } = require('./utils') const { isBrowser, decodeNullUnicode } = require('./utils');
import { enumZipEntries, readEntire } from '../../bundle';
class Zip { class Zip {
constructor (file) { constructor(file) {
if (isBrowser()) { if (isBrowser()) {
if (!(file instanceof window.Blob || typeof file.size !== 'undefined')) { if (!(file instanceof window.Blob || typeof file.size !== 'undefined')) {
throw new Error('Param error: [file] must be an instance of Blob or File in browser.') throw new Error(
'Param error: [file] must be an instance of Blob or File in browser.',
);
} }
this.file = file this.file = file;
} else { } else {
if (typeof file !== 'string') { if (typeof file !== 'string') {
throw new Error('Param error: [file] must be file path in Node.') throw new Error('Param error: [file] must be file path in Node.');
} }
this.file = require('path').resolve(file) this.file = require('path').resolve(file);
} }
this.unzip = new Unzip(this.file) this.unzip = new Unzip(this.file);
} }
/** /**
@@ -22,27 +25,42 @@ class Zip {
* @param {Array} regexps // regexps for matching files * @param {Array} regexps // regexps for matching files
* @param {String} type // return type, can be buffer or blob, default buffer * @param {String} type // return type, can be buffer or blob, default buffer
*/ */
getEntries (regexps, type = 'buffer') { getEntries(regexps, type = 'buffer') {
regexps = regexps.map(regex => decodeNullUnicode(regex)) regexps = regexps.map((regex) => decodeNullUnicode(regex));
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.unzip.getBuffer(regexps, { type }, (err, buffers) => { this.unzip.getBuffer(regexps, { type }, (err, buffers) => {
err ? reject(err) : resolve(buffers) err ? reject(err) : resolve(buffers);
}) });
}) });
} }
/** /**
* get entry by regex, return an instance of Buffer or Blob * get entry by regex, return an instance of Buffer or Blob
* @param {Regex} regex // regex for matching file * @param {Regex} regex // regex for matching file
* @param {String} type // return type, can be buffer or blob, default buffer * @param {String} type // return type, can be buffer or blob, default buffer
*/ */
getEntry (regex, type = 'buffer') { getEntry(regex, type = 'buffer') {
regex = decodeNullUnicode(regex) regex = decodeNullUnicode(regex);
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.unzip.getBuffer([regex], { type }, (err, buffers) => { this.unzip.getBuffer([regex], { type }, (err, buffers) => {
err ? reject(err) : resolve(buffers[regex]) // console.log(buffers);
}) err ? reject(err) : resolve(buffers[regex]);
}) });
});
}
async getEntryFromHarmonyApp(regex) {
try {
let originSource;
await enumZipEntries(this.file, (entry, zipFile) => {
if (regex.test(entry.fileName)) {
return readEntire(entry, zipFile).then((v) => (originSource = v));
}
});
return originSource;
} catch (error) {
console.error('Error in getEntryFromHarmonyApp:', error);
}
} }
} }
module.exports = Zip module.exports = Zip;

28
src/utils/check-plugin.ts Normal file
View File

@@ -0,0 +1,28 @@
import { plugins } from './plugin-config';
interface BundleParams {
sentry: boolean;
sourcemap: boolean;
[key: string]: any;
}
export async function checkPlugins(): Promise<BundleParams> {
const params: BundleParams = {
sentry: false,
sourcemap: false,
};
for (const plugin of plugins) {
try {
const isEnabled = await plugin.detect();
if (isEnabled && plugin.bundleParams) {
Object.assign(params, plugin.bundleParams);
console.log(`检测到 ${plugin.name} 插件,应用相应打包配置`);
}
} catch (err) {
console.warn(`检测 ${plugin.name} 插件时出错:`, err);
}
}
return params;
}

13
src/utils/constants.ts Normal file
View File

@@ -0,0 +1,13 @@
import path from 'node:path';
const scriptName: 'cresc' | 'pushy' = path.basename(process.argv[1]) as
| 'cresc'
| 'pushy';
export const IS_CRESC = scriptName === 'cresc';
export const credentialFile = IS_CRESC ? '.cresc.token' : '.update';
export const updateJson = IS_CRESC ? 'cresc.config.json' : 'update.json';
export const tempDir = IS_CRESC ? '.cresc.temp' : '.pushy';
export const pricingPageUrl = IS_CRESC
? 'https://cresc.dev/pricing'
: 'https://pushy.reactnative.cn/pricing.html';

26
src/utils/dep-versions.ts Normal file
View File

@@ -0,0 +1,26 @@
const currentPackage = require(`${process.cwd()}/package.json`);
const depKeys = Object.keys(currentPackage.dependencies);
const devDepKeys = Object.keys(currentPackage.devDependencies);
const dedupedDeps = [...new Set([...depKeys, ...devDepKeys])];
const _depVersions: Record<string, string> = {};
for (const dep of dedupedDeps) {
try {
const packageJsonPath = require.resolve(`${dep}/package.json`, {
paths: [process.cwd()],
});
const version = require(packageJsonPath).version;
_depVersions[dep] = version;
} catch (e) {}
}
export const depVersions = Object.keys(_depVersions)
.sort() // Sort the keys alphabetically
.reduce((obj, key) => {
obj[key] = _depVersions[key]; // Rebuild the object with sorted keys
return obj;
}, {} as Record<string, string>);
// console.log({ depVersions });

View File

@@ -6,10 +6,13 @@ import AppInfoParser from './app-info-parser';
import semverSatisfies from 'semver/functions/satisfies'; import semverSatisfies from 'semver/functions/satisfies';
import chalk from 'chalk'; import chalk from 'chalk';
import latestVersion from '@badisi/latest-version'; import latestVersion from '@badisi/latest-version';
import { checkPlugins } from './check-plugin';
import { read } from 'read'; import { read } from 'read';
import { tempDir } from './constants';
import { depVersions } from './dep-versions';
export async function question(query, password) { export async function question(query: string, password?: boolean) {
if (NO_INTERACTIVE) { if (NO_INTERACTIVE) {
return ''; return '';
} }
@@ -20,14 +23,15 @@ export async function question(query, password) {
}); });
} }
export function translateOptions(options) { export function translateOptions(options: Record<string, string>) {
const ret = {}; const ret: Record<string, string> = {};
for (let key in options) { for (const key in options) {
const v = options[key]; const v = options[key];
if (typeof v === 'string') { if (typeof v === 'string') {
ret[key] = v.replace(/\$\{(\w+)\}/g, function (v, n) { ret[key] = v.replace(
return options[n] || process.env[n] || v; /\$\{(\w+)\}/g,
}); (v, n) => options[n] || process.env[n] || v,
);
} else { } else {
ret[key] = v; ret[key] = v;
} }
@@ -35,25 +39,7 @@ export function translateOptions(options) {
return ret; return ret;
} }
export function getRNVersion() { export async function getApkInfo(fn: string) {
const version = JSON.parse(
fs.readFileSync(
require.resolve('react-native/package.json', {
paths: [process.cwd()],
}),
),
).version;
// We only care about major and minor version.
const match = /^(\d+)\.(\d+)\./.exec(version);
return {
version,
major: match[1] | 0,
minor: match[2] | 0,
};
}
export async function getApkInfo(fn) {
const appInfoParser = new AppInfoParser(fn); const appInfoParser = new AppInfoParser(fn);
const bundleFile = await appInfoParser.parser.getEntry( const bundleFile = await appInfoParser.parser.getEntry(
/assets\/index.android.bundle/, /assets\/index.android.bundle/,
@@ -87,7 +73,44 @@ export async function getApkInfo(fn) {
return { versionName, buildTime, ...appCredential }; return { versionName, buildTime, ...appCredential };
} }
export async function getIpaInfo(fn) { export async function getAppInfo(fn) {
const appInfoParser = new AppInfoParser(fn);
const bundleFile = await appInfoParser.parser.getEntryFromHarmonyApp(
/rawfile\/bundle.harmony.js/,
);
if (!bundleFile) {
throw new Error(
'找不到bundle文件。请确保此app为release版本且bundle文件名为默认的bundle.harmony.js',
);
}
const updateJsonFile = await appInfoParser.parser.getEntryFromHarmonyApp(
/rawfile\/update.json/,
);
let appCredential = {};
if (updateJsonFile) {
appCredential = JSON.parse(updateJsonFile.toString()).harmony;
}
const metaJsonFile = await appInfoParser.parser.getEntryFromHarmonyApp(
/rawfile\/meta.json/,
);
let metaData = {};
if (metaJsonFile) {
metaData = JSON.parse(metaJsonFile.toString());
}
const { versionName, pushy_build_time } = metaData;
let buildTime = 0;
if (pushy_build_time) {
buildTime = pushy_build_time;
}
if (buildTime == 0) {
throw new Error(
'无法获取此包的编译时间戳。请更新 react-native-update 到最新版本后重新打包上传。',
);
}
return { versionName, buildTime, ...appCredential };
}
export async function getIpaInfo(fn: string) {
const appInfoParser = new AppInfoParser(fn); const appInfoParser = new AppInfoParser(fn);
const bundleFile = await appInfoParser.parser.getEntry( const bundleFile = await appInfoParser.parser.getEntry(
/payload\/.+?\.app\/main.jsbundle/, /payload\/.+?\.app\/main.jsbundle/,
@@ -124,26 +147,31 @@ export async function getIpaInfo(fn) {
return { versionName, buildTime, ...appCredential }; return { versionName, buildTime, ...appCredential };
} }
const localDir = path.resolve(os.homedir(), '.pushy'); const localDir = path.resolve(os.homedir(), tempDir);
fs.ensureDirSync(localDir); fs.ensureDirSync(localDir);
export function saveToLocal(originPath, destName) { export function saveToLocal(originPath: string, destName: string) {
// TODO // TODO
// const destPath = path.join(localDir, destName); // const destPath = path.join(localDir, destName);
// fs.ensureDirSync(path.dirname(destPath)); // fs.ensureDirSync(path.dirname(destPath));
// fs.copyFileSync(originPath, destPath); // fs.copyFileSync(originPath, destPath);
} }
async function getLatestVersion(pkgName) { async function getLatestVersion(pkgNames: string[]) {
return Promise.race([ return latestVersion(pkgNames, {
latestVersion(pkgName) useCache: true,
.then((p) => p.latest) requestOptions: {
.catch(() => ''), timeout: 2000,
new Promise((resolve) => setTimeout(() => resolve(''), 2000)), },
]); })
.then((pkgs) => pkgs.map((pkg) => pkg.latest))
.catch(() => []);
} }
export async function printVersionCommand() { export async function printVersionCommand() {
let latestPushyCliVersion = await getLatestVersion('react-native-update-cli'); let [latestPushyCliVersion, latestPushyVersion] = await getLatestVersion([
'react-native-update-cli',
'react-native-update',
]);
latestPushyCliVersion = latestPushyCliVersion latestPushyCliVersion = latestPushyCliVersion
? ` (最新:${chalk.green(latestPushyCliVersion)}` ? ` (最新:${chalk.green(latestPushyCliVersion)}`
: ''; : '';
@@ -151,22 +179,11 @@ export async function printVersionCommand() {
`react-native-update-cli: ${pkg.version}${latestPushyCliVersion}`, `react-native-update-cli: ${pkg.version}${latestPushyCliVersion}`,
); );
let pushyVersion = ''; let pushyVersion = '';
try { pushyVersion = depVersions['react-native-update'];
const PACKAGE_JSON_PATH = require.resolve( latestPushyVersion = latestPushyVersion
'react-native-update/package.json', ? ` (最新:${chalk.green(latestPushyVersion)}`
{ : '';
paths: [process.cwd()], console.log(`react-native-update: ${pushyVersion}${latestPushyVersion}`);
},
);
pushyVersion = require(PACKAGE_JSON_PATH).version;
let latestPushyVersion = await getLatestVersion('react-native-update');
latestPushyVersion = latestPushyVersion
? ` (最新:${chalk.green(latestPushyVersion)}`
: '';
console.log(`react-native-update: ${pushyVersion}${latestPushyVersion}`);
} catch (e) {
console.log('react-native-update: 无法获取版本号,请在项目目录中运行命令');
}
if (pushyVersion) { if (pushyVersion) {
if (semverSatisfies(pushyVersion, '<8.5.2')) { if (semverSatisfies(pushyVersion, '<8.5.2')) {
console.warn( console.warn(
@@ -180,10 +197,12 @@ export async function printVersionCommand() {
); );
} else if (semverSatisfies(pushyVersion, '10.0.0 - 10.17.0')) { } else if (semverSatisfies(pushyVersion, '10.0.0 - 10.17.0')) {
console.warn( console.warn(
`当前版本已不再支持,请升级到 v10 的最新小版本(代码无需改动,可直接热更): npm i react-native-update@10`, '当前版本已不再支持,请升级到 v10 的最新小版本(代码无需改动,可直接热更): npm i react-native-update@10',
); );
} }
} else {
console.log('react-native-update: 无法获取版本号,请在项目目录中运行命令');
} }
} }
export const pricingPageUrl = 'https://pushy.reactnative.cn/pricing.html'; export { checkPlugins };

24
src/utils/lock-checker.ts Normal file
View File

@@ -0,0 +1,24 @@
const lockFiles = [
'package-lock.json',
'yarn.lock',
'pnpm-lock.yaml',
'bun.lockb',
'bun.lock',
];
const lockNotFound = `
没有检测到任何 lock 文件,这可能导致依赖关系不一致而使热更异常。
`;
const multipleLocksFound = `
检测到多个锁文件(),这可能导致依赖关系不一致而使热更异常。
`;
const lockBestPractice = `
关于 lock 文件的最佳实践:
1. 开发团队中的所有成员应该使用相同的包管理器,维护同一份 lock 文件。
2. 将 lock 文件添加到版本控制中(但不要同时提交多种不同格式的 lock 文件)。
3. 代码审核时应关注 lock 文件的变化。
这样可以最大限度避免因依赖关系不一致而导致的热更异常,也降低供应链攻击等安全隐患。
`;

View File

@@ -0,0 +1,32 @@
import fs from 'fs-extra';
interface PluginConfig {
name: string;
bundleParams?: {
[key: string]: any;
};
detect: () => Promise<boolean>;
}
export const plugins: PluginConfig[] = [
{
name: 'sentry',
bundleParams: {
sentry: true,
sourcemap: true,
},
detect: async () => {
try {
await fs.access('ios/sentry.properties');
return true;
} catch {
try {
await fs.access('android/sentry.properties');
return true;
} catch {
return false;
}
}
}
}
];

View File

@@ -4,8 +4,9 @@ import { question, saveToLocal } from './utils';
import { checkPlatform, getSelectedApp } from './app'; import { checkPlatform, getSelectedApp } from './app';
import { choosePackage } from './package'; import { choosePackage } from './package';
import { compare } from 'compare-versions'; import { compare } from 'compare-versions';
import { depVersions } from './utils/dep-versions';
async function showVersion(appId, offset) { async function showVersion(appId: string, offset: number) {
const { data, count } = await get(`/app/${appId}/version/list`); const { data, count } = await get(`/app/${appId}/version/list`);
console.log(`Offset ${offset}`); console.log(`Offset ${offset}`);
for (const version of data) { for (const version of data) {
@@ -13,12 +14,12 @@ async function showVersion(appId, offset) {
.slice(0, 3) .slice(0, 3)
.map((v) => v.name) .map((v) => v.name)
.join(', '); .join(', ');
const count = version.packages.length; const pkgCount = version.packages.length;
if (count > 3) { if (pkgCount > 3) {
packageInfo += `...and ${count - 3} more`; packageInfo += `...and ${pkgCount - 3} more`;
} }
if (count === 0) { if (pkgCount === 0) {
packageInfo = `(no package)`; packageInfo = 'no package';
} else { } else {
packageInfo = `[${packageInfo}]`; packageInfo = `[${packageInfo}]`;
} }
@@ -31,7 +32,7 @@ async function showVersion(appId, offset) {
return data; return data;
} }
async function listVersions(appId) { async function listVersions(appId: string) {
let offset = 0; let offset = 0;
while (true) { while (true) {
await showVersion(appId, offset); await showVersion(appId, offset);
@@ -52,7 +53,7 @@ async function listVersions(appId) {
} }
} }
async function chooseVersion(appId) { async function chooseVersion(appId: string) {
let offset = 0; let offset = 0;
while (true) { while (true) {
const data = await showVersion(appId, offset); const data = await showVersion(appId, offset);
@@ -86,22 +87,24 @@ export const commands = {
if (!fn || !fn.endsWith('.ppk')) { if (!fn || !fn.endsWith('.ppk')) {
throw new Error( throw new Error(
'使用方法: pushy publish ppk后缀文件 --platform ios|android', '使用方法: pushy publish ppk后缀文件 --platform ios|android|harmony',
); );
} }
const platform = checkPlatform( const platform = checkPlatform(
options.platform || (await question('平台(ios/android):')), options.platform || (await question('平台(ios/android/harmony):')),
); );
const { appId } = await getSelectedApp(platform); const { appId } = await getSelectedApp(platform);
const { hash } = await uploadFile(fn); const { hash } = await uploadFile(fn);
const versionName = name || (await question('输入版本名称: ')) || '(未命名)';
const { id } = await post(`/app/${appId}/version/create`, { const { id } = await post(`/app/${appId}/version/create`, {
name: name || (await question('输入版本名称: ')) || '(未命名)', name: versionName,
hash, hash,
description: description || (await question('输入版本描述:')), description: description || (await question('输入版本描述:')),
metaInfo: metaInfo || (await question('输入自定义的 meta info:')), metaInfo: metaInfo || (await question('输入自定义的 meta info:')),
deps: depVersions,
}); });
// TODO local diff // TODO local diff
saveToLocal(fn, `${appId}/ppk/${id}.ppk`); saveToLocal(fn, `${appId}/ppk/${id}.ppk`);
@@ -111,17 +114,18 @@ export const commands = {
if (v.toLowerCase() === 'y') { if (v.toLowerCase() === 'y') {
await this.update({ args: [], options: { versionId: id, platform } }); await this.update({ args: [], options: { versionId: id, platform } });
} }
return versionName;
}, },
versions: async function ({ options }) { versions: async ({ options }) => {
const platform = checkPlatform( const platform = checkPlatform(
options.platform || (await question('平台(ios/android):')), options.platform || (await question('平台(ios/android/harmony):')),
); );
const { appId } = await getSelectedApp(platform); const { appId } = await getSelectedApp(platform);
await listVersions(appId); await listVersions(appId);
}, },
update: async function ({ args, options }) { update: async ({ args, options }) => {
const platform = checkPlatform( const platform = checkPlatform(
options.platform || (await question('平台(ios/android):')), options.platform || (await question('平台(ios/android/harmony):')),
); );
const { appId } = await getSelectedApp(platform); const { appId } = await getSelectedApp(platform);
let versionId = options.versionId || (await chooseVersion(appId)).id; let versionId = options.versionId || (await chooseVersion(appId)).id;
@@ -138,7 +142,7 @@ export const commands = {
rollout = null; rollout = null;
} else { } else {
try { try {
rollout = parseInt(rollout); rollout = Number.parseInt(rollout);
} catch (e) { } catch (e) {
throw new Error('rollout 必须是 1-100 的整数'); throw new Error('rollout 必须是 1-100 的整数');
} }
@@ -173,7 +177,9 @@ export const commands = {
await put(`/app/${appId}/package/${pkg.id}`, { await put(`/app/${appId}/package/${pkg.id}`, {
versionId, versionId,
}); });
console.log(`已将热更版本 ${versionId} 绑定到原生版本 ${pkg.name} (id: ${pkg.id})`); console.log(
`已将热更版本 ${versionId} 绑定到原生版本 ${pkg.name} (id: ${pkg.id})`,
);
} }
console.log(`操作完成,共已绑定 ${pkgs.length} 个原生版本`); console.log(`操作完成,共已绑定 ${pkgs.length} 个原生版本`);
return; return;
@@ -205,7 +211,9 @@ export const commands = {
await put(`/app/${appId}/package/${pkg.id}`, { await put(`/app/${appId}/package/${pkg.id}`, {
versionId, versionId,
}); });
console.log(`已将热更版本 ${versionId} 绑定到原生版本 ${pkg.name} (id: ${pkg.id})`); console.log(
`已将热更版本 ${versionId} 绑定到原生版本 ${pkg.name} (id: ${pkg.id})`,
);
} }
console.log(`操作完成,共已绑定 ${pkgs.length} 个原生版本`); console.log(`操作完成,共已绑定 ${pkgs.length} 个原生版本`);
return; return;
@@ -228,14 +236,14 @@ export const commands = {
if (!pkgId) { if (!pkgId) {
throw new Error('请提供 packageId 或 packageVersion 参数'); throw new Error('请提供 packageId 或 packageVersion 参数');
} }
if (!pkgVersion) { if (!pkgVersion) {
const pkg = data.find((d) => d.id === pkgId); const pkg = data.find((d) => d.id === pkgId);
if (pkg) { if (pkg) {
pkgVersion = pkg.name; pkgVersion = pkg.name;
} }
} }
if (rollout) { if (rollout) {
await put(`/app/${appId}/version/${versionId}`, { await put(`/app/${appId}/version/${versionId}`, {
config: { config: {
@@ -251,11 +259,13 @@ export const commands = {
await put(`/app/${appId}/package/${pkgId}`, { await put(`/app/${appId}/package/${pkgId}`, {
versionId, versionId,
}); });
console.log(`已将热更版本 ${versionId} 绑定到原生版本 ${pkgVersion} (id: ${pkgId})`); console.log(
`已将热更版本 ${versionId} 绑定到原生版本 ${pkgVersion} (id: ${pkgId})`,
);
}, },
updateVersionInfo: async function ({ args, options }) { updateVersionInfo: async ({ args, options }) => {
const platform = checkPlatform( const platform = checkPlatform(
options.platform || (await question('平台(ios/android):')), options.platform || (await question('平台(ios/android/harmony):')),
); );
const { appId } = await getSelectedApp(platform); const { appId } = await getSelectedApp(platform);
const versionId = options.versionId || (await chooseVersion(appId)).id; const versionId = options.versionId || (await chooseVersion(appId)).id;

View File

@@ -52,9 +52,9 @@
] /* List of folders to include type definitions from. */, ] /* List of folders to include type definitions from. */,
// "types": [], /* Type declaration files to be included in compilation. */ // "types": [], /* Type declaration files to be included in compilation. */
"allowSyntheticDefaultImports": true /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */, "allowSyntheticDefaultImports": true /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */,
// "paths": { "paths": {
// "@/*": ["src/*"] "@/*": ["src/*"]
// }, },
"resolveJsonModule": true, "resolveJsonModule": true,
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */