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

Compare commits

...

22 Commits

Author SHA1 Message Date
sunnylqm
818907f811 Refactor rollout configuration handling in bindVersionToPackages; replace rollout logic with direct package binding and update API call to use POST method. 2025-11-04 21:52:25 +08:00
sunnylqm
6751daf8e0 Update version to 2.3.2 in package.json and enhance search paths for @expo/cli in runReactNativeBundleCommand to include expo package directory. 2025-10-31 16:07:02 +08:00
sunnylqm
b973ace443 Update version to 2.3.1 in package.json and add support for harmony platform in runReactNativeBundleCommand to handle asset copying and file movement. 2025-10-26 18:05:18 +08:00
sunnylqm
e81744b52a Refactor bundle file handling by introducing isPPKBundleFileName utility; streamline diff logic for bundle files in bundle.ts. 2025-10-25 16:07:41 +08:00
sunnylqm
89da1e5238 fix typo 2025-10-25 15:52:53 +08:00
sunnylqm
603e2adf47 add install command 2025-10-25 15:49:35 +08:00
sunnylqm
317975cdba Update version to 2.3.0 in package.json 2025-10-25 12:19:18 +08:00
sunnylqm
f8edbb8083 Refactor Hermes option handling in CLI and bundle commands; rename 'disableHermes' to 'hermes' for clarity and update related logic in bundle.ts and provider.ts. 2025-10-25 11:20:09 +08:00
sunnylqm
15c8052459 Update version to 2.2.4 in package.json and enhance argument handling in runReactNativeBundleCommand for improved functionality. 2025-10-25 10:53:50 +08:00
sunnylqm
c633af549d Update version to 2.2.3 in package.json and implement recursive file copying with special handling for assets in bundle.ts 2025-10-24 23:58:57 +08:00
sunnylqm
78159f362b Update version to 2.2.2 in package.json and refactor argument handling in runReactNativeBundleCommand for better clarity and efficiency. 2025-10-24 22:04:24 +08:00
sunnylqm
b76440d018 Update version to 2.2.1 in package.json and refactor argument handling in runReactNativeBundleCommand for improved clarity and efficiency. 2025-10-24 20:41:46 +08:00
Sunny Luo
e3c951bc1b Update package.json 2025-09-23 15:37:35 +08:00
波仔糕
f6ed8872bd add logic to support android aab package hot update (#17)
* add logic to support android aab package hot update

* update

* udpate
2025-09-23 15:22:34 +08:00
sunnylqm
fd46bafb98 Update version to 2.1.3 in package.json; set baseUrl in .swcrc; refactor API query logic to use dynamic base URL and update defaultEndpoints in constants.ts 2025-09-14 17:25:35 +08:00
sunny.ll
917f99f2ab Fix package selection logic to match by package name instead of version; improve error handling for package retrieval. 2025-09-10 17:11:12 +08:00
sunny.ll
ac13464d4d Enhance package command options to include packageId and packageVersion; improve package selection logic with error handling for missing packages. 2025-09-10 16:18:34 +08:00
sunny.ll
f82bab887a Remove console log for module registration in module-manager.ts 2025-09-10 15:38:56 +08:00
sunny.ll
07ff19fbe5 Update version to 2.1.1 in package.json and improve error handling for package loading in dep-versions.ts 2025-09-10 11:05:24 +08:00
sunny.ll
a4467717bc Add deletePackage command with confirmation and error handling; update version to 2.1.0 and enhance localization for delete operations 2025-09-09 12:34:06 +08:00
Sunny Luo
cd890347d1 Update package.json 2025-08-26 09:50:25 +08:00
sunnylqm
e6de3eeef3 Enhance upload commands to support custom versioning and update documentation. Added version option to uploadIpa, uploadApk, and uploadApp commands. Updated README and localization files to reflect changes. 2025-08-22 10:09:37 +08:00
23 changed files with 710 additions and 413 deletions

5
.gitignore vendored
View File

@@ -104,4 +104,7 @@ dist
.tern-port
lib/
.DS_Store
.DS_Store
# react-native-update
.update
.pushy

1
.swcrc
View File

@@ -1,5 +1,6 @@
{
"jsc": {
"baseUrl": "./src",
"loose": true,
"target": "es2018",
"parser": {

177
README.md
View File

@@ -49,14 +49,14 @@ const provider = moduleManager.getProvider();
const bundleResult = await provider.bundle({
platform: 'ios',
dev: false,
sourcemap: true
sourcemap: true,
});
// Publish version
const publishResult = await provider.publish({
name: 'v1.2.3',
description: 'Bug fixes and improvements',
rollout: 100
rollout: 100,
});
```
@@ -65,12 +65,16 @@ const publishResult = await provider.publish({
### 1. Define Module
```typescript
import type { CLIModule, CommandDefinition, CustomWorkflow } from 'react-native-update-cli';
import type {
CLIModule,
CommandDefinition,
CustomWorkflow,
} from 'react-native-update-cli';
export const myCustomModule: CLIModule = {
name: 'my-custom',
version: '1.0.0',
commands: [
{
name: 'custom-command',
@@ -79,15 +83,15 @@ export const myCustomModule: CLIModule = {
console.log('Executing custom command...');
return {
success: true,
data: { message: 'Custom command executed' }
data: { message: 'Custom command executed' },
};
},
options: {
param: { hasValue: true, description: 'Custom parameter' }
}
}
param: { hasValue: true, description: 'Custom parameter' },
},
},
],
workflows: [
{
name: 'my-workflow',
@@ -99,7 +103,7 @@ export const myCustomModule: CLIModule = {
execute: async (context, previousResult) => {
console.log('Executing step 1...');
return { step1Completed: true };
}
},
},
{
name: 'step2',
@@ -107,19 +111,19 @@ export const myCustomModule: CLIModule = {
execute: async (context, previousResult) => {
console.log('Executing step 2...');
return { ...previousResult, step2Completed: true };
}
}
]
}
},
},
],
},
],
init: (provider) => {
console.log('Custom module initialized');
},
cleanup: () => {
console.log('Custom module cleanup');
}
},
};
```
@@ -135,13 +139,13 @@ moduleManager.registerModule(myCustomModule);
// Execute custom command
const result = await moduleManager.executeCommand('custom-command', {
args: [],
options: { param: 'value' }
options: { param: 'value' },
});
// Execute custom workflow
const workflowResult = await moduleManager.executeWorkflow('my-workflow', {
args: [],
options: {}
options: {},
});
```
@@ -191,6 +195,7 @@ Each workflow step contains:
## 📋 Built-in Modules
### Bundle Module (`bundle`)
- `bundle`: Bundle JavaScript code and optionally publish
- `diff`: Generate differences between two PPK files
- `hdiff`: Generate hdiff between two PPK files
@@ -201,27 +206,31 @@ Each workflow step contains:
- `hdiffFromIpa`: Generate hdiff from IPA files
### Version Module (`version`)
- `publish`: Publish new version
- `versions`: List all versions
- `update`: Update version information
- `updateVersionInfo`: Update version metadata
### App Module (`app`)
- `createApp`: Create new application
- `apps`: List all applications
- `selectApp`: Select application
- `deleteApp`: Delete application
### Package Module (`package`)
- `uploadIpa`: Upload IPA files
- `uploadApk`: Upload APK files
- `uploadApp`: Upload APP files
- `uploadIpa`: Upload IPA files (supports `--version` to override extracted version)
- `uploadApk`: Upload APK files (supports `--version` to override extracted version)
- `uploadApp`: Upload APP files (supports `--version` to override extracted version)
- `parseApp`: Parse APP file information
- `parseIpa`: Parse IPA file information
- `parseApk`: Parse APK file information
- `packages`: List packages
### User Module (`user`)
- `login`: Login
- `logout`: Logout
- `me`: Show user information
@@ -234,36 +243,45 @@ Each workflow step contains:
interface CLIProvider {
// Bundle
bundle(options: BundleOptions): Promise<CommandResult>;
// Publish
publish(options: PublishOptions): Promise<CommandResult>;
// Upload
upload(options: UploadOptions): Promise<CommandResult>;
// Application management
getSelectedApp(platform?: Platform): Promise<{ appId: string; platform: Platform }>;
getSelectedApp(
platform?: Platform,
): Promise<{ appId: string; platform: Platform }>;
listApps(platform?: Platform): Promise<CommandResult>;
createApp(name: string, platform: Platform): Promise<CommandResult>;
// Version management
listVersions(appId: string): Promise<CommandResult>;
getVersion(appId: string, versionId: string): Promise<CommandResult>;
updateVersion(appId: string, versionId: string, updates: Partial<Version>): Promise<CommandResult>;
updateVersion(
appId: string,
versionId: string,
updates: Partial<Version>,
): Promise<CommandResult>;
// Package management
listPackages(appId: string, platform?: Platform): Promise<CommandResult>;
getPackage(appId: string, packageId: string): Promise<CommandResult>;
// Utility functions
getPlatform(platform?: Platform): Promise<Platform>;
loadSession(): Promise<Session>;
saveToLocal(key: string, value: string): void;
question(prompt: string): Promise<string>;
// Workflows
registerWorkflow(workflow: CustomWorkflow): void;
executeWorkflow(workflowName: string, context: CommandContext): Promise<CommandResult>;
executeWorkflow(
workflowName: string,
context: CommandContext,
): Promise<CommandResult>;
}
```
@@ -276,8 +294,8 @@ const bundleResult = await moduleManager.executeCommand('custom-bundle', {
options: {
platform: 'android',
validate: true,
optimize: true
}
optimize: true,
},
});
// Generate diff file
@@ -286,8 +304,8 @@ const diffResult = await moduleManager.executeCommand('diff', {
options: {
origin: './build/v1.0.0.ppk',
next: './build/v1.1.0.ppk',
output: './build/diff.patch'
}
output: './build/diff.patch',
},
});
// Generate diff from APK files
@@ -296,8 +314,8 @@ const apkDiffResult = await moduleManager.executeCommand('diffFromApk', {
options: {
origin: './build/app-v1.0.0.apk',
next: './build/app-v1.1.0.apk',
output: './build/apk-diff.patch'
}
output: './build/apk-diff.patch',
},
});
```
@@ -349,29 +367,31 @@ Provider provides a concise programming interface suitable for integrating React
### 📋 Core API Methods
#### Core Business Functions
```typescript
// Bundle application
await provider.bundle({
platform: 'ios',
dev: false,
sourcemap: true
sourcemap: true,
});
// Publish version
await provider.publish({
name: 'v1.0.0',
description: 'Bug fixes',
rollout: 100
rollout: 100,
});
// Upload file
await provider.upload({
filePath: 'app.ipa',
platform: 'ios'
platform: 'ios',
});
```
#### Application Management
```typescript
// Create application
await provider.createApp('MyApp', 'ios');
@@ -384,6 +404,7 @@ const { appId, platform } = await provider.getSelectedApp('ios');
```
#### Version Management
```typescript
// List versions
await provider.listVersions('app123');
@@ -391,11 +412,12 @@ await provider.listVersions('app123');
// Update version
await provider.updateVersion('app123', 'version456', {
name: 'v1.1.0',
description: 'New features'
description: 'New features',
});
```
#### Utility Functions
```typescript
// Get platform
const platform = await provider.getPlatform('ios');
@@ -407,72 +429,75 @@ const session = await provider.loadSession();
### 🎯 Use Cases
#### 1. Automated Build Scripts
```typescript
import { moduleManager } from 'react-native-update-cli';
async function buildAndPublish() {
const provider = moduleManager.getProvider();
// 1. Bundle
const bundleResult = await provider.bundle({
platform: 'ios',
dev: false,
sourcemap: true
sourcemap: true,
});
if (!bundleResult.success) {
throw new Error(`Bundle failed: ${bundleResult.error}`);
}
// 2. Publish
const publishResult = await provider.publish({
name: 'v1.2.3',
description: 'Bug fixes and performance improvements',
rollout: 100
rollout: 100,
});
if (!publishResult.success) {
throw new Error(`Publish failed: ${publishResult.error}`);
}
console.log('Build and publish completed!');
}
```
#### 2. CI/CD Integration
```typescript
async function ciBuild() {
const provider = moduleManager.getProvider();
const result = await provider.bundle({
platform: process.env.PLATFORM as 'ios' | 'android',
dev: process.env.NODE_ENV !== 'production',
sourcemap: process.env.NODE_ENV === 'production'
sourcemap: process.env.NODE_ENV === 'production',
});
return result;
}
```
#### 3. Application Management Service
```typescript
class AppManagementService {
private provider = moduleManager.getProvider();
async setupNewApp(name: string, platform: Platform) {
// Create application
const createResult = await this.provider.createApp(name, platform);
if (createResult.success) {
// Get application information
const { appId } = await this.provider.getSelectedApp(platform);
// List versions
await this.provider.listVersions(appId);
return { appId, success: true };
}
return { success: false, error: createResult.error };
}
}
@@ -488,6 +513,7 @@ class AppManagementService {
### 🔧 Advanced Features
#### Custom Workflows
```typescript
// Register custom workflow
provider.registerWorkflow({
@@ -498,7 +524,7 @@ provider.registerWorkflow({
name: 'bundle',
execute: async () => {
return await provider.bundle({ platform: 'ios', dev: false });
}
},
},
{
name: 'publish',
@@ -507,9 +533,9 @@ provider.registerWorkflow({
throw new Error('Bundle failed, cannot publish');
}
return await provider.publish({ name: 'auto-release', rollout: 50 });
}
}
]
},
},
],
});
// Execute workflow
@@ -523,50 +549,49 @@ import { moduleManager } from 'react-native-update-cli';
class ReactNativeUpdateService {
private provider = moduleManager.getProvider();
async initialize() {
// Load session
await this.provider.loadSession();
}
async buildAndDeploy(platform: Platform, version: string) {
try {
// 1. Bundle
const bundleResult = await this.provider.bundle({
platform,
dev: false,
sourcemap: true
sourcemap: true,
});
if (!bundleResult.success) {
throw new Error(`Bundle failed: ${bundleResult.error}`);
}
// 2. Publish
const publishResult = await this.provider.publish({
name: version,
description: `Release ${version}`,
rollout: 100
rollout: 100,
});
if (!publishResult.success) {
throw new Error(`Publish failed: ${publishResult.error}`);
}
return { success: true, data: publishResult.data };
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error'
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error',
};
}
}
async getAppInfo(platform: Platform) {
const { appId } = await this.provider.getSelectedApp(platform);
const versions = await this.provider.listVersions(appId);
return { appId, versions };
}
}
@@ -575,4 +600,4 @@ class ReactNativeUpdateService {
const service = new ReactNativeUpdateService();
await service.initialize();
await service.buildAndDeploy('ios', 'v1.0.0');
```
```

View File

@@ -1,15 +1,15 @@
# React Native Update CLI
这是一个统一的React Native Update CLI同时支持传统命令和模块化架构以及自定义发布流程。
这是一个统一的 React Native Update CLI同时支持传统命令和模块化架构以及自定义发布流程。
## 🚀 特性
- **统一CLI**: 使用单个`pushy`命令提供所有功能
- **统一 CLI**: 使用单个`pushy`命令提供所有功能
- **向后兼容**: 所有现有命令都能正常工作
- **模块化架构**: 将CLI功能拆分为独立的模块
- **模块化架构**: 将 CLI 功能拆分为独立的模块
- **自定义工作流**: 支持创建自定义的发布流程
- **可扩展性**: 用户可以导入和注册自定义模块
- **类型安全**: 完整的TypeScript类型支持
- **类型安全**: 完整的 TypeScript 类型支持
## 📦 安装
@@ -47,14 +47,14 @@ const provider = moduleManager.getProvider();
const bundleResult = await provider.bundle({
platform: 'ios',
dev: false,
sourcemap: true
sourcemap: true,
});
// 发布版本
const publishResult = await provider.publish({
name: 'v1.2.3',
description: 'Bug fixes and improvements',
rollout: 100
rollout: 100,
});
```
@@ -63,12 +63,16 @@ const publishResult = await provider.publish({
### 1. 定义模块
```typescript
import type { CLIModule, CommandDefinition, CustomWorkflow } from 'react-native-update-cli';
import type {
CLIModule,
CommandDefinition,
CustomWorkflow,
} from 'react-native-update-cli';
export const myCustomModule: CLIModule = {
name: 'my-custom',
version: '1.0.0',
commands: [
{
name: 'custom-command',
@@ -77,15 +81,15 @@ export const myCustomModule: CLIModule = {
console.log('Executing custom command...');
return {
success: true,
data: { message: 'Custom command executed' }
data: { message: 'Custom command executed' },
};
},
options: {
param: { hasValue: true, description: 'Custom parameter' }
}
}
param: { hasValue: true, description: 'Custom parameter' },
},
},
],
workflows: [
{
name: 'my-workflow',
@@ -97,7 +101,7 @@ export const myCustomModule: CLIModule = {
execute: async (context, previousResult) => {
console.log('Executing step 1...');
return { step1Completed: true };
}
},
},
{
name: 'step2',
@@ -105,19 +109,19 @@ export const myCustomModule: CLIModule = {
execute: async (context, previousResult) => {
console.log('Executing step 2...');
return { ...previousResult, step2Completed: true };
}
}
]
}
},
},
],
},
],
init: (provider) => {
console.log('Custom module initialized');
},
cleanup: () => {
console.log('Custom module cleanup');
}
},
};
```
@@ -133,13 +137,13 @@ moduleManager.registerModule(myCustomModule);
// 执行自定义命令
const result = await moduleManager.executeCommand('custom-command', {
args: [],
options: { param: 'value' }
options: { param: 'value' },
});
// 执行自定义工作流
const workflowResult = await moduleManager.executeWorkflow('my-workflow', {
args: [],
options: {}
options: {},
});
```
@@ -188,43 +192,48 @@ const workflowResult = await moduleManager.executeWorkflow('my-workflow', {
## 📋 内置模块
### Bundle模块 (`bundle`)
- `bundle`: 打包JavaScript代码并可选发布
- `diff`: 生成两个PPK文件之间的差异
- `hdiff`: 生成两个PPK文件之间的hdiff
- `diffFromApk`: 从APK文件生成差异
- `hdiffFromApk`: 从APK文件生成hdiff
- `hdiffFromApp`: 从APP文件生成hdiff
- `diffFromIpa`: 从IPA文件生成差异
- `hdiffFromIpa`: 从IPA文件生成hdiff
### Bundle 模块 (`bundle`)
- `bundle`: 打包 JavaScript 代码并可选发布
- `diff`: 生成两个 PPK 文件之间的差异
- `hdiff`: 生成两个 PPK 文件之间的 hdiff
- `diffFromApk`: 从 APK 文件生成差异
- `hdiffFromApk`: 从 APK 文件生成 hdiff
- `hdiffFromApp`: 从 APP 文件生成 hdiff
- `diffFromIpa`: 从 IPA 文件生成差异
- `hdiffFromIpa`: 从 IPA 文件生成 hdiff
### Version 模块 (`version`)
### Version模块 (`version`)
- `publish`: 发布新版本
- `versions`: 列出所有版本
- `update`: 更新版本信息
- `updateVersionInfo`: 更新版本元数据
### App模块 (`app`)
### App 模块 (`app`)
- `createApp`: 创建新应用
- `apps`: 列出所有应用
- `selectApp`: 选择应用
- `deleteApp`: 删除应用
### Package模块 (`package`)
- `uploadIpa`: 上传IPA文件
- `uploadApk`: 上传APK文件
- `uploadApp`: 上传APP文件
- `parseApp`: 解析APP文件信息
- `parseIpa`: 解析IPA文件信息
- `parseApk`: 解析APK文件信息
### Package 模块 (`package`)
- `uploadIpa`: 上传 IPA 文件(支持 `--version` 参数覆盖提取的版本)
- `uploadApk`: 上传 APK 文件(支持 `--version` 参数覆盖提取的版本)
- `uploadApp`: 上传 APP 文件(支持 `--version` 参数覆盖提取的版本)
- `parseApp`: 解析 APP 文件信息
- `parseIpa`: 解析 IPA 文件信息
- `parseApk`: 解析 APK 文件信息
- `packages`: 列出包
### User模块 (`user`)
### User 模块 (`user`)
- `login`: 登录
- `logout`: 登出
- `me`: 显示用户信息
## 🛠️ CLI提供者API
## 🛠️ CLI 提供者 API
### 核心功能
@@ -232,36 +241,45 @@ const workflowResult = await moduleManager.executeWorkflow('my-workflow', {
interface CLIProvider {
// 打包
bundle(options: BundleOptions): Promise<CommandResult>;
// 发布
publish(options: PublishOptions): Promise<CommandResult>;
// 上传
upload(options: UploadOptions): Promise<CommandResult>;
// 应用管理
getSelectedApp(platform?: Platform): Promise<{ appId: string; platform: Platform }>;
getSelectedApp(
platform?: Platform,
): Promise<{ appId: string; platform: Platform }>;
listApps(platform?: Platform): Promise<CommandResult>;
createApp(name: string, platform: Platform): Promise<CommandResult>;
// 版本管理
listVersions(appId: string): Promise<CommandResult>;
getVersion(appId: string, versionId: string): Promise<CommandResult>;
updateVersion(appId: string, versionId: string, updates: Partial<Version>): Promise<CommandResult>;
updateVersion(
appId: string,
versionId: string,
updates: Partial<Version>,
): Promise<CommandResult>;
// 包管理
listPackages(appId: string, platform?: Platform): Promise<CommandResult>;
getPackage(appId: string, packageId: string): Promise<CommandResult>;
// 工具函数
getPlatform(platform?: Platform): Promise<Platform>;
loadSession(): Promise<Session>;
saveToLocal(key: string, value: string): void;
question(prompt: string): Promise<string>;
// 工作流
registerWorkflow(workflow: CustomWorkflow): void;
executeWorkflow(workflowName: string, context: CommandContext): Promise<CommandResult>;
executeWorkflow(
workflowName: string,
context: CommandContext,
): Promise<CommandResult>;
}
```
@@ -274,8 +292,8 @@ const bundleResult = await moduleManager.executeCommand('custom-bundle', {
options: {
platform: 'android',
validate: true,
optimize: true
}
optimize: true,
},
});
// 生成差异文件
@@ -284,8 +302,8 @@ const diffResult = await moduleManager.executeCommand('diff', {
options: {
origin: './build/v1.0.0.ppk',
next: './build/v1.1.0.ppk',
output: './build/diff.patch'
}
output: './build/diff.patch',
},
});
// 从APK文件生成差异
@@ -294,8 +312,8 @@ const apkDiffResult = await moduleManager.executeCommand('diffFromApk', {
options: {
origin: './build/app-v1.0.0.apk',
next: './build/app-v1.1.0.apk',
output: './build/apk-diff.patch'
}
output: './build/apk-diff.patch',
},
});
```
@@ -330,46 +348,48 @@ export NO_INTERACTIVE=true
## 🚨 注意事项
1. **向后兼容**: 新的模块化CLI保持与现有CLI的兼容性
2. **类型安全**: 所有API都有完整的TypeScript类型定义
1. **向后兼容**: 新的模块化 CLI 保持与现有 CLI 的兼容性
2. **类型安全**: 所有 API 都有完整的 TypeScript 类型定义
3. **错误处理**: 所有操作都返回标准化的结果格式
4. **资源清理**: 模块支持清理函数来释放资源
5. **模块分离**: 功能按逻辑分离到不同模块中,便于维护和扩展
## 🤝 贡献
欢迎提交IssuePull Request来改进这个项目
欢迎提交 IssuePull Request 来改进这个项目!
## 🚀 Provider API 使用指南
Provider提供了简洁的编程接口适合在应用程序中集成React Native Update CLI功能。
Provider 提供了简洁的编程接口,适合在应用程序中集成 React Native Update CLI 功能。
### 📋 核心API方法
### 📋 核心 API 方法
#### 核心业务功能
```typescript
// 打包应用
await provider.bundle({
platform: 'ios',
dev: false,
sourcemap: true
sourcemap: true,
});
// 发布版本
await provider.publish({
name: 'v1.0.0',
description: 'Bug fixes',
rollout: 100
rollout: 100,
});
// 上传文件
await provider.upload({
filePath: 'app.ipa',
platform: 'ios'
platform: 'ios',
});
```
#### 应用管理
```typescript
// 创建应用
await provider.createApp('MyApp', 'ios');
@@ -382,6 +402,7 @@ const { appId, platform } = await provider.getSelectedApp('ios');
```
#### 版本管理
```typescript
// 列出版本
await provider.listVersions('app123');
@@ -389,11 +410,12 @@ await provider.listVersions('app123');
// 更新版本
await provider.updateVersion('app123', 'version456', {
name: 'v1.1.0',
description: 'New features'
description: 'New features',
});
```
#### 工具函数
```typescript
// 获取平台
const platform = await provider.getPlatform('ios');
@@ -405,72 +427,75 @@ const session = await provider.loadSession();
### 🎯 使用场景
#### 1. 自动化构建脚本
```typescript
import { moduleManager } from 'react-native-update-cli';
async function buildAndPublish() {
const provider = moduleManager.getProvider();
// 1. 打包
const bundleResult = await provider.bundle({
platform: 'ios',
dev: false,
sourcemap: true
sourcemap: true,
});
if (!bundleResult.success) {
throw new Error(`打包失败: ${bundleResult.error}`);
}
// 2. 发布
const publishResult = await provider.publish({
name: 'v1.2.3',
description: 'Bug fixes and performance improvements',
rollout: 100
rollout: 100,
});
if (!publishResult.success) {
throw new Error(`发布失败: ${publishResult.error}`);
}
console.log('构建和发布完成!');
}
```
#### 2. CI/CD集成
#### 2. CI/CD 集成
```typescript
async function ciBuild() {
const provider = moduleManager.getProvider();
const result = await provider.bundle({
platform: process.env.PLATFORM as 'ios' | 'android',
dev: process.env.NODE_ENV !== 'production',
sourcemap: process.env.NODE_ENV === 'production'
sourcemap: process.env.NODE_ENV === 'production',
});
return result;
}
```
#### 3. 应用管理服务
```typescript
class AppManagementService {
private provider = moduleManager.getProvider();
async setupNewApp(name: string, platform: Platform) {
// 创建应用
const createResult = await this.provider.createApp(name, platform);
if (createResult.success) {
// 获取应用信息
const { appId } = await this.provider.getSelectedApp(platform);
// 列出版本
await this.provider.listVersions(appId);
return { appId, success: true };
}
return { success: false, error: createResult.error };
}
}
@@ -478,14 +503,15 @@ class AppManagementService {
### ⚠️ 注意事项
1. **错误处理**: 所有Provider方法都返回`CommandResult`,需要检查`success`字段
2. **类型安全**: Provider提供完整的TypeScript类型支持
1. **错误处理**: 所有 Provider 方法都返回`CommandResult`,需要检查`success`字段
2. **类型安全**: Provider 提供完整的 TypeScript 类型支持
3. **会话管理**: 使用前确保已登录,可通过`loadSession()`检查
4. **平台支持**: 支持`'ios' | 'android' | 'harmony'`三个平台
### 🔧 高级功能
#### 自定义工作流
```typescript
// 注册自定义工作流
provider.registerWorkflow({
@@ -496,7 +522,7 @@ provider.registerWorkflow({
name: 'bundle',
execute: async () => {
return await provider.bundle({ platform: 'ios', dev: false });
}
},
},
{
name: 'publish',
@@ -505,9 +531,9 @@ provider.registerWorkflow({
throw new Error('打包失败,无法发布');
}
return await provider.publish({ name: 'auto-release', rollout: 50 });
}
}
]
},
},
],
});
// 执行工作流
@@ -521,50 +547,49 @@ import { moduleManager } from 'react-native-update-cli';
class ReactNativeUpdateService {
private provider = moduleManager.getProvider();
async initialize() {
// 加载会话
await this.provider.loadSession();
}
async buildAndDeploy(platform: Platform, version: string) {
try {
// 1. 打包
const bundleResult = await this.provider.bundle({
platform,
dev: false,
sourcemap: true
sourcemap: true,
});
if (!bundleResult.success) {
throw new Error(`打包失败: ${bundleResult.error}`);
}
// 2. 发布
const publishResult = await this.provider.publish({
name: version,
description: `Release ${version}`,
rollout: 100
rollout: 100,
});
if (!publishResult.success) {
throw new Error(`发布失败: ${publishResult.error}`);
}
return { success: true, data: publishResult.data };
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error'
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error',
};
}
}
async getAppInfo(platform: Platform) {
const { appId } = await this.provider.getSelectedApp(platform);
const versions = await this.provider.listVersions(appId);
return { appId, versions };
}
}
@@ -573,4 +598,4 @@ class ReactNativeUpdateService {
const service = new ReactNativeUpdateService();
await service.initialize();
await service.buildAndDeploy('ios', 'v1.0.0');
```
```

View File

@@ -31,9 +31,27 @@
}
}
},
"uploadIpa": {},
"uploadApk": {},
"uploadApp": {},
"uploadIpa": {
"options": {
"version": {
"hasValue": true
}
}
},
"uploadApk": {
"options": {
"version": {
"hasValue": true
}
}
},
"uploadApp": {
"options": {
"version": {
"hasValue": true
}
}
},
"parseApp": {},
"parseIpa": {},
"parseApk": {},
@@ -44,6 +62,19 @@
}
}
},
"deletePackage": {
"options": {
"appId": {
"hasValue": true
},
"packageVersion": {
"hasValue": true
},
"packageId": {
"hasValue": true
}
}
},
"publish": {
"options": {
"platform": {
@@ -182,7 +213,7 @@
"rncli": {
"default": false
},
"disableHermes": {
"hermes": {
"default": false
},
"name": {
@@ -268,15 +299,6 @@
}
}
},
"hdiffFromPPK": {
"description": "Create hdiff patch from a Prepare package(.ppk)",
"options": {
"output": {
"default": "${tempDir}/output/hdiff-${time}.ppk-patch",
"hasValue": true
}
}
},
"hdiffFromApp": {
"description": "Create hdiff patch from a Harmony package(.app)",
"options": {
@@ -312,6 +334,10 @@
"hasValue": true
}
}
},
"install": {
"description": "Install optional dependencies to the CLI",
"options": {}
}
},
"globalOptions": {

View File

@@ -0,0 +1,53 @@
# Custom Version Parameter Usage
This document demonstrates how to use the `--version` parameter with upload commands to override the version extracted from APK/IPA/APP files.
## Commands Supporting Custom Version
- `uploadApk --version <version>`
- `uploadIpa --version <version>`
- `uploadApp --version <version>`
## Usage Examples
### Upload APK with Custom Version
```bash
# Upload APK and override version to "1.2.3-custom"
cresc uploadApk app-release.apk --version "1.2.3-custom"
```
### Upload IPA with Custom Version
```bash
# Upload IPA and override version to "2.0.0-beta"
cresc uploadIpa MyApp.ipa --version "2.0.0-beta"
```
### Upload APP with Custom Version
```bash
# Upload APP and override version to "3.1.0-harmony"
cresc uploadApp MyApp.app --version "3.1.0-harmony"
```
## Behavior
1. **Without `--version`**: The command uses the version extracted from the package file (APK/IPA/APP)
2. **With `--version`**: The command uses the provided custom version instead of the extracted version
3. **Console Output**: When using a custom version, the CLI will display "Using custom version: <version>" message
## Use Cases
- **Testing**: Upload test builds with specific version identifiers
- **Hotfixes**: Override version numbers for emergency releases
- **Version Alignment**: Ensure consistent versioning across different platforms
- **Manual Override**: When the extracted version is incorrect or inappropriate
## Example Output
```
$ cresc uploadApk app-release.apk --version "1.2.3-hotfix"
Using custom version: 1.2.3-hotfix
Successfully uploaded APK native package (id: 12345, version: 1.2.3-hotfix, buildTime: 2024-01-15T10:30:00Z)
```

View File

@@ -1,6 +1,6 @@
{
"name": "react-native-update-cli",
"version": "2.0.0",
"version": "2.4.0",
"description": "command line tool for react-native-update (remote updates for react native)",
"main": "index.js",
"bin": {

View File

@@ -10,18 +10,16 @@ import packageJson from '../package.json';
import type { Package, Session } from './types';
import {
credentialFile,
defaultEndpoint,
pricingPageUrl,
} from './utils/constants';
import { t } from './utils/i18n';
import { getBaseUrl } from 'utils/http-helper';
const tcpPing = util.promisify(tcpp.ping);
let session: Session | undefined;
let savedSession: Session | undefined;
const host =
process.env.PUSHY_REGISTRY || process.env.RNU_API || defaultEndpoint;
const userAgent = `react-native-update-cli/${packageJson.version}`;
@@ -64,7 +62,9 @@ export const closeSession = () => {
};
async function query(url: string, options: fetch.RequestInit) {
const resp = await fetch(url, options);
const baseUrl = await getBaseUrl;
const fullUrl = `${baseUrl}${url}`;
const resp = await fetch(fullUrl, options);
const text = await resp.text();
let json: any;
try {
@@ -83,7 +83,7 @@ async function query(url: string, options: fetch.RequestInit) {
function queryWithoutBody(method: string) {
return (api: string) =>
query(host + api, {
query(api, {
method,
headers: {
'User-Agent': userAgent,
@@ -94,7 +94,7 @@ function queryWithoutBody(method: string) {
function queryWithBody(method: string) {
return (api: string, body?: Record<string, any>) =>
query(host + api, {
query(api, {
method,
headers: {
'User-Agent': userAgent,
@@ -116,6 +116,7 @@ export async function uploadFile(fn: string, key?: string) {
});
let realUrl = url;
if (backupUrl) {
// @ts-ignore
if (global.USE_ACC_OSS) {
realUrl = backupUrl;
} else {

View File

@@ -16,7 +16,7 @@ import os from 'os';
const properties = require('properties');
import { addGitIgnore } from './utils/add-gitignore';
import { checkLockFiles } from './utils/check-lockfile';
import { tempDir } from './utils/constants';
import { isPPKBundleFileName, scriptName, tempDir } from './utils/constants';
import { depVersions } from './utils/dep-versions';
import { t } from './utils/i18n';
import { versionCommands } from './versions';
@@ -42,7 +42,7 @@ async function runReactNativeBundleCommand({
platform,
sourcemapOutput,
config,
disableHermes,
forceHermes,
cli,
}: {
bundleName: string;
@@ -52,7 +52,7 @@ async function runReactNativeBundleCommand({
platform: string;
sourcemapOutput: string;
config?: string;
disableHermes?: boolean;
forceHermes?: boolean;
cli: {
taro?: boolean;
expo?: boolean;
@@ -75,27 +75,40 @@ async function runReactNativeBundleCommand({
const envArgs = process.env.PUSHY_ENV_ARGS;
if (envArgs) {
Array.prototype.push.apply(
reactNativeBundleArgs,
envArgs.trim().split(/\s+/),
);
reactNativeBundleArgs.push(...envArgs.trim().split(/\s+/));
}
fs.emptyDirSync(outputFolder);
let cliPath: string | undefined;
let cliPath = '';
let usingExpo = false;
const getExpoCli = () => {
try {
const searchPaths = [process.cwd()];
// 尝试添加 expo 包的路径作为额外的搜索路径
try {
const expoPath = require.resolve('expo/package.json', {
paths: [process.cwd()],
});
// 获取 expo 包的目录路径
const expoDir = expoPath.replace(/\/package\.json$/, '');
searchPaths.push(expoDir);
} catch {
// expo 包不存在,忽略
}
// 尝试从搜索路径中解析 @expo/cli
cliPath = require.resolve('@expo/cli', {
paths: [process.cwd()],
paths: searchPaths,
});
const expoCliVersion = JSON.parse(
fs
.readFileSync(
require.resolve('@expo/cli/package.json', {
paths: [process.cwd()],
paths: searchPaths,
}),
)
.toString(),
@@ -104,7 +117,7 @@ async function runReactNativeBundleCommand({
if (satisfies(expoCliVersion, '>= 0.10.17')) {
usingExpo = true;
} else {
cliPath = undefined;
cliPath = '';
}
} catch (e) {}
};
@@ -167,48 +180,38 @@ async function runReactNativeBundleCommand({
}
if (platform === 'harmony') {
Array.prototype.push.apply(reactNativeBundleArgs, [
cliPath,
bundleCommand,
'--dev',
dev,
'--entry-file',
entryFile,
]);
if (sourcemapOutput) {
reactNativeBundleArgs.push('--sourcemap-output', sourcemapOutput);
bundleName = 'bundle.harmony.js';
if (forceHermes === undefined) {
// enable hermes by default for harmony
forceHermes = true;
}
}
if (config) {
reactNativeBundleArgs.push('--config', config);
}
reactNativeBundleArgs.push(
cliPath,
bundleCommand,
'--assets-dest',
outputFolder,
'--bundle-output',
path.join(outputFolder, bundleName),
);
if (platform !== 'harmony') {
reactNativeBundleArgs.push('--platform', platform, '--reset-cache');
}
if (cli.taro) {
reactNativeBundleArgs.push('--type', 'rn');
} else {
Array.prototype.push.apply(reactNativeBundleArgs, [
cliPath,
bundleCommand,
'--assets-dest',
outputFolder,
'--bundle-output',
path.join(outputFolder, bundleName),
'--platform',
platform,
'--reset-cache',
]);
reactNativeBundleArgs.push('--dev', dev, '--entry-file', entryFile);
}
if (cli.taro) {
reactNativeBundleArgs.push(...['--type', 'rn']);
} else {
reactNativeBundleArgs.push(...['--dev', dev, '--entry-file', entryFile]);
}
if (sourcemapOutput) {
reactNativeBundleArgs.push('--sourcemap-output', sourcemapOutput);
}
if (sourcemapOutput) {
reactNativeBundleArgs.push('--sourcemap-output', sourcemapOutput);
}
if (config) {
reactNativeBundleArgs.push('--config', config);
}
if (config) {
reactNativeBundleArgs.push('--config', config);
}
const reactNativeBundleProcess = spawn('node', reactNativeBundleArgs);
@@ -231,9 +234,9 @@ async function runReactNativeBundleCommand({
} else {
let hermesEnabled: boolean | undefined = false;
if (disableHermes) {
hermesEnabled = false;
console.log(t('hermesDisabled'));
if (forceHermes) {
hermesEnabled = true;
console.log(t('forceHermes'));
} else if (platform === 'android') {
const gradlePropeties = await new Promise<{
hermesEnabled?: boolean;
@@ -260,8 +263,6 @@ async function runReactNativeBundleCommand({
fs.existsSync('ios/Pods/hermes-engine')
) {
hermesEnabled = true;
} else if (platform === 'harmony') {
await copyHarmonyBundle(outputFolder);
}
if (hermesEnabled) {
await compileHermesByteCode(
@@ -271,45 +272,25 @@ async function runReactNativeBundleCommand({
!isSentry,
);
}
if (platform === 'harmony') {
const harmonyRawAssetsPath =
'harmony/entry/src/main/resources/rawfile/assets';
// copy all files in outputFolder to harmonyRawPath
// assets should be in rawfile/assets
fs.ensureDirSync(harmonyRawAssetsPath);
fs.copySync(outputFolder, harmonyRawAssetsPath, { overwrite: true });
fs.moveSync(
`${harmonyRawAssetsPath}/bundle.harmony.js`,
`${harmonyRawAssetsPath}/../bundle.harmony.js`,
{ overwrite: true },
);
}
resolve(null);
}
});
});
}
async function copyHarmonyBundle(outputFolder: string) {
const harmonyRawPath = 'harmony/entry/src/main/resources/rawfile';
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);
const files = await fs.readdir(harmonyRawPath);
for (const file of files) {
if (file !== 'update.json' && file !== 'meta.json') {
const sourcePath = path.join(harmonyRawPath, file);
const destPath = path.join(outputFolder, file);
const stat = await fs.stat(sourcePath);
if (stat.isFile()) {
await fs.copy(sourcePath, destPath);
} else if (stat.isDirectory()) {
await fs.copy(sourcePath, destPath);
}
}
}
} catch (error: any) {
console.error(t('copyHarmonyBundleError', { error }));
throw new Error(t('copyFileFailed', { error: error.message }));
}
}
function getHermesOSBin() {
if (os.platform() === 'win32') return 'win64-bin';
if (os.platform() === 'darwin') return 'osx-bin';
@@ -498,7 +479,12 @@ async function uploadSourcemapForSentry(
}
}
const ignorePackingFileNames = ['.', '..', 'index.bundlejs.map'];
const ignorePackingFileNames = [
'.',
'..',
'index.bundlejs.map',
'bundle.harmony.js.map',
];
const ignorePackingExtensions = ['DS_Store', 'txt.map'];
async function pack(dir: string, output: string) {
console.log(t('packing'));
@@ -580,10 +566,7 @@ async function diffFromPPK(origin: string, next: string, output: string) {
// isFile
originMap[entry.crc32] = entry.fileName;
if (
entry.fileName === 'index.bundlejs' ||
entry.fileName === 'bundle.harmony.js'
) {
if (isPPKBundleFileName(entry.fileName)) {
// This is source.
return readEntry(entry, zipFile).then((v) => (originSource = v));
}
@@ -591,12 +574,11 @@ async function diffFromPPK(origin: string, next: string, output: string) {
});
if (!originSource) {
throw new Error(
'Bundle file not found! Please use default bundle file name and path.',
);
throw new Error(t('bundleFileNotFound'));
}
const copies = {};
const copiesv2 = {};
const zipfile = new YazlZipFile();
@@ -633,23 +615,13 @@ async function diffFromPPK(origin: string, next: string, output: string) {
if (!originEntries[entry.fileName]) {
addEntry(entry.fileName);
}
} else if (entry.fileName === 'index.bundlejs') {
} else if (isPPKBundleFileName(entry.fileName)) {
//console.log('Found bundle');
return readEntry(entry, nextZipfile).then((newSource) => {
//console.log('Begin diff');
zipfile.addBuffer(
diff(originSource, newSource),
'index.bundlejs.patch',
);
//console.log('End diff');
});
} else if (entry.fileName === 'bundle.harmony.js') {
//console.log('Found bundle');
return readEntry(entry, nextZipfile).then((newSource) => {
//console.log('Begin diff');
zipfile.addBuffer(
diff(originSource, newSource),
'bundle.harmony.js.patch',
`${entry.fileName}.patch`,
);
//console.log('End diff');
});
@@ -668,6 +640,7 @@ async function diffFromPPK(origin: string, next: string, output: string) {
addEntry(base);
}
copies[entry.fileName] = originMap[entry.crc32];
copiesv2[entry.crc32] = entry.fileName;
return;
}
@@ -700,7 +673,7 @@ async function diffFromPPK(origin: string, next: string, output: string) {
//console.log({copies, deletes});
zipfile.addBuffer(
Buffer.from(JSON.stringify({ copies, deletes })),
Buffer.from(JSON.stringify({ copies, copiesv2, deletes })),
'__diff.json',
);
zipfile.end();
@@ -741,12 +714,11 @@ async function diffFromPackage(
});
if (!originSource) {
throw new Error(
'Bundle file not found! Please use default bundle file name and path.',
);
throw new Error(t('bundleFileNotFound'));
}
const copies = {};
const copiesv2 = {};
const zipfile = new YazlZipFile();
@@ -763,23 +735,13 @@ async function diffFromPackage(
if (/\/$/.test(entry.fileName)) {
// Directory
zipfile.addEmptyDirectory(entry.fileName);
} else if (entry.fileName === 'index.bundlejs') {
} else if (isPPKBundleFileName(entry.fileName)) {
//console.log('Found bundle');
return readEntry(entry, nextZipfile).then((newSource) => {
//console.log('Begin diff');
zipfile.addBuffer(
diff(originSource, newSource),
'index.bundlejs.patch',
);
//console.log('End diff');
});
} else if (entry.fileName === 'bundle.harmony.js') {
//console.log('Found bundle');
return readEntry(entry, nextZipfile).then((newSource) => {
//console.log('Begin diff');
zipfile.addBuffer(
diff(originSource, newSource),
'bundle.harmony.js.patch',
`${entry.fileName}.patch`,
);
//console.log('End diff');
});
@@ -792,6 +754,7 @@ async function diffFromPackage(
// If moved from other place
if (originMap[entry.crc32]) {
copies[entry.fileName] = originMap[entry.crc32];
copiesv2[entry.crc32] = entry.fileName;
return;
}
@@ -810,7 +773,10 @@ async function diffFromPackage(
}
});
zipfile.addBuffer(Buffer.from(JSON.stringify({ copies })), '__diff.json');
zipfile.addBuffer(
Buffer.from(JSON.stringify({ copies, copiesv2 })),
'__diff.json',
);
zipfile.end();
await writePromise;
}
@@ -892,24 +858,21 @@ function diffArgsCheck(args: string[], options: any, diffFn: string) {
if (diffFn.startsWith('hdiff')) {
if (!hdiff) {
console.error(
`This function needs "node-hdiffpatch".
Please run "npm i node-hdiffpatch" to install`,
);
console.error(t('nodeHdiffpatchRequired', { scriptName }));
process.exit(1);
}
diff = hdiff;
} else {
if (!bsdiff) {
console.error(
`This function needs "node-bsdiff".
Please run "npm i node-bsdiff" to install`,
);
console.error(t('nodeBsdiffRequired', { scriptName }));
process.exit(1);
}
diff = bsdiff;
}
const { output } = options;
const { output } = translateOptions({
...options,
tempDir,
});
return {
origin,
@@ -932,7 +895,7 @@ export const bundleCommands = {
taro,
expo,
rncli,
disableHermes,
hermes,
name,
description,
metaInfo,
@@ -973,7 +936,7 @@ export const bundleCommands = {
outputFolder: intermediaDir,
platform,
sourcemapOutput: sourcemap || sourcemapPlugin ? sourcemapOutput : '',
disableHermes: !!disableHermes,
forceHermes: hermes as unknown as boolean,
cli: {
taro: !!taro,
expo: !!expo,
@@ -1040,14 +1003,14 @@ export const bundleCommands = {
const { origin, next, realOutput } = diffArgsCheck(args, options, 'diff');
await diffFromPPK(origin, next, realOutput);
console.log(`${realOutput} generated.`);
console.log(t('diffPackageGenerated', { output: realOutput }));
},
async hdiff({ args, options }) {
const { origin, next, realOutput } = diffArgsCheck(args, options, 'hdiff');
await diffFromPPK(origin, next, realOutput);
console.log(`${realOutput} generated.`);
console.log(t('diffPackageGenerated', { output: realOutput }));
},
async diffFromApk({ args, options }) {
@@ -1063,7 +1026,7 @@ export const bundleCommands = {
realOutput,
'assets/index.android.bundle',
);
console.log(`${realOutput} generated.`);
console.log(t('diffPackageGenerated', { output: realOutput }));
},
async hdiffFromApk({ args, options }) {
@@ -1079,7 +1042,7 @@ export const bundleCommands = {
realOutput,
'assets/index.android.bundle',
);
console.log(`${realOutput} generated.`);
console.log(t('diffPackageGenerated', { output: realOutput }));
},
async diffFromApp({ args, options }) {
@@ -1094,7 +1057,7 @@ export const bundleCommands = {
realOutput,
'resources/rawfile/bundle.harmony.js',
);
console.log(`${realOutput} generated.`);
console.log(t('diffPackageGenerated', { output: realOutput }));
},
async hdiffFromApp({ args, options }) {
@@ -1109,7 +1072,7 @@ export const bundleCommands = {
realOutput,
'resources/rawfile/bundle.harmony.js',
);
console.log(`${realOutput} generated.`);
console.log(t('diffPackageGenerated', { output: realOutput }));
},
async diffFromIpa({ args, options }) {
@@ -1124,7 +1087,7 @@ export const bundleCommands = {
return m?.[1];
});
console.log(`${realOutput} generated.`);
console.log(t('diffPackageGenerated', { output: realOutput }));
},
async hdiffFromIpa({ args, options }) {
@@ -1139,6 +1102,6 @@ export const bundleCommands = {
return m?.[1];
});
console.log(`${realOutput} generated.`);
console.log(t('diffPackageGenerated', { output: realOutput }));
},
};

View File

@@ -3,6 +3,7 @@
import { loadSession } from './api';
import { appCommands } from './app';
import { bundleCommands } from './bundle';
import { installCommands } from './install';
import { moduleManager } from './module-manager';
import { builtinModules } from './modules';
import { packageCommands } from './package';
@@ -26,15 +27,16 @@ function printUsage() {
console.log('React Native Update CLI');
console.log('');
console.log('Traditional commands:');
const legacyCommands = {
...userCommands,
...bundleCommands,
...appCommands,
...packageCommands,
...versionCommands,
...installCommands,
};
for (const [name, handler] of Object.entries(legacyCommands)) {
console.log(` ${name}: Legacy command`);
}
@@ -62,7 +64,7 @@ function printUsage() {
console.log(' list: List all available commands and workflows');
console.log(' workflow <name>: Execute a specific workflow');
console.log(' help: Show this help message');
console.log('');
console.log(
'Visit `https://github.com/reactnativecn/react-native-update` for document.',
@@ -76,6 +78,7 @@ const legacyCommands = {
...appCommands,
...packageCommands,
...versionCommands,
...installCommands,
help: printUsage,
};
@@ -118,7 +121,7 @@ async function run() {
process.exit(1);
}
console.log('Workflow completed successfully:', result.data);
}
}
// Try legacy commands first for backward compatibility
else if (legacyCommands[argv.command]) {
await legacyCommands[argv.command](argv);

19
src/install.ts Normal file
View File

@@ -0,0 +1,19 @@
import { spawnSync } from 'child_process';
import path from 'path';
import type { CommandContext } from './types';
export const installCommands = {
install: async ({ args }: CommandContext) => {
if (args.length === 0) {
return;
}
const cliDir = path.resolve(__dirname, '..');
spawnSync('npm', ['install', ...args], {
cwd: cliDir,
stdio: 'inherit',
shell: true,
});
},
};

View File

@@ -49,7 +49,7 @@ export default {
fileGenerated: '{{- file}} generated.',
fileSizeExceeded:
'This file size is {{fileSize}} , exceeding the current quota {{maxSize}} . You may consider upgrading to a higher plan to increase this quota. Details can be found at: {{- pricingPageUrl}}',
hermesDisabled: 'Hermes disabled',
forceHermes: 'Forcing Hermes enabled for this build',
hermesEnabledCompiling: 'Hermes enabled, now compiling to hermes bytecode:\n',
ipaUploadSuccess:
'Successfully uploaded IPA native package (id: {{id}}, version: {{version}}, buildTime: {{buildTime}})',
@@ -130,4 +130,18 @@ This can reduce the risk of inconsistent dependencies and supply chain attacks.
updateNativePackageQuestion: 'Bind to native package now?(Y/N)',
unnamed: '(Unnamed)',
dryRun: 'Below is the dry-run result, no actual operation will be performed:',
usingCustomVersion: 'Using custom version: {{version}}',
confirmDeletePackage:
'Confirm delete native package {{packageId}}? This operation cannot be undone (Y/N):',
deletePackageSuccess: 'Native package {{packageId}} deleted successfully',
deletePackageError:
'Failed to delete native package {{packageId}}: {{error}}',
usageDeletePackage: 'Usage: cresc deletePackage [packageId] --appId [appId]',
bundleFileNotFound:
'Bundle file not found! Please use default bundle file name and path.',
diffPackageGenerated: '{{- output}} generated.',
nodeBsdiffRequired:
'This function needs "node-bsdiff". Please run "{{scriptName}} install node-bsdiff" to install',
nodeHdiffpatchRequired:
'This function needs "node-hdiffpatch". Please run "{{scriptName}} install node-hdiffpatch" to install',
};

View File

@@ -47,7 +47,7 @@ export default {
fileGenerated: '已生成 {{- file}}',
fileSizeExceeded:
'此文件大小 {{fileSize}} , 超出当前额度 {{maxSize}} 。您可以考虑升级付费业务以提升此额度。详情请访问: {{- pricingPageUrl}}',
hermesDisabled: 'Hermes 已禁用',
forceHermes: '强制启用 Hermes 编译',
hermesEnabledCompiling: 'Hermes 已启用,正在编译为 hermes 字节码:\n',
ipaUploadSuccess:
'已成功上传ipa原生包id: {{id}}, version: {{version}}, buildTime: {{buildTime}}',
@@ -123,4 +123,16 @@ export default {
updateNativePackageQuestion: '是否现在将此热更应用到原生包上?(Y/N)',
unnamed: '(未命名)',
dryRun: '以下是 dry-run 模拟运行结果,不会实际执行任何操作:',
usingCustomVersion: '使用自定义版本:{{version}}',
confirmDeletePackage: '确认删除原生包 {{packageId}}? 此操作不可撤销 (Y/N):',
deletePackageSuccess: '原生包 {{packageId}} 删除成功',
deletePackageError: '删除原生包 {{packageId}} 失败: {{error}}',
usageDeletePackage:
'使用方法: pushy deletePackage [packageId] --appId [appId]',
bundleFileNotFound: '未找到 bundle 文件!请使用默认的 bundle 文件名和路径。',
diffPackageGenerated: '{{- output}} 已生成。',
nodeBsdiffRequired:
'此功能需要 "node-bsdiff"。请运行 "{{scriptName}} install node-bsdiff" 来安装',
nodeHdiffpatchRequired:
'此功能需要 "node-hdiffpatch"。请运行 "{{scriptName}} install node-hdiffpatch" 来安装',
};

View File

@@ -39,9 +39,9 @@ export class ModuleManager {
module.init(this.provider);
}
console.log(
`Module '${module.name}' (v${module.version}) registered successfully`,
);
// console.log(
// `Module '${module.name}' (v${module.version}) registered successfully`,
// );
}
unregisterModule(moduleName: string): void {

View File

@@ -53,7 +53,7 @@ export const bundleModule: CLIModule = {
taro = false,
expo = false,
rncli = false,
disableHermes = false,
hermes = false,
output,
} = context.options;
@@ -73,7 +73,7 @@ export const bundleModule: CLIModule = {
taro,
expo,
rncli,
disableHermes,
hermes,
intermediaDir: '${tempDir}/intermedia/${platform}',
output: '${tempDir}/output/${platform}.${time}.ppk',
};
@@ -170,10 +170,10 @@ export const bundleModule: CLIModule = {
default: false,
description: 'Use React Native CLI',
},
disableHermes: {
hermes: {
hasValue: false,
default: false,
description: 'Disable Hermes',
description: 'Force enable Hermes',
},
name: {
hasValue: true,

View File

@@ -1,4 +1,4 @@
import { get, getAllPackages, post, uploadFile } from './api';
import { get, getAllPackages, post, uploadFile, doDelete } from './api';
import { question, saveToLocal } from './utils';
import { t } from './utils/i18n';
@@ -23,9 +23,9 @@ export async function listPackage(appId: string) {
let versionInfo = '';
if (version) {
const versionObj = version as any;
versionInfo = t('boundTo', {
name: versionObj.name || version,
id: versionObj.id || version
versionInfo = t('boundTo', {
name: versionObj.name || version,
id: versionObj.id || version,
});
}
let output = pkg.name;
@@ -57,16 +57,19 @@ export async function choosePackage(appId: string) {
}
export const packageCommands = {
uploadIpa: async ({ args }: { args: string[] }) => {
uploadIpa: async ({
args,
options,
}: {
args: string[];
options: Record<string, any>;
}) => {
const fn = args[0];
if (!fn || !fn.endsWith('.ipa')) {
throw new Error(t('usageUploadIpa'));
}
const ipaInfo = await getIpaInfo(fn);
const {
versionName,
buildTime,
} = ipaInfo;
const { versionName: extractedVersionName, buildTime } = ipaInfo;
const appIdInPkg = (ipaInfo as any).appId;
const appKeyInPkg = (ipaInfo as any).appKey;
const { appId, appKey } = await getSelectedApp('ios');
@@ -79,6 +82,12 @@ export const packageCommands = {
throw new Error(t('appKeyMismatchIpa', { appKeyInPkg, appKey }));
}
// Use custom version if provided, otherwise use extracted version
const versionName = options.version || extractedVersionName;
if (options.version) {
console.log(t('usingCustomVersion', { version: versionName }));
}
const { hash } = await uploadFile(fn);
const { id } = await post(`/app/${appId}/package/create`, {
@@ -89,20 +98,21 @@ export const packageCommands = {
commit: await getCommitInfo(),
});
saveToLocal(fn, `${appId}/package/${id}.ipa`);
console.log(
t('ipaUploadSuccess', { id, version: versionName, buildTime }),
);
console.log(t('ipaUploadSuccess', { id, version: versionName, buildTime }));
},
uploadApk: async ({ args }: { args: string[] }) => {
uploadApk: async ({
args,
options,
}: {
args: string[];
options: Record<string, any>;
}) => {
const fn = args[0];
if (!fn || !fn.endsWith('.apk')) {
throw new Error(t('usageUploadApk'));
}
const apkInfo = await getApkInfo(fn);
const {
versionName,
buildTime,
} = apkInfo;
const { versionName: extractedVersionName, buildTime } = apkInfo;
const appIdInPkg = (apkInfo as any).appId;
const appKeyInPkg = (apkInfo as any).appKey;
const { appId, appKey } = await getSelectedApp('android');
@@ -115,6 +125,12 @@ export const packageCommands = {
throw new Error(t('appKeyMismatchApk', { appKeyInPkg, appKey }));
}
// Use custom version if provided, otherwise use extracted version
const versionName = options.version || extractedVersionName;
if (options.version) {
console.log(t('usingCustomVersion', { version: versionName }));
}
const { hash } = await uploadFile(fn);
const { id } = await post(`/app/${appId}/package/create`, {
@@ -125,20 +141,21 @@ export const packageCommands = {
commit: await getCommitInfo(),
});
saveToLocal(fn, `${appId}/package/${id}.apk`);
console.log(
t('apkUploadSuccess', { id, version: versionName, buildTime }),
);
console.log(t('apkUploadSuccess', { id, version: versionName, buildTime }));
},
uploadApp: async ({ args }: { args: string[] }) => {
uploadApp: async ({
args,
options,
}: {
args: string[];
options: Record<string, any>;
}) => {
const fn = args[0];
if (!fn || !fn.endsWith('.app')) {
throw new Error(t('usageUploadApp'));
}
const appInfo = await getAppInfo(fn);
const {
versionName,
buildTime,
} = appInfo;
const { versionName: extractedVersionName, buildTime } = appInfo;
const appIdInPkg = (appInfo as any).appId;
const appKeyInPkg = (appInfo as any).appKey;
const { appId, appKey } = await getSelectedApp('harmony');
@@ -151,6 +168,12 @@ export const packageCommands = {
throw new Error(t('appKeyMismatchApp', { appKeyInPkg, appKey }));
}
// Use custom version if provided, otherwise use extracted version
const versionName = options.version || extractedVersionName;
if (options.version) {
console.log(t('usingCustomVersion', { version: versionName }));
}
const { hash } = await uploadFile(fn);
const { id } = await post(`/app/${appId}/package/create`, {
@@ -161,9 +184,7 @@ export const packageCommands = {
commit: await getCommitInfo(),
});
saveToLocal(fn, `${appId}/package/${id}.app`);
console.log(
t('appUploadSuccess', { id, version: versionName, buildTime }),
);
console.log(t('appUploadSuccess', { id, version: versionName, buildTime }));
},
parseApp: async ({ args }: { args: string[] }) => {
const fn = args[0];
@@ -191,4 +212,53 @@ export const packageCommands = {
const { appId } = await getSelectedApp(platform);
await listPackage(appId);
},
deletePackage: async ({
args,
options,
}: {
args: string[];
options: { appId?: string, packageId?: string, packageVersion?: string };
}) => {
let { appId, packageId, packageVersion } = options;
if (!appId) {
const platform = await getPlatform();
appId = (await getSelectedApp(platform)).appId as string;
}
// If no packageId provided as argument, let user choose from list
if (!packageId) {
const allPkgs = await getAllPackages(appId);
if (!allPkgs) {
throw new Error(t('noPackagesFound', { appId }));
}
const selectedPackage = allPkgs.find((pkg) => pkg.name === packageVersion);
if (!selectedPackage) {
throw new Error(t('packageNotFound', { packageVersion }));
}
packageId = selectedPackage.id;
}
// Confirm deletion
// const confirmDelete = await question(
// t('confirmDeletePackage', { packageId }),
// );
// if (
// confirmDelete.toLowerCase() !== 'y' &&
// confirmDelete.toLowerCase() !== 'yes'
// ) {
// console.log(t('cancelled'));
// return;
// }
try {
await doDelete(`/app/${appId}/package/${packageId}`);
console.log(t('deletePackageSuccess', { packageId }));
} catch (error: any) {
throw new Error(
t('deletePackageError', { packageId, error: error.message }),
);
}
},
};

View File

@@ -42,7 +42,7 @@ export class CLIProviderImpl implements CLIProvider {
taro: options.taro || false,
expo: options.expo || false,
rncli: options.rncli || false,
disableHermes: options.disableHermes || false,
hermes: options.hermes || false,
},
};
@@ -110,7 +110,7 @@ export class CLIProviderImpl implements CLIProvider {
const context: CommandContext = {
args: [filePath],
options: { platform, appId },
options: { platform, appId, version: options.version },
};
const { packageCommands } = await import('./package');

View File

@@ -65,7 +65,7 @@ export interface BundleOptions {
taro?: boolean;
expo?: boolean;
rncli?: boolean;
disableHermes?: boolean;
hermes?: boolean;
}
export interface PublishOptions {
@@ -85,6 +85,7 @@ export interface UploadOptions {
platform?: Platform;
filePath: string;
appId?: string;
version?: string;
}
export interface WorkflowStep {

View File

@@ -1,8 +1,12 @@
import path from 'path';
const scriptName = path.basename(process.argv[1]) as 'cresc' | 'pushy';
export const scriptName = path.basename(process.argv[1]) as 'cresc' | 'pushy';
export const IS_CRESC = scriptName === 'cresc';
export const ppkBundleFileNames = ['index.bundlejs', 'bundle.harmony.js'];
export const isPPKBundleFileName = (fileName: string) =>
ppkBundleFileNames.includes(fileName);
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';
@@ -10,6 +14,6 @@ export const pricingPageUrl = IS_CRESC
? 'https://cresc.dev/pricing'
: 'https://pushy.reactnative.cn/pricing.html';
export const defaultEndpoint = IS_CRESC
? 'https://api.cresc.dev'
: 'https://update.reactnative.cn/api';
export const defaultEndpoints = IS_CRESC
? ['https://api.cresc.dev', 'https://api.cresc.app']
: ['https://update.reactnative.cn/api', 'https://update.react-native.cn/api'];

View File

@@ -1,4 +1,9 @@
const currentPackage = require(`${process.cwd()}/package.json`);
let currentPackage = null;
try {
currentPackage = require(`${process.cwd()}/package.json`);
} catch (e) {
// console.warn('No package.json file were found');
}
const _depVersions: Record<string, string> = {};
@@ -24,12 +29,9 @@ if (currentPackage) {
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>,
);
.reduce((obj, key) => {
obj[key] = _depVersions[key]; // Rebuild the object with sorted keys
return obj;
}, {} as Record<string, string>);
// console.log({ depVersions });

83
src/utils/http-helper.ts Normal file
View File

@@ -0,0 +1,83 @@
import { defaultEndpoints } from './constants';
// const baseUrl = `http://localhost:9000`;
// let baseUrl = SERVER.main[0];
// const baseUrl = `https://p.reactnative.cn/api`;
export function promiseAny<T>(promises: Promise<T>[]) {
return new Promise<T>((resolve, reject) => {
let count = 0;
for (const promise of promises) {
Promise.resolve(promise)
.then(resolve)
.catch(() => {
count++;
if (count === promises.length) {
reject(new Error('All promises were rejected'));
}
});
}
});
}
export const ping = async (url: string) => {
let pingFinished = false;
return Promise.race([
fetch(url, {
method: 'HEAD',
})
.then(({ status, statusText }) => {
pingFinished = true;
if (status === 200) {
// console.log('ping success', url);
return url;
}
// console.log('ping failed', url, status, statusText);
throw new Error('ping failed');
})
.catch((e) => {
pingFinished = true;
// console.log('ping error', url, e);
throw new Error('ping error');
}),
new Promise((_, reject) =>
setTimeout(() => {
reject(new Error('ping timeout'));
if (!pingFinished) {
// console.log('ping timeout', url);
}
}, 2000),
),
]) as Promise<string | null>;
};
export const testUrls = async (urls?: string[]) => {
if (!urls?.length) {
return null;
}
const ret = await promiseAny(urls.map(ping));
if (ret) {
return ret;
}
// console.log('all ping failed, use first url:', urls[0]);
return urls[0];
};
export const getBaseUrl = (async () => {
const testEndpoint = process.env.PUSHY_REGISTRY || process.env.RNU_API;
if (testEndpoint) {
return testEndpoint;
}
return testUrls(defaultEndpoints.map((url) => `${url}/status`)).then(
(ret) => {
let baseUrl = defaultEndpoints[0];
if (ret) {
// remove /status
baseUrl = ret.replace('/status', '');
}
// console.log('baseUrl', baseUrl);
return baseUrl;
},
);
})();

View File

@@ -122,17 +122,6 @@ export const bindVersionToPackages = async ({
console.log(chalk.yellow(t('dryRun')));
}
if (rollout !== undefined) {
const rolloutConfig: Record<string, number> = {};
for (const pkg of pkgs) {
rolloutConfig[pkg.name] = rollout;
}
if (!dryRun) {
await put(`/app/${appId}/version/${versionId}`, {
config: {
rollout: rolloutConfig,
},
});
}
console.log(
`${t('rolloutConfigSet', {
versions: pkgs.map((pkg: Package) => pkg.name).join(', '),
@@ -142,8 +131,10 @@ export const bindVersionToPackages = async ({
}
for (const pkg of pkgs) {
if (!dryRun) {
await put(`/app/${appId}/package/${pkg.id}`, {
await post(`/app/${appId}/binding`, {
versionId,
rollout,
packageId: pkg.id,
});
}
console.log(

View File

@@ -4,7 +4,8 @@
"target": "ESNext" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
"lib": [
"ESNext"
"ESNext",
"DOM"
] /* Specify library files to be included in the compilation. */,
"allowJs": true /* Allow javascript files to be compiled. */,
// "checkJs": true /* Report errors in .js files. */,