uniapp-android-cli 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/uni-pack.js CHANGED
File without changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "uniapp-android-cli",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
5
  "description": "离线打包 uni-app Android 应用:正式包、自定义基座、wgt、设备调试",
6
6
  "keywords": [
package/src/cli.js CHANGED
@@ -14,7 +14,9 @@ const SPECS = {
14
14
  init: {
15
15
  ...COMMON,
16
16
  appkey: { type: 'string' },
17
+ yes: { type: 'boolean', short: 'y' },
17
18
  keystore: { type: 'string' },
19
+ 'keystore-properties': { type: 'string' },
18
20
  'key-alias': { type: 'string' },
19
21
  package: { type: 'string' },
20
22
  sdk: { type: 'string' },
@@ -23,6 +25,7 @@ const SPECS = {
23
25
  jdk: { type: 'string' },
24
26
  },
25
27
  doctor: { ...COMMON },
28
+ projects: { ...COMMON },
26
29
  devices: { ...COMMON },
27
30
  device: {
28
31
  ...COMMON,
@@ -37,16 +40,24 @@ const SPECS = {
37
40
  ...COMMON,
38
41
  mode: { type: 'string' },
39
42
  'skip-web': { type: 'boolean' },
43
+ 'skip-resource-check': { type: 'boolean' },
40
44
  out: { type: 'string' },
41
45
  install: { type: 'boolean' },
42
46
  device: { type: 'string' },
43
47
  offline: { type: 'boolean' },
48
+ 'no-daemon': { type: 'boolean' },
49
+ prune: { type: 'string' },
44
50
  'keep-workdir': { type: 'boolean' },
45
51
  'skip-version-check': { type: 'boolean' },
46
52
  'store-password': { type: 'string' },
47
53
  'key-password': { type: 'string' },
48
54
  },
49
- wgt: { ...COMMON, 'skip-web': { type: 'boolean' }, out: { type: 'string' } },
55
+ wgt: {
56
+ ...COMMON,
57
+ 'skip-web': { type: 'boolean' },
58
+ 'skip-resource-check': { type: 'boolean' },
59
+ out: { type: 'string' },
60
+ },
50
61
  debug: {
51
62
  ...COMMON,
52
63
  install: { type: 'boolean' },
@@ -55,7 +66,14 @@ const SPECS = {
55
66
  device: { type: 'string' },
56
67
  base: { type: 'string' },
57
68
  build: { type: 'boolean' },
69
+ hbuilderx: { type: 'boolean' },
70
+ playground: { type: 'string' },
71
+ 'custom-type': { type: 'string' },
72
+ ui: { type: 'boolean' },
58
73
  'skip-web': { type: 'boolean' },
74
+ 'skip-resource-check': { type: 'boolean' },
75
+ 'no-daemon': { type: 'boolean' },
76
+ prune: { type: 'string' },
59
77
  'store-password': { type: 'string' },
60
78
  'key-password': { type: 'string' },
61
79
  },
@@ -89,7 +107,7 @@ export async function main(argv) {
89
107
  options.positionals = positionals
90
108
  options.cwd = process.cwd()
91
109
  } catch (error) {
92
- console.error(error instanceof Error ? error.message : String(error))
110
+ console.error(translateArgsError(error, rest, spec))
93
111
  process.exitCode = 2
94
112
  return
95
113
  }
@@ -101,6 +119,9 @@ export async function main(argv) {
101
119
  } else if (command === 'doctor') {
102
120
  const { doctorCommand } = await import('./commands/doctor.js')
103
121
  await doctorCommand(options)
122
+ } else if (command === 'projects') {
123
+ const { projectsCommand } = await import('./commands/projects.js')
124
+ await projectsCommand(options)
104
125
  } else if (command === 'devices') {
105
126
  const { devicesCommand } = await import('./commands/devices.js')
106
127
  await devicesCommand(options)
@@ -134,6 +155,37 @@ export async function main(argv) {
134
155
  }
135
156
  }
136
157
 
158
+ /**
159
+ * node:util parseArgs 的报错是英文,且单横线长参数会被拆成短选项(-appkey → -a),
160
+ * 这里翻译成中文并提示正确写法,避免用户对着 "Unknown option '-a'" 猜。
161
+ * @param {unknown} error
162
+ * @param {string[]} args
163
+ * @param {Record<string, unknown>} spec
164
+ * @returns {string}
165
+ */
166
+ export function translateArgsError(error, args, spec) {
167
+ const message = error instanceof Error ? error.message : String(error)
168
+ const known = new Set(Object.keys(spec))
169
+ const mistaken = args.find((arg) => /^-[^-][\w-]+$/.test(arg) && known.has(arg.slice(1)))
170
+ if (mistaken) {
171
+ return `未知参数:${mistaken}\n长参数需要两个横线,改为:--${mistaken.slice(1)}`
172
+ }
173
+ const unknown = /Unknown option '(-[^']+)'/.exec(message)?.[1]
174
+ if (unknown) {
175
+ const flags = new Set()
176
+ for (const [key, value] of Object.entries(spec)) {
177
+ const short =
178
+ value && typeof value === 'object' && 'short' in value ? String(/** @type {any} */ (value).short ?? '') : ''
179
+ if (short) {
180
+ flags.add(`-${short}`)
181
+ }
182
+ flags.add(key.length === 1 ? `-${key}` : `--${key}`)
183
+ }
184
+ return `未知参数:${unknown}\n可用参数:${[...flags].sort().join(' ')}`
185
+ }
186
+ return message
187
+ }
188
+
137
189
  /**
138
190
  * @param {Record<string, unknown>} values
139
191
  */
@@ -151,12 +203,17 @@ function printHelp() {
151
203
 
152
204
  用法:
153
205
  uni-pack init [-p <dir>] [--appkey <key>] [--package <包名>] [--sdk <dir>] [--hbuilderx <dir>]
154
- [--android-sdk <dir>] [--jdk <dir>]
206
+ [--keystore <文件>] [--key-alias <别名>] [--keystore-properties <文件>]
207
+ [--android-sdk <dir>] [--jdk <dir>] [--yes]
208
+ (问答式写入 <项目>/uni-pack.config.json;缺环境会引导填写;CI 用 --yes 跳过)
155
209
  uni-pack doctor [-p <dir>] [--json] 环境自检
210
+ uni-pack projects 列出已登记项目(-p 可用项目名/目录名)
156
211
  uni-pack build [-p <dir>] [--mode release|debug] [--install] [--device <serial>]
157
- [--skip-web] [--out <dir>] [--offline]
158
- uni-pack wgt [-p <dir>] [--skip-web] [--out <dir>]
212
+ [--skip-web] [--skip-resource-check] [--out <dir>] [--offline]
213
+ [--prune <n>] [--no-daemon]
214
+ uni-pack wgt [-p <dir>] [--skip-web] [--skip-resource-check] [--out <dir>]
159
215
  uni-pack debug [-p <dir>] [--push] [--install] [--build] [--logs] [--device <serial>]
216
+ [--hbuilderx [--playground standard|custom] [--custom-type local|device] [--ui]]
160
217
  uni-pack devices 列出设备(同 device list)
161
218
  uni-pack device [list] 列出 USB / 无线设备
162
219
  uni-pack device pair [--timeout 120] [--service <名>] [--code <6位>]
@@ -178,6 +235,7 @@ function printHelp() {
178
235
  HBUILDERX_HOME HBuilderX 安装目录
179
236
  ANDROID_HOME Android SDK 根目录
180
237
  JAVA_HOME JDK 17+ 根目录
238
+ UNI_PACK_TEMP 前端构建临时目录(默认 <workDir>/<项目>/tmp)
181
239
 
182
240
  配置:~/.uniapp-android-cli/config.json(项目内 uni-pack.config.json 可覆盖项目级字段)
183
241
  `)
@@ -36,6 +36,10 @@ export async function buildCommand(options) {
36
36
  apk: result.apk,
37
37
  latest: result.latest,
38
38
  sha256: result.sha256,
39
+ apkRecord: result.apkRecord,
40
+ latestLinked: result.latestLinked,
41
+ resourceVersion: result.resourceVersion,
42
+ resourceVersionCode: result.resourceVersionCode,
39
43
  workDir: path.join(result.workRoot, 'gradle'),
40
44
  })
41
45
  return result
@@ -3,11 +3,16 @@ import { spawn } from 'node:child_process'
3
3
  import { buildProject } from '../core/build.js'
4
4
  import { installApk, listDevices, pickDevice, startApp } from '../core/adb.js'
5
5
  import { loadConfig, resolveProject } from '../core/config.js'
6
- import { exists } from '../core/fsx.js'
6
+ import { resolveDebugBase, resolveDebugDevice, resolveDebugLogs, resolveDebugStrategy } from '../core/debugPreset.js'
7
+ import { PackError, EXIT } from '../core/errors.js'
8
+ import { ensureDir, exists } from '../core/fsx.js'
9
+ import { resolveHbuilderx } from '../core/hbuilderx.js'
10
+ import { buildLaunchArgs, cliPath, ensureHbuilderxRunning, localCustomBasePath, runLaunch } from '../core/hbuilderxCli.js'
7
11
  import { Logger } from '../core/logger.js'
8
- import { apkBaseName } from '../core/output.js'
12
+ import { apkBaseName, resolveApkPrefix } from '../core/output.js'
9
13
  import { normalizeManifest, readProjectManifest } from '../core/project.js'
10
14
  import { resolveAndroidTools } from '../core/sdk.js'
15
+ import { resolveBuildTempDir, resolveWorkRoot } from '../core/workdir.js'
11
16
 
12
17
  /**
13
18
  * @param {Record<string, any>} options
@@ -16,6 +21,16 @@ export async function debugCommand(options) {
16
21
  const logger = new Logger(options)
17
22
  const config = await loadConfig()
18
23
  const { project } = await resolveProject(config, options.project, options.cwd)
24
+ const preset = project.debug ?? {}
25
+
26
+ options.device = resolveDebugDevice(options, preset) || undefined
27
+ options.logs = resolveDebugLogs(options, preset)
28
+
29
+ if (resolveDebugStrategy(options, preset) === 'hbuilderx') {
30
+ await runHbuilderxDebug({ config, project, options, logger, preset })
31
+ return
32
+ }
33
+
19
34
  const tools = await resolveAndroidTools(config)
20
35
 
21
36
  const devices = await listDevices(tools.adb)
@@ -33,7 +48,7 @@ export async function debugCommand(options) {
33
48
 
34
49
  let baseApk = options.base ? path.resolve(options.base) : ''
35
50
  if (!baseApk) {
36
- const baseName = apkBaseName(project.name ?? resolved.name, resolved.versionName, resolved.versionCode)
51
+ const baseName = apkBaseName(resolveApkPrefix(project, resolved), resolved.versionName, resolved.versionCode)
37
52
  const candidate = path.join(path.resolve(project.outputDir), `${baseName}_debug_latest.apk`)
38
53
  baseApk = (await exists(candidate)) ? candidate : ''
39
54
  }
@@ -68,6 +83,91 @@ export async function debugCommand(options) {
68
83
  }
69
84
  }
70
85
 
86
+ /**
87
+ * 用 HBuilderX CLI 真机运行:HBuilderX 负责编译、安装基座、差量同步与项目日志,
88
+ * uni-pack 只做环境检查和参数转发。
89
+ * @param {{ config: any, project: any, options: Record<string, any>, logger: Logger, preset: any }} input
90
+ */
91
+ async function runHbuilderxDebug(input) {
92
+ const { config, project, options, logger, preset } = input
93
+ if (options.playground && !['standard', 'custom'].includes(String(options.playground).toLowerCase())) {
94
+ throw new PackError(`--playground 只支持 standard 或 custom,收到:${options.playground}`, EXIT.CONFIG)
95
+ }
96
+ if (options.customType && !['local', 'device'].includes(String(options.customType).toLowerCase())) {
97
+ throw new PackError(`--custom-type 只支持 local 或 device,收到:${options.customType}`, EXIT.CONFIG)
98
+ }
99
+ const { playground, customType } = resolveDebugBase(options, preset)
100
+
101
+ const tools = await resolveAndroidTools(config)
102
+ const devices = await listDevices(tools.adb)
103
+ const device = pickDevice(devices, options.device ?? preset.device)
104
+ options.device = device.serial
105
+
106
+ // 本地自定义基座:先自己 adb install -r。
107
+ // HBuilderX 只按包名+版本判断“基座已是最新”,同版本的正式包会让它误判并跳过安装。
108
+ if (playground === 'custom' && customType === 'local') {
109
+ const baseApk = localCustomBasePath(project.projectDir)
110
+ if (!(await exists(baseApk))) {
111
+ throw new PackError(`找不到本地自定义基座:${baseApk}`, EXIT.PREFLIGHT, {
112
+ hint: '先在 HBuilderX 制作自定义基座(生成 unpackage/debug/android_debug.apk),或改用 --custom-type device',
113
+ })
114
+ }
115
+ logger.info(`安装本地自定义基座:${baseApk}`)
116
+ await installApk(tools.adb, baseApk, device.serial)
117
+ }
118
+
119
+ const hbuilderx = await resolveHbuilderx(config, { project })
120
+ if (!hbuilderx) {
121
+ throw new PackError('找不到 HBuilderX,无法使用 --hbuilderx 运行', EXIT.PREFLIGHT, {
122
+ hint: '运行 uni-pack init 配置 hbuilderx.root,或设置 HBUILDERX_HOME',
123
+ })
124
+ }
125
+ const cli = cliPath(hbuilderx.root)
126
+ if (!(await exists(cli))) {
127
+ throw new PackError(`找不到 HBuilderX CLI:${cli}`, EXIT.PREFLIGHT, {
128
+ hint: '确认 hbuilderx.root 指向 HBuilderX 安装目录(与 cli.exe 同级)',
129
+ })
130
+ }
131
+
132
+ const workRoot = resolveWorkRoot(config, project)
133
+ const temp = resolveBuildTempDir(workRoot)
134
+ await ensureDir(temp.tempDir)
135
+ const env = { TEMP: temp.tempDir, TMP: temp.tempDir }
136
+
137
+ logger.step(`HBuilderX 真机运行:${project.projectDir}`)
138
+ const version = await ensureHbuilderxRunning({ cli, logger, env })
139
+ logger.info(`HBuilderX ${version.raw}${options.logs ? '(项目日志会直接输出)' : ''}`)
140
+
141
+ let packageName = ''
142
+ if (playground === 'custom' && customType === 'device') {
143
+ const { manifest } = await readProjectManifest(project.projectDir)
144
+ packageName = normalizeManifest(manifest, { package: project.package }, { validate: false }).packageName
145
+ if (!packageName) {
146
+ throw new PackError('--custom-type device 需要知道设备上基座的包名', EXIT.CONFIG, {
147
+ hint: '在 manifest 的 app-plus.distribute.android.packagename 配好包名,或改用 --custom-type local',
148
+ })
149
+ }
150
+ }
151
+
152
+ if (options.push || options.base || options.install || options.build) {
153
+ logger.info('--hbuilderx 模式下由 HBuilderX 负责构建/安装/启动,--push/--base/--install 会忽略')
154
+ }
155
+
156
+ const args = buildLaunchArgs({
157
+ projectDir: project.projectDir,
158
+ deviceId: options.device,
159
+ playground: /** @type {'standard' | 'custom'} */ (playground),
160
+ customType: /** @type {'local' | 'device'} */ (customType),
161
+ packageName,
162
+ ui: Boolean(options.ui),
163
+ })
164
+ logger.info(`保存代码后自动差量编译并同步;Ctrl+C 结束${options.ui ? '(界面模式)' : ''}`)
165
+ const code = await runLaunch({ cli, args, env })
166
+ if (code !== 0) {
167
+ throw new PackError(`HBuilderX 运行结束(退出码 ${code})`, EXIT.DEVICE)
168
+ }
169
+ }
170
+
71
171
  /**
72
172
  * @param {string} adb
73
173
  * @param {string} serial
@@ -110,7 +110,13 @@ async function pairByQr(adb, options, logger) {
110
110
  const pairing = await waitForPairingService(adb, service, before, timeout)
111
111
  if (!pairing) {
112
112
  throw new PackError(`等待超时:没有发现配对服务 ${service}`, EXIT.DEVICE, {
113
- hint: '确认手机与电脑在同一 Wi-Fi,且已选择“使用二维码配对设备”;关闭 VPN/代理后重试',
113
+ hint: [
114
+ '确认手机与电脑在同一 Wi-Fi,且已选择“使用二维码配对设备”;关闭 VPN/代理后重试。',
115
+ '仍不行改用配对码方式:手机 无线调试 → “使用配对码配对设备”,然后执行',
116
+ ' uni-pack device pair <手机显示的 IP:端口> <6 位配对码>',
117
+ '配对完成后在无线调试主页查看 IP:端口,执行 uni-pack device connect <IP:端口>',
118
+ '诊断:另开终端执行 uni-pack device mdns,应能看到 _adb-tls-pairing._tcp 服务',
119
+ ].join('\n'),
114
120
  })
115
121
  }
116
122
 
@@ -149,7 +155,7 @@ async function pairByCode(adb, addressValue, codeValue, logger) {
149
155
  const host = hostOf(address)
150
156
  const connectService = await waitForConnectService(adb, host, before, 10)
151
157
  if (!connectService) {
152
- logger.info(`连接:uni-pack device connect ${host}:5555`)
158
+ logger.info('已配对。请在手机“无线调试”主页查看 IP:端口,执行:uni-pack device connect <IP:端口>')
153
159
  return
154
160
  }
155
161
  await connect(adb, connectService.address, logger)
@@ -142,6 +142,16 @@ export async function doctorCommand(options) {
142
142
  }
143
143
 
144
144
  const failed = checks.filter((check) => !check.ok)
145
+ const blocking = failed.filter((check) => check.name !== 'ADB 设备')
146
+ if (project) {
147
+ if (blocking.length === 0) {
148
+ logger.info(
149
+ `下一步:uni-pack build -p "${project.projectDir}"(正式包);调试基座加 --mode debug,资源包用 uni-pack wgt`,
150
+ )
151
+ } else {
152
+ logger.info('先按上面的告警处理,再执行 build / wgt')
153
+ }
154
+ }
145
155
  logger.output('doctor', { ok: failed.length === 0, checks })
146
156
  if (failed.length > 0) {
147
157
  process.exitCode = 3