uniapp-android-cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,250 @@
1
+ import path from 'node:path'
2
+ import { PackError, EXIT } from './errors.js'
3
+ import { exists, readJson, readJsonc, readText } from './fsx.js'
4
+
5
+ /**
6
+ * @typedef {Object} ProjectManifest
7
+ * @property {string} appid
8
+ * @property {string} name
9
+ * @property {string} versionName
10
+ * @property {number} versionCode
11
+ * @property {string} packageName
12
+ * @property {string[]} abiFilters
13
+ * @property {number} minSdkVersion
14
+ * @property {number} targetSdkVersion
15
+ * @property {string[]} permissions
16
+ * @property {string[]} features
17
+ * @property {string[]} modules
18
+ */
19
+
20
+ /**
21
+ * @typedef {Object} ProjectLayout
22
+ * @property {'cli' | 'hbuilderx' | 'unknown'} type
23
+ * @property {string} inputDir uni-app 源码目录(CLI 为 src,HBuilderX 为项目根)
24
+ * @property {string} manifestFile manifest.json 路径
25
+ */
26
+
27
+ /**
28
+ * 两种项目的结构差异:
29
+ * - CLI(vite starter):src/manifest.json,产物 dist/build/app
30
+ * - HBuilderX:根目录 manifest.json(JSONC),产物 unpackage/dist/build/app-plus
31
+ * @param {string} projectDir
32
+ * @returns {Promise<ProjectLayout>}
33
+ */
34
+ export async function detectProject(projectDir) {
35
+ const srcManifest = path.join(projectDir, 'src/manifest.json')
36
+ if (await exists(srcManifest)) {
37
+ return { type: 'cli', inputDir: path.join(projectDir, 'src'), manifestFile: srcManifest }
38
+ }
39
+ const rootManifest = path.join(projectDir, 'manifest.json')
40
+ if (await exists(rootManifest)) {
41
+ return { type: 'hbuilderx', inputDir: projectDir, manifestFile: rootManifest }
42
+ }
43
+ return { type: 'unknown', inputDir: projectDir, manifestFile: '' }
44
+ }
45
+
46
+ /**
47
+ * @param {string} projectDir
48
+ * @returns {Promise<boolean>}
49
+ */
50
+ export async function isUniappProject(projectDir) {
51
+ return (await detectProject(projectDir)).type !== 'unknown'
52
+ }
53
+
54
+ /**
55
+ * 读取项目 manifest:优先生成后的 src/manifest.json,其次已构建产物,最后项目根目录。
56
+ * HBuilderX 的 manifest.json 含注释与末尾逗号,走 JSONC 解析。
57
+ * @param {string} projectDir
58
+ * @returns {Promise<{ manifest: any, file: string, type: ProjectLayout['type'], inputDir: string }>}
59
+ */
60
+ export async function readProjectManifest(projectDir) {
61
+ const layout = await detectProject(projectDir)
62
+ if (layout.type !== 'unknown') {
63
+ return {
64
+ manifest: await readJsonc(layout.manifestFile),
65
+ file: layout.manifestFile,
66
+ type: layout.type,
67
+ inputDir: layout.inputDir,
68
+ }
69
+ }
70
+
71
+ const candidates = [
72
+ { file: path.join(projectDir, 'dist/build/app/manifest.json'), type: 'cli', inputDir: path.join(projectDir, 'src') },
73
+ {
74
+ file: path.join(projectDir, 'unpackage/dist/build/app-plus/manifest.json'),
75
+ type: 'hbuilderx',
76
+ inputDir: projectDir,
77
+ },
78
+ { file: path.join(projectDir, 'unpackage/dist/build/app/manifest.json'), type: 'hbuilderx', inputDir: projectDir },
79
+ ]
80
+ for (const candidate of candidates) {
81
+ if (await exists(candidate.file)) {
82
+ return {
83
+ manifest: await readJson(candidate.file),
84
+ file: candidate.file,
85
+ type: /** @type {ProjectLayout['type']} */ (candidate.type),
86
+ inputDir: candidate.inputDir,
87
+ }
88
+ }
89
+ }
90
+
91
+ throw new PackError(`找不到 manifest.json:${projectDir}`, EXIT.CONFIG, {
92
+ hint: '确认目录是 uni-app 项目(CLI 项目有 src/manifest.json,HBuilderX 项目根目录有 manifest.json)',
93
+ })
94
+ }
95
+
96
+ /**
97
+ * HBuilderX 项目常常不在 manifest.json 里写包名(云打包时单独填),
98
+ * 项目根的 AndroidManifest.xml 是最后可用的兜底来源。
99
+ * HBuilderX 实际打包会把包名转小写,AppKey 又按包名绑定,这里保持一致。
100
+ * @param {string} projectDir
101
+ * @returns {Promise<string>}
102
+ */
103
+ export async function readProjectPackage(projectDir) {
104
+ const file = path.join(projectDir, 'AndroidManifest.xml')
105
+ if (!(await exists(file))) {
106
+ return ''
107
+ }
108
+ const value = /package="([^"]+)"/.exec(await readText(file))?.[1] ?? ''
109
+ return value.toLowerCase()
110
+ }
111
+
112
+ /**
113
+ * HBuilderX 的 Vue 3 项目会在 manifest 里写 "vueVersion": "3";没有该字段按 Vue 2 处理。
114
+ * @param {any} manifest
115
+ * @returns {2 | 3}
116
+ */
117
+ export function readVueVersion(manifest) {
118
+ return String(manifest?.vueVersion ?? '').trim() === '3' ? 3 : 2
119
+ }
120
+
121
+ /**
122
+ * CLI 项目通常不在 manifest 写 vueVersion,改从 package.json 的 vue / @dcloudio 版本推断。
123
+ * @param {string} projectDir
124
+ * @param {any} manifest
125
+ * @param {'cli' | 'hbuilderx' | 'unknown'} type
126
+ * @returns {Promise<2 | 3>}
127
+ */
128
+ export async function detectVueVersion(projectDir, manifest, type = 'cli') {
129
+ const declared = String(manifest?.vueVersion ?? '').trim()
130
+ if (declared === '2' || declared === '3') {
131
+ return declared === '3' ? 3 : 2
132
+ }
133
+ if (type === 'hbuilderx') {
134
+ return 2
135
+ }
136
+
137
+ const packageFile = path.join(projectDir, 'package.json')
138
+ if (await exists(packageFile)) {
139
+ const pkg = await readJson(packageFile).catch(() => ({}))
140
+ const dependencies = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) }
141
+ const candidates = [dependencies.vue, dependencies['@dcloudio/uni-app']].map((value) => String(value ?? ''))
142
+ if (candidates.some((value) => /^2\./.test(value))) {
143
+ return 2
144
+ }
145
+ if (candidates.some((value) => /^3\./.test(value))) {
146
+ return 3
147
+ }
148
+ }
149
+ return 3
150
+ }
151
+
152
+ /**
153
+ * @param {...any} values
154
+ */
155
+ function firstPresent(...values) {
156
+ for (const value of values) {
157
+ if (value !== undefined && value !== null && value !== '') {
158
+ return value
159
+ }
160
+ }
161
+ return undefined
162
+ }
163
+
164
+ /**
165
+ * manifest 是唯一来源,fallbacks 只在该字段缺失时兜底。
166
+ * 配置里的同名字段可能是 init 时的快照,直接覆盖会让改过 manifest 的项目静默打旧版本。
167
+ * @param {any} manifest
168
+ * @param {any} [fallbacks]
169
+ * @param {{ validate?: boolean }} [options]
170
+ * @returns {ProjectManifest}
171
+ */
172
+ export function normalizeManifest(manifest, fallbacks = {}, options = {}) {
173
+ const distribute = manifest?.['app-plus']?.distribute ?? {}
174
+ const android = distribute.android ?? {}
175
+ const manifestAbi = Array.isArray(android.abiFilters) && android.abiFilters.length > 0 ? android.abiFilters : undefined
176
+
177
+ const permissions = extractPermissionNames(android.permissions ?? [])
178
+ const features = extractFeatureNames(android.permissions ?? [])
179
+
180
+ const result = {
181
+ appid: String(firstPresent(manifest?.appid, fallbacks.appid) ?? ''),
182
+ name: String(firstPresent(manifest?.name, fallbacks.name) ?? ''),
183
+ versionName: String(firstPresent(manifest?.versionName, fallbacks.versionName) ?? '1.0.0'),
184
+ versionCode: Number(firstPresent(manifest?.versionCode, manifest?.version?.code, fallbacks.versionCode) ?? 1),
185
+ packageName: String(firstPresent(android.packagename, fallbacks.package) ?? ''),
186
+ abiFilters: firstPresent(manifestAbi, fallbacks.abiFilters, ['armeabi-v7a', 'arm64-v8a']),
187
+ minSdkVersion: Number(firstPresent(android.minSdkVersion, fallbacks.minSdkVersion, 21)),
188
+ targetSdkVersion: Number(firstPresent(android.targetSdkVersion, fallbacks.targetSdkVersion, 30)),
189
+ permissions,
190
+ features,
191
+ modules: Object.keys(manifest?.['app-plus']?.modules ?? {}),
192
+ }
193
+
194
+ if (options.validate !== false) {
195
+ validateManifest(result)
196
+ }
197
+ return result
198
+ }
199
+
200
+ /**
201
+ * @param {ProjectManifest} manifest
202
+ */
203
+ function validateManifest(manifest) {
204
+ if (!/^__UNI__[0-9A-F]+$/i.test(manifest.appid)) {
205
+ throw new PackError(`appid 不合法:${manifest.appid || '(空)'},应为 __UNI__XXXXXX`, EXIT.CONFIG)
206
+ }
207
+ if (!/^[a-z][a-z0-9_]*(\.[a-z0-9_]+)+$/i.test(manifest.packageName)) {
208
+ throw new PackError(`包名不合法:${manifest.packageName || '(空)'}`, EXIT.CONFIG, {
209
+ hint: '在 manifest.json 的 app-plus.distribute.android.packagename 填写,或 init 时用 --package 指定',
210
+ })
211
+ }
212
+ if (!Number.isInteger(manifest.versionCode) || manifest.versionCode <= 0) {
213
+ throw new PackError(`versionCode 不合法:${manifest.versionCode}`, EXIT.CONFIG)
214
+ }
215
+ if (!manifest.versionName) {
216
+ throw new PackError('versionName 为空', EXIT.CONFIG)
217
+ }
218
+ }
219
+
220
+ /**
221
+ * @param {string[]} entries
222
+ * @returns {string[]}
223
+ */
224
+ export function extractPermissionNames(entries) {
225
+ /** @type {string[]} */
226
+ const names = []
227
+ for (const entry of entries) {
228
+ const match = /<uses-permission[^>]*android:name="([^"]+)"/.exec(entry)
229
+ if (match) {
230
+ names.push(match[1])
231
+ }
232
+ }
233
+ return names
234
+ }
235
+
236
+ /**
237
+ * @param {string[]} entries
238
+ * @returns {string[]} 形如 "android.hardware.touchscreen|false"
239
+ */
240
+ export function extractFeatureNames(entries) {
241
+ /** @type {string[]} */
242
+ const features = []
243
+ for (const entry of entries) {
244
+ const match = /<uses-feature[^>]*android:name="([^"]+)"[^>]*android:required="(true|false)"/.exec(entry)
245
+ if (match) {
246
+ features.push(`${match[1]}|${match[2]}`)
247
+ }
248
+ }
249
+ return features
250
+ }
@@ -0,0 +1,13 @@
1
+ import qrcode from 'qrcode-terminal'
2
+
3
+ /**
4
+ * @param {string} text
5
+ * @returns {string}
6
+ */
7
+ export function renderQr(text) {
8
+ let output = ''
9
+ qrcode.generate(text, { small: true }, (code) => {
10
+ output = code
11
+ })
12
+ return output
13
+ }
@@ -0,0 +1,398 @@
1
+ import os from 'node:os'
2
+ import path from 'node:path'
3
+ import { readdir } from 'node:fs/promises'
4
+ import { PackError, EXIT } from './errors.js'
5
+ import { exists, readText } from './fsx.js'
6
+ import { run } from './process.js'
7
+
8
+ /** 基础 AAR:与当前线上可运行的自定义基座保持一致 */
9
+ export const BASE_AARS = [
10
+ 'android-gif-drawable-1.2.29.aar',
11
+ 'audio-mp3aac-release.aar',
12
+ 'breakpad-build-release.aar',
13
+ 'lib.5plus.base-release.aar',
14
+ 'msa_mdid_1.0.13.aar',
15
+ 'uni-chooseMedia-release.aar',
16
+ 'uni-createRequestPermissionListener-release.aar',
17
+ 'uni-exit-release.aar',
18
+ 'uni-getAccessibilityInfo-release.aar',
19
+ 'uni-getAppAuthorizeSetting-release.aar',
20
+ 'uni-getAppBaseInfo-release.aar',
21
+ 'uni-getDeviceInfo-release.aar',
22
+ 'uni-getNetworkType-release.aar',
23
+ 'uni-getSystemInfo-release.aar',
24
+ 'uni-getSystemSetting-release.aar',
25
+ 'uni-installApk-release.aar',
26
+ 'uni-network-release.aar',
27
+ 'uni-openAppAuthorizeSetting-release.aar',
28
+ 'uni-prompt-release.aar',
29
+ 'uni-storage-release.aar',
30
+ 'uniapp-v8-release.aar',
31
+ ]
32
+
33
+ export const DEBUG_AAR = 'debug-server-release.aar'
34
+
35
+ /**
36
+ * manifest.json 的 app-plus.modules 与 SDK/libs 里的 AAR 不是一一对应,常见的做映射,
37
+ * 认不出的模块给出提示而不是直接失败(很多模块已经并进核心 AAR)。
38
+ */
39
+ export const MODULE_AARS = {
40
+ Barcode: ['barcode-release.aar'],
41
+ Bluetooth: ['Bluetooth-release.aar'],
42
+ Camera: ['media-release.aar'],
43
+ VideoPlayer: ['media-release.aar', 'weex_videoplayer-release.aar'],
44
+ Audio: ['audio-mp3aac-release.aar'],
45
+ Speech: ['speech-release.aar'],
46
+ Fingerprint: ['fingerprint-release.aar'],
47
+ Contacts: ['contacts-release.aar'],
48
+ Messaging: ['messaging-release.aar'],
49
+ iBeacon: ['iBeacon-release.aar'],
50
+ Share: ['share-weixin-release.aar', 'share-qq-release.aar', 'share-sina-release.aar'],
51
+ Payment: ['payment-weixin-release.aar', 'payment-alipay-release.aar'],
52
+ OAuth: ['oauth-weixin-release.aar', 'oauth-qq-release.aar', 'oauth-sina-release.aar'],
53
+ Statistic: ['statistic-release.aar'],
54
+ }
55
+
56
+ /**
57
+ * 接受用户可能给的各种层级:SDK 根、解压出来的归档根,甚至 HBuilder-Integrate-AS 本身。
58
+ * @param {string} input
59
+ * @returns {Promise<string>} 含 HBuilder-Integrate-AS 的目录;找不到返回空串
60
+ */
61
+ export async function resolveSdkRootInput(input) {
62
+ const value = String(input ?? '').trim()
63
+ if (!value) {
64
+ return ''
65
+ }
66
+ const root = path.resolve(value)
67
+ if (path.basename(root) === 'HBuilder-Integrate-AS') {
68
+ return path.dirname(root)
69
+ }
70
+ if (await exists(path.join(root, 'HBuilder-Integrate-AS'))) {
71
+ return root
72
+ }
73
+ const nested = path.join(root, path.basename(root))
74
+ if (await exists(path.join(nested, 'HBuilder-Integrate-AS'))) {
75
+ return nested
76
+ }
77
+ const entries = await readdir(root, { withFileTypes: true }).catch(() => [])
78
+ const candidates = entries
79
+ .filter((entry) => entry.isDirectory() && entry.name.startsWith('Android-SDK@'))
80
+ .map((entry) => path.join(root, entry.name))
81
+ .sort()
82
+ .reverse()
83
+ for (const candidate of candidates) {
84
+ if (await exists(path.join(candidate, 'HBuilder-Integrate-AS'))) {
85
+ return candidate
86
+ }
87
+ const deep = path.join(candidate, path.basename(candidate))
88
+ if (await exists(path.join(deep, 'HBuilder-Integrate-AS'))) {
89
+ return deep
90
+ }
91
+ }
92
+ return ''
93
+ }
94
+
95
+ /**
96
+ * 解析离线 SDK。显式配置优先;没有显式配置时按项目的编译器版本在已安装的 Android-SDK@x.yy 里找。
97
+ * @param {any} config
98
+ * @param {{ project?: any, version?: string, searchDirs?: string[] }} [options]
99
+ */
100
+ export async function resolveSdk(config, options = {}) {
101
+ const explicit = [options.project?.sdkRoot, config.sdk?.root, process.env.UNI_SDK_ROOT]
102
+ .map((item) => String(item ?? '').trim())
103
+ .filter(Boolean)
104
+
105
+ let invalid = ''
106
+ for (const candidate of explicit) {
107
+ const root = await resolveSdkRootInput(candidate)
108
+ if (root) {
109
+ return validateSdkRoot(root, config)
110
+ }
111
+ invalid = candidate
112
+ }
113
+
114
+ const version = String(options.version ?? '').trim()
115
+ if (version) {
116
+ const matched = await findSdkForVersion(config, version, options.searchDirs)
117
+ if (matched) {
118
+ return validateSdkRoot(matched, config)
119
+ }
120
+ if (invalid) {
121
+ throw new PackError(`离线 SDK 路径无效:${invalid}`, EXIT.PREFLIGHT, {
122
+ hint: `未找到与 uni-app ${version} 匹配的其他 SDK;--sdk / sdk.root 应指向包含 HBuilder-Integrate-AS 的 Android-SDK@x.yy 目录`,
123
+ })
124
+ }
125
+ const installed = await listInstalledSdks(config, options.searchDirs)
126
+ throw new PackError(`未找到与 uni-app ${version} 匹配的离线 SDK`, EXIT.PREFLIGHT, {
127
+ hint: [
128
+ `已安装的 SDK:${installed.map((item) => item.version).join(', ') || '(未扫描到)'}`,
129
+ `请下载 Android-SDK@${version} 放到 ${defaultSdkDirs(config).join(' 或 ')},`,
130
+ '或在配置里指定该项目的 sdkRoot / sdk.root',
131
+ ].join('\n'),
132
+ })
133
+ }
134
+
135
+ if (invalid) {
136
+ throw new PackError(`离线 SDK 路径无效:${invalid}`, EXIT.PREFLIGHT, {
137
+ hint: 'UNI_SDK_ROOT / --sdk 应指向包含 HBuilder-Integrate-AS 的 Android-SDK@x.yy 目录',
138
+ })
139
+ }
140
+
141
+ throw new PackError('未配置离线 SDK 路径(sdk.root)', EXIT.PREFLIGHT, {
142
+ hint: '运行 uni-pack init --sdk <目录>,或设置环境变量 UNI_SDK_ROOT,或手工填写 ~/.uniapp-android-cli/config.json',
143
+ })
144
+ }
145
+
146
+ /**
147
+ * @param {string} root
148
+ * @param {any} config
149
+ */
150
+ async function validateSdkRoot(root, config) {
151
+ const templateRoot = path.join(root, String(config.sdk?.template ?? 'HBuilder-Integrate-AS'))
152
+ const moduleDir = path.join(templateRoot, 'simpleDemo')
153
+ const libsDir = path.join(root, String(config.sdk?.libsDir ?? 'SDK/libs'))
154
+ const dataDir = path.join(root, String(config.sdk?.dataDir ?? 'SDK/assets/data'))
155
+
156
+ const required = [
157
+ path.join(libsDir, 'lib.5plus.base-release.aar'),
158
+ path.join(moduleDir, 'build.gradle'),
159
+ path.join(moduleDir, 'src/main/AndroidManifest.xml'),
160
+ path.join(dataDir, 'dcloud_control.xml'),
161
+ ]
162
+ const missing = []
163
+ for (const item of required) {
164
+ if (!(await exists(item))) {
165
+ missing.push(item)
166
+ }
167
+ }
168
+ if (missing.length > 0) {
169
+ throw new PackError(`离线 SDK 不完整,缺少:\n${missing.join('\n')}`, EXIT.PREFLIGHT)
170
+ }
171
+
172
+ const gradlew = path.join(templateRoot, process.platform === 'win32' ? 'gradlew.bat' : 'gradlew')
173
+ if (!(await exists(gradlew))) {
174
+ throw new PackError(`找不到 ${gradlew}`, EXIT.PREFLIGHT)
175
+ }
176
+
177
+ return { root, templateRoot, moduleDir, libsDir, dataDir, gradlew }
178
+ }
179
+
180
+ /**
181
+ * @param {any} config
182
+ * @param {string[]} [extraDirs]
183
+ * @returns {string[]}
184
+ */
185
+ function defaultSdkDirs(config, extraDirs = []) {
186
+ return [
187
+ ...extraDirs,
188
+ ...(config?.sdk?.searchDirs ?? []),
189
+ config?.sdk?.root ? path.dirname(path.resolve(String(config.sdk.root))) : '',
190
+ ...String(process.env.UNI_SDK_DIRS ?? '').split(path.delimiter),
191
+ 'C:/develop/android-sdk/uniapp-Android',
192
+ path.join(os.homedir(), 'android-sdk', 'uniapp-Android'),
193
+ ].filter((item) => typeof item === 'string' && item.trim())
194
+ }
195
+
196
+ /**
197
+ * 扫描 Android-SDK@x.yy 目录。解压后常见一层同名嵌套,交给 resolveSdkRootInput 处理。
198
+ * @param {any} config
199
+ * @param {string[]} [extraDirs]
200
+ * @returns {Promise<Array<{ version: string, root: string, name: string }>>}
201
+ */
202
+ export async function listInstalledSdks(config, extraDirs = []) {
203
+ /** @type {Array<{ version: string, root: string, name: string }>} */
204
+ const found = []
205
+ const seen = new Set()
206
+ for (const dir of defaultSdkDirs(config, extraDirs)) {
207
+ const entries = await readdir(path.resolve(dir), { withFileTypes: true }).catch(() => [])
208
+ for (const entry of entries) {
209
+ if (!entry.isDirectory()) {
210
+ continue
211
+ }
212
+ const match = /^Android-SDK@(\d+\.\d+)\./i.exec(entry.name)
213
+ if (!match) {
214
+ continue
215
+ }
216
+ const root = await resolveSdkRootInput(path.join(dir, entry.name))
217
+ if (!root) {
218
+ continue
219
+ }
220
+ const key = root.toLowerCase()
221
+ if (seen.has(key)) {
222
+ continue
223
+ }
224
+ seen.add(key)
225
+ found.push({ version: match[1], root, name: entry.name })
226
+ }
227
+ }
228
+ return found.sort((a, b) => b.name.localeCompare(a.name))
229
+ }
230
+
231
+ /**
232
+ * @param {any} config
233
+ * @param {string} version
234
+ * @param {string[]} [extraDirs]
235
+ * @returns {Promise<string>}
236
+ */
237
+ export async function findSdkForVersion(config, version, extraDirs = []) {
238
+ const installed = await listInstalledSdks(config, extraDirs)
239
+ return installed.find((item) => item.version === version)?.root ?? ''
240
+ }
241
+
242
+ /**
243
+ * 老版本 SDK 的 compileSdk/buildTools 与新版不同,优先沿用 SDK 自带的模板值。
244
+ * @param {string} templateRoot
245
+ * @returns {Promise<{ compileSdkVersion?: number, buildToolsVersion?: string }>}
246
+ */
247
+ export async function readTemplateDefaults(templateRoot) {
248
+ const file = path.join(templateRoot, 'simpleDemo', 'build.gradle')
249
+ if (!(await exists(file))) {
250
+ return {}
251
+ }
252
+ const text = await readText(file)
253
+ const compileSdk = Number(/compileSdkVersion\s+(\d+)/.exec(text)?.[1])
254
+ const buildTools = /buildToolsVersion\s+'([^']+)'/.exec(text)?.[1]
255
+ return {
256
+ compileSdkVersion: Number.isFinite(compileSdk) ? compileSdk : undefined,
257
+ buildToolsVersion: buildTools || undefined,
258
+ }
259
+ }
260
+
261
+ /**
262
+ * @param {string} sdkDir
263
+ * @returns {Promise<string[]>}
264
+ */
265
+ async function listBuildTools(sdkDir) {
266
+ const dir = path.join(sdkDir, 'build-tools')
267
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => [])
268
+ return entries
269
+ .filter((entry) => entry.isDirectory())
270
+ .map((entry) => entry.name)
271
+ .sort((a, b) => compareDotted(b, a))
272
+ }
273
+
274
+ /**
275
+ * @param {string} a
276
+ * @param {string} b
277
+ */
278
+ function compareDotted(a, b) {
279
+ const left = a.split(/[.-]/).map(Number)
280
+ const right = b.split(/[.-]/).map(Number)
281
+ for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
282
+ const diff = (left[index] || 0) - (right[index] || 0)
283
+ if (diff !== 0) {
284
+ return diff
285
+ }
286
+ }
287
+ return a.localeCompare(b)
288
+ }
289
+
290
+ /**
291
+ * @param {any} config
292
+ * @returns {string}
293
+ */
294
+ function resolveAndroidSdkDir(config) {
295
+ const configured = String(config.android?.sdkDir ?? '').trim()
296
+ const candidate = configured || String(process.env.ANDROID_HOME || process.env.ANDROID_SDK_ROOT || '').trim()
297
+ if (!candidate) {
298
+ throw new PackError('未配置 Android SDK 路径(android.sdkDir)', EXIT.PREFLIGHT, {
299
+ hint: '运行 uni-pack init --android-sdk <目录>,或设置环境变量 ANDROID_HOME',
300
+ })
301
+ }
302
+ return path.resolve(candidate)
303
+ }
304
+
305
+ /**
306
+ * 只依赖 adb 的命令(设备列表/配对)不需要 JDK 与 build-tools。
307
+ * @param {any} config
308
+ * @returns {Promise<string>}
309
+ */
310
+ export async function resolveAdbPath(config) {
311
+ const adb = path.join(
312
+ resolveAndroidSdkDir(config),
313
+ 'platform-tools',
314
+ `adb${process.platform === 'win32' ? '.exe' : ''}`,
315
+ )
316
+ if (!(await exists(adb))) {
317
+ throw new PackError(`找不到 adb:${adb}`, EXIT.PREFLIGHT, {
318
+ hint: '在 Android SDK Manager 里安装 Platform-Tools',
319
+ })
320
+ }
321
+ return adb
322
+ }
323
+
324
+ /**
325
+ * @param {any} config
326
+ * @param {{ preferredBuildTools?: string }} [options]
327
+ */
328
+ export async function resolveAndroidTools(config, options = {}) {
329
+ const sdkDir = resolveAndroidSdkDir(config)
330
+
331
+ const installed = await listBuildTools(sdkDir)
332
+ const wanted = [
333
+ String(config.android?.buildTools ?? '').trim(),
334
+ String(options.preferredBuildTools ?? '').trim(),
335
+ ].filter(Boolean)
336
+ const buildTools = wanted.find((item) => installed.includes(item)) ?? installed[0]
337
+ if (!buildTools) {
338
+ throw new PackError(`Android SDK 下没有 build-tools:${path.join(sdkDir, 'build-tools')}`, EXIT.PREFLIGHT)
339
+ }
340
+
341
+ const buildToolsDir = path.join(sdkDir, 'build-tools', buildTools)
342
+ const suffix = process.platform === 'win32' ? '.bat' : ''
343
+ const apksigner = path.join(buildToolsDir, `apksigner${suffix}`)
344
+ const zipalign = path.join(buildToolsDir, `zipalign${process.platform === 'win32' ? '.exe' : ''}`)
345
+ const adb = path.join(sdkDir, 'platform-tools', `adb${process.platform === 'win32' ? '.exe' : ''}`)
346
+ const keytool = await resolveKeytool(config)
347
+
348
+ if (!(await exists(apksigner))) {
349
+ throw new PackError(`找不到 apksigner:${apksigner}`, EXIT.PREFLIGHT)
350
+ }
351
+
352
+ return { sdkDir, buildTools, buildToolsDir, apksigner, zipalign, adb, keytool }
353
+ }
354
+
355
+ /**
356
+ * @param {any} config
357
+ * @returns {Promise<string>}
358
+ */
359
+ export async function resolveJavaHome(config) {
360
+ const candidates = [
361
+ config.android?.jdk,
362
+ process.env.JAVA_HOME,
363
+ 'C:/Program Files/Java/jdk-21',
364
+ 'C:/Program Files/Java/jdk-17',
365
+ ].filter((item) => typeof item === 'string' && item.length > 0)
366
+
367
+ for (const candidate of candidates) {
368
+ const java = path.join(String(candidate), 'bin', process.platform === 'win32' ? 'java.exe' : 'java')
369
+ if (await exists(java)) {
370
+ return String(candidate)
371
+ }
372
+ }
373
+ throw new PackError('找不到 JDK,请在配置里填写 android.jdk 或设置 JAVA_HOME', EXIT.PREFLIGHT)
374
+ }
375
+
376
+ /**
377
+ * @param {any} config
378
+ * @returns {Promise<string>}
379
+ */
380
+ async function resolveKeytool(config) {
381
+ const javaHome = await resolveJavaHome(config)
382
+ return path.join(javaHome, 'bin', process.platform === 'win32' ? 'keytool.exe' : 'keytool')
383
+ }
384
+
385
+ /**
386
+ * @param {string} keytool
387
+ * @param {string} keystore
388
+ * @param {string} storePassword
389
+ * @param {string} alias
390
+ */
391
+ export async function readKeystoreFingerprint(keytool, keystore, storePassword, alias) {
392
+ const { stdout } = await run(keytool, ['-list', '-v', '-keystore', keystore, '-storepass', storePassword, '-alias', alias], {
393
+ allowFailure: false,
394
+ })
395
+ const sha1 = /SHA1:\s*([0-9A-F:]+)/i.exec(stdout)?.[1] ?? ''
396
+ const sha256 = /SHA256:\s*([0-9A-F:]+)/i.exec(stdout)?.[1] ?? ''
397
+ return { sha1, sha256, raw: stdout }
398
+ }