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.
@@ -0,0 +1,87 @@
1
+ import path from 'node:path'
2
+ import { PackError, EXIT } from './errors.js'
3
+ import { readJson } from './fsx.js'
4
+
5
+ /**
6
+ * 前端产物 manifest 里的版本字段(构建产物里是 version.name / version.code)。
7
+ * @typedef {Object} ResourceVersion
8
+ * @property {string} versionName
9
+ * @property {number} versionCode
10
+ */
11
+
12
+ /**
13
+ * @param {any} manifest 前端产物的 manifest.json
14
+ * @returns {ResourceVersion}
15
+ */
16
+ export function readResourceVersion(manifest) {
17
+ const version = manifest?.version ?? {}
18
+ return {
19
+ versionName: String(version.name ?? ''),
20
+ versionCode: Number(version.code ?? 0),
21
+ }
22
+ }
23
+
24
+ /**
25
+ * 前端产物只是 dist 里的一份静态资源:bump 版本后如果没重新编译(或用了 --skip-web),
26
+ * 会打出「新版本号 + 旧资源」,签名与体积检查都发现不了,只能靠版本一致性闸门。
27
+ * @param {ResourceVersion} resource
28
+ * @param {{ versionName: string, versionCode: number }} expected 项目 manifest 解析出的版本
29
+ * @returns {{ ok: boolean, message: string }}
30
+ */
31
+ export function compareResourceVersion(resource, expected) {
32
+ const versionName = String(expected.versionName ?? '')
33
+ const versionCode = Number(expected.versionCode ?? 0)
34
+ const ok = resource.versionName === versionName && resource.versionCode === versionCode
35
+ return {
36
+ ok,
37
+ message: ok
38
+ ? ''
39
+ : `前端产物版本 ${resource.versionName || '(空)'}(${resource.versionCode}) 与项目 manifest 版本 ${versionName}(${versionCode}) 不一致`,
40
+ }
41
+ }
42
+
43
+ /**
44
+ * 版本不一致时给出可执行的修复方向。
45
+ * @param {string} resourcesDir
46
+ * @returns {string}
47
+ */
48
+ function mismatchHint(resourcesDir) {
49
+ return [
50
+ '前端资源是旧版本,继续打包会得到「新版本号 + 旧资源」的 APK/wgt。',
51
+ `要么重新构建:pnpm build:app-android(产物写入 ${resourcesDir})`,
52
+ '要么确认 dist 已是最新后再用 --skip-web;确实要跳过校验加 --skip-resource-check。',
53
+ ].join('\n')
54
+ }
55
+
56
+ /**
57
+ * 读取 <resourcesDir>/manifest.json 并断言版本与项目 manifest 一致。
58
+ * @param {Object} options
59
+ * @param {string} options.resourcesDir
60
+ * @param {{ versionName: string, versionCode: number }} options.expected
61
+ * @param {boolean} [options.skip]
62
+ * @param {import('./logger.js').Logger} options.logger
63
+ * @returns {Promise<ResourceVersion & { skipped: boolean }>}
64
+ */
65
+ export async function assertResourceVersion(options) {
66
+ const manifestFile = path.join(options.resourcesDir, 'manifest.json')
67
+ let manifest
68
+ try {
69
+ manifest = await readJson(manifestFile)
70
+ } catch (error) {
71
+ throw new PackError(`无法读取前端产物 manifest:${manifestFile}`, EXIT.WEB_BUILD, {
72
+ hint: '确认前端产物目录完整,或去掉 --skip-web 重新构建',
73
+ cause: error,
74
+ })
75
+ }
76
+
77
+ const resource = readResourceVersion(manifest)
78
+ const result = compareResourceVersion(resource, options.expected)
79
+ if (result.ok) {
80
+ return { ...resource, skipped: false }
81
+ }
82
+ if (options.skip) {
83
+ options.logger.warn(`已跳过资源版本校验:${result.message}`)
84
+ return { ...resource, skipped: true }
85
+ }
86
+ throw new PackError(result.message, EXIT.WEB_BUILD, { hint: mismatchHint(options.resourcesDir) })
87
+ }
package/src/core/sdk.js CHANGED
@@ -241,8 +241,9 @@ export async function findSdkForVersion(config, version, extraDirs = []) {
241
241
 
242
242
  /**
243
243
  * 老版本 SDK 的 compileSdk/buildTools 与新版不同,优先沿用 SDK 自带的模板值。
244
+ * Kotlin 版本同样以模板声明为准;模板没写 kotlin-gradle-plugin 时返回空,由调用方兜底。
244
245
  * @param {string} templateRoot
245
- * @returns {Promise<{ compileSdkVersion?: number, buildToolsVersion?: string }>}
246
+ * @returns {Promise<{ compileSdkVersion?: number, buildToolsVersion?: string, kotlinVersion?: string }>}
246
247
  */
247
248
  export async function readTemplateDefaults(templateRoot) {
248
249
  const file = path.join(templateRoot, 'simpleDemo', 'build.gradle')
@@ -252,9 +253,13 @@ export async function readTemplateDefaults(templateRoot) {
252
253
  const text = await readText(file)
253
254
  const compileSdk = Number(/compileSdkVersion\s+(\d+)/.exec(text)?.[1])
254
255
  const buildTools = /buildToolsVersion\s+'([^']+)'/.exec(text)?.[1]
256
+ const rootFile = path.join(templateRoot, 'build.gradle')
257
+ const rootText = (await exists(rootFile)) ? await readText(rootFile) : ''
258
+ const kotlinVersion = /kotlin-gradle-plugin:([0-9][\w.-]*)/.exec(rootText)?.[1]
255
259
  return {
256
260
  compileSdkVersion: Number.isFinite(compileSdk) ? compileSdk : undefined,
257
261
  buildToolsVersion: buildTools || undefined,
262
+ kotlinVersion: kotlinVersion || undefined,
258
263
  }
259
264
  }
260
265
 
@@ -18,17 +18,21 @@ import { exists, readText } from './fsx.js'
18
18
  */
19
19
  export async function resolveSigning(project, options = {}) {
20
20
  const signing = project.signing ?? {}
21
- const keystore = String(signing.keystore ?? '')
22
- const keyAlias = String(signing.keyAlias ?? '')
21
+ const keystore = resolveProjectPath(project.projectDir, signing.keystore)
22
+ const properties = await readProperties(signing.keystoreProperties, project.projectDir)
23
+ // 别名优先取配置;允许只给 keystore.properties(团队自定义布局时更省配置)
24
+ const keyAlias = String(signing.keyAlias ?? '') || String(properties.keyAlias ?? '')
23
25
  if (!keystore || !(await exists(keystore))) {
24
- throw new PackError(`找不到签名证书:${keystore || '(未配置)'}`, EXIT.SIGN)
26
+ throw new PackError(`找不到签名证书:${keystore || '(未配置)'}`, EXIT.SIGN, {
27
+ hint: '检查 signing.keystore;相对路径按项目目录解析,也可以写绝对路径',
28
+ })
25
29
  }
26
30
  if (!keyAlias) {
27
- throw new PackError('未配置签名别名 keyAlias', EXIT.SIGN)
31
+ throw new PackError('未配置签名别名 keyAlias', EXIT.SIGN, {
32
+ hint: '在配置 signing.keyAlias 填写,或写进 keystoreProperties 的 keyAlias',
33
+ })
28
34
  }
29
35
 
30
- const properties = await readProperties(signing.keystoreProperties, project.projectDir)
31
-
32
36
  const storePassword =
33
37
  options.storePassword ??
34
38
  envValue(signing.storePasswordEnv) ??
@@ -49,6 +53,20 @@ export async function resolveSigning(project, options = {}) {
49
53
  return { keystore, keyAlias, storePassword, keyPassword }
50
54
  }
51
55
 
56
+ /**
57
+ * 配置里的相对路径统一相对项目目录解析,避免从别的目录执行时找不到证书。
58
+ * @param {string | undefined} projectDir
59
+ * @param {unknown} value
60
+ * @returns {string}
61
+ */
62
+ function resolveProjectPath(projectDir, value) {
63
+ const text = String(value ?? '').trim()
64
+ if (!text) {
65
+ return ''
66
+ }
67
+ return path.isAbsolute(text) ? text : path.join(String(projectDir ?? ''), text)
68
+ }
69
+
52
70
  /**
53
71
  * @param {string | undefined} name
54
72
  */
@@ -0,0 +1,81 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { rm, stat } from 'node:fs/promises'
3
+ import path from 'node:path'
4
+ import { exists, readJson, writeJson } from './fsx.js'
5
+
6
+ export const TEMPLATE_STATE_FILE = '.uni-pack-template.json'
7
+
8
+ const FINGERPRINT_FILES = [
9
+ 'build.gradle',
10
+ 'settings.gradle',
11
+ 'gradle/wrapper/gradle-wrapper.properties',
12
+ 'simpleDemo/build.gradle',
13
+ 'simpleDemo/src/main/AndroidManifest.xml',
14
+ ]
15
+
16
+ /**
17
+ * SDK 换版本、模板被手工改过(mtime/大小变化)时都要重新复制模板。
18
+ * @param {{ root: string, templateRoot: string, version?: string | null }} sdk
19
+ * @returns {Promise<{ fingerprint: string, files: Array<{ file: string, size: number, mtimeMs: number }> }>}
20
+ */
21
+ export async function templateFingerprint(sdk) {
22
+ /** @type {Array<{ file: string, size: number, mtimeMs: number }>} */
23
+ const files = []
24
+ for (const relative of FINGERPRINT_FILES) {
25
+ const file = path.join(sdk.templateRoot, relative)
26
+ try {
27
+ const info = await stat(file)
28
+ files.push({ file: relative, size: info.size, mtimeMs: Math.round(info.mtimeMs) })
29
+ } catch {
30
+ files.push({ file: relative, size: -1, mtimeMs: -1 })
31
+ }
32
+ }
33
+ const payload = JSON.stringify({
34
+ root: sdk.root,
35
+ templateRoot: sdk.templateRoot,
36
+ version: String(sdk.version ?? ''),
37
+ files,
38
+ })
39
+ return { fingerprint: createHash('sha256').update(payload).digest('hex'), files }
40
+ }
41
+
42
+ /**
43
+ * @param {string} gradleRoot
44
+ * @returns {Promise<{ fingerprint?: string, templateRoot?: string, version?: string, builtAt?: string } | null>}
45
+ */
46
+ export async function readTemplateState(gradleRoot) {
47
+ return readJson(path.join(gradleRoot, TEMPLATE_STATE_FILE)).catch(() => null)
48
+ }
49
+
50
+ /**
51
+ * @param {string} gradleRoot
52
+ * @param {Record<string, unknown>} state
53
+ */
54
+ export async function writeTemplateState(gradleRoot, state) {
55
+ await writeJson(path.join(gradleRoot, TEMPLATE_STATE_FILE), state)
56
+ }
57
+
58
+ /**
59
+ * 增量构建前清掉会残留的输入:当前 appid 的 www、SDK 模板 assets 数据、上次的 AAR/so。
60
+ * build/、.gradle/、simpleDemo/build/ 保留,Gradle 才能命中 UP-TO-DATE。
61
+ * @param {{ gradleRoot: string, appid: string }} options
62
+ * @returns {Promise<string[]>} 已清理的路径
63
+ */
64
+ export async function cleanIncrementalInputs(options) {
65
+ const relative = [
66
+ path.join('simpleDemo', 'src', 'main', 'assets', 'apps', options.appid),
67
+ path.join('simpleDemo', 'src', 'main', 'assets', 'data'),
68
+ path.join('simpleDemo', 'src', 'main', 'assets', 'dcloud_uniplugins.json'),
69
+ path.join('simpleDemo', 'libs'),
70
+ path.join('simpleDemo', 'src', 'main', 'jniLibs'),
71
+ ]
72
+ const removed = []
73
+ for (const item of relative) {
74
+ const target = path.join(options.gradleRoot, item)
75
+ if (await exists(target)) {
76
+ await rm(target, { recursive: true, force: true })
77
+ removed.push(item)
78
+ }
79
+ }
80
+ return removed
81
+ }
@@ -1,15 +1,16 @@
1
1
  import path from 'node:path'
2
2
  import { PackError, EXIT } from './errors.js'
3
- import { exists, readJson } from './fsx.js'
3
+ import { ensureDir, exists, readJson } from './fsx.js'
4
4
  import { runHbuilderxBuild } from './hbuilderx.js'
5
5
  import { run } from './process.js'
6
+ import { buildTempEnv } from './workdir.js'
6
7
 
7
8
  const REQUIRED = ['manifest.json', 'app-service.js', 'app-config.js', '__uniappview.html']
8
9
 
9
10
  /**
10
11
  * @param {any} project
11
12
  * @param {import('./logger.js').Logger} logger
12
- * @param {{ hbuilderx?: { root: string, version: string }, vueVersion?: 2 | 3 }} [context]
13
+ * @param {{ hbuilderx?: { root: string, version: string }, vueVersion?: 2 | 3, tempDir?: string }} [context]
13
14
  * @returns {Promise<{ dir: string, manifest: any }>}
14
15
  */
15
16
  export async function runWebBuild(project, logger, context = {}) {
@@ -18,6 +19,11 @@ export async function runWebBuild(project, logger, context = {}) {
18
19
  project.projectDir,
19
20
  String(config.outputDir ?? (project.type === 'hbuilderx' ? 'unpackage/dist/build/app-plus' : 'dist/build/app')),
20
21
  )
22
+ const tempDir = context.tempDir ? String(context.tempDir) : ''
23
+ if (tempDir) {
24
+ // 先建好目录,再把它作为子进程的 TEMP/TMP,避免系统 TEMP 的 ACL 问题
25
+ await ensureDir(tempDir)
26
+ }
21
27
 
22
28
  if (project.type === 'hbuilderx') {
23
29
  const hbuilderx = context.hbuilderx
@@ -32,6 +38,7 @@ export async function runWebBuild(project, logger, context = {}) {
32
38
  inputDir: String(project.inputDir ?? project.projectDir),
33
39
  outputDir: dir,
34
40
  vueVersion: context.vueVersion ?? 3,
41
+ tempDir: tempDir || undefined,
35
42
  logger,
36
43
  })
37
44
  } else {
@@ -42,6 +49,7 @@ export async function runWebBuild(project, logger, context = {}) {
42
49
  try {
43
50
  await run(command, args, {
44
51
  cwd: project.projectDir,
52
+ env: tempDir ? buildTempEnv(tempDir) : undefined,
45
53
  onLine: (line) => logger.detail(line),
46
54
  })
47
55
  } catch (error) {
package/src/core/wgt.js CHANGED
@@ -1,18 +1,36 @@
1
- import { createHash } from 'node:crypto'
2
- import { createReadStream, createWriteStream } from 'node:fs'
3
- import { readdir, readFile } from 'node:fs/promises'
4
1
  import path from 'node:path'
2
+ import { createWriteStream } from 'node:fs'
3
+ import { readdir, stat } from 'node:fs/promises'
5
4
  import { pipeline } from 'node:stream/promises'
6
5
  import yazl from 'yazl'
7
6
  import { PackError, EXIT } from './errors.js'
8
- import { ensureDir, exists, readJson } from './fsx.js'
7
+ import { ensureDir, exists, readJson, replaceHardLink, writeJson } from './fsx.js'
8
+ import { fileHash } from './hash.js'
9
9
 
10
10
  const REQUIRED = ['manifest.json', 'app-service.js', '__uniappview.html']
11
11
 
12
+ /**
13
+ * 产物基名:<appid>-<versionName>。版本名里可能有斜杠等字符,统一替换成下划线。
14
+ * @param {{ appid: string, versionName: string }} options
15
+ * @returns {string}
16
+ */
17
+ export function wgtBaseName(options) {
18
+ const appid = String(options.appid ?? '').trim()
19
+ const version = String(options.versionName ?? '')
20
+ .trim()
21
+ .replace(/[^\w.-]+/g, '_')
22
+ .replace(/^_+|_+$/g, '')
23
+ return version ? `${appid}-${version}` : appid
24
+ }
25
+
12
26
  /**
13
27
  * @param {Object} input
14
28
  * @param {string} input.resourcesDir
15
- * @param {string} input.outputFile
29
+ * @param {string} input.outputDir
30
+ * @param {string} input.appid
31
+ * @param {string} input.versionName
32
+ * @param {number} input.versionCode
33
+ * @returns {Promise<{ file: string, meta: string, latest: string, sha256: string, size: number, manifest: any }>}
16
34
  */
17
35
  export async function writeWgt(input) {
18
36
  const manifest = await readJson(path.join(input.resourcesDir, 'manifest.json'))
@@ -29,19 +47,36 @@ export async function writeWgt(input) {
29
47
  throw new PackError('wgt 的 manifest.json 缺少 id', EXIT.WGT)
30
48
  }
31
49
 
32
- await ensureDir(path.dirname(input.outputFile))
50
+ const baseName = wgtBaseName({ appid: input.appid, versionName: input.versionName })
51
+ const outputFile = path.join(input.outputDir, `${baseName}.wgt`)
52
+ const metaFile = path.join(input.outputDir, `${baseName}.json`)
53
+ const latest = path.join(input.outputDir, `${input.appid}.wgt`)
54
+
55
+ await ensureDir(input.outputDir)
33
56
  const zip = new yazl.ZipFile()
34
57
  await addDirectory(zip, input.resourcesDir, '')
35
58
  zip.end()
36
- await pipeline(zip.outputStream, createWriteStream(input.outputFile))
59
+ await pipeline(zip.outputStream, createWriteStream(outputFile))
37
60
 
38
- const buffer = await readFile(input.outputFile)
39
- const sha256 = createHash('sha256').update(buffer).digest('hex')
40
- if (buffer.length < 1024 * 1024) {
41
- throw new PackError(`wgt 体积异常(${buffer.length} 字节),检查资源目录是否完整`, EXIT.WGT)
61
+ const size = (await stat(outputFile)).size
62
+ if (size < 1024 * 1024) {
63
+ throw new PackError(`wgt 体积异常(${size} 字节),检查资源目录是否完整`, EXIT.WGT)
42
64
  }
65
+ const sha256 = await fileHash(outputFile)
66
+
67
+ await writeJson(metaFile, {
68
+ appid: input.appid,
69
+ versionName: input.versionName,
70
+ versionCode: input.versionCode,
71
+ file: path.basename(outputFile),
72
+ size,
73
+ sha256,
74
+ builtAt: new Date().toISOString(),
75
+ })
76
+ // 固定名保持旧路径可用:硬链到最新版本,零复制且不会被覆盖
77
+ await replaceHardLink(outputFile, latest)
43
78
 
44
- return { file: input.outputFile, sha256, size: buffer.length, manifest }
79
+ return { file: outputFile, meta: metaFile, latest, sha256, size, manifest }
45
80
  }
46
81
 
47
82
  /**
@@ -61,16 +96,3 @@ async function addDirectory(zip, dir, prefix) {
61
96
  }
62
97
  }
63
98
  }
64
-
65
- /**
66
- * @param {string} file
67
- */
68
- export function fileHash(file) {
69
- return new Promise((resolve, reject) => {
70
- const sha = createHash('sha256')
71
- createReadStream(file)
72
- .on('data', (chunk) => sha.update(chunk))
73
- .on('error', reject)
74
- .on('end', () => resolve(sha.digest('hex')))
75
- })
76
- }
@@ -0,0 +1,44 @@
1
+ import path from 'node:path'
2
+
3
+ /**
4
+ * 项目名可能是中文或带空格,工作目录用清洗后的名字,和旧版本保持一致。
5
+ * @param {unknown} value
6
+ * @returns {string}
7
+ */
8
+ export function sanitizeWorkName(value) {
9
+ return String(value ?? '').replace(/[^\w.-]+/g, '-').replace(/^-+|-+$/g, '') || 'project'
10
+ }
11
+
12
+ /**
13
+ * 每个项目一个稳定的构建工作目录:<workDir>/<项目名>。
14
+ * @param {any} config
15
+ * @param {any} project
16
+ * @returns {string}
17
+ */
18
+ export function resolveWorkRoot(config, project) {
19
+ return path.join(String(config?.workDir ?? ''), sanitizeWorkName(project?.name ?? 'project'))
20
+ }
21
+
22
+ /**
23
+ * 前端构建(pnpm / HBuilderX 编译器)的临时目录。
24
+ * 默认 <workRoot>/tmp:某些机器的系统 TEMP 有 ACL 问题,esbuild 删除临时文件会被拒绝。
25
+ * 用户显式设置 UNI_PACK_TEMP 时不覆盖。
26
+ * @param {string} workRoot
27
+ * @param {Record<string, string | undefined>} [env]
28
+ * @returns {{ tempDir: string, explicit: boolean }}
29
+ */
30
+ export function resolveBuildTempDir(workRoot, env = process.env) {
31
+ const explicit = String(env.UNI_PACK_TEMP ?? '').trim()
32
+ if (explicit) {
33
+ return { tempDir: explicit, explicit: true }
34
+ }
35
+ return { tempDir: path.join(workRoot, 'tmp'), explicit: false }
36
+ }
37
+
38
+ /**
39
+ * @param {string} tempDir
40
+ * @returns {{ TEMP: string, TMP: string }}
41
+ */
42
+ export function buildTempEnv(tempDir) {
43
+ return { TEMP: tempDir, TMP: tempDir }
44
+ }