uniapp-android-cli 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +382 -2
- package/bin/uni-pack.js +7 -0
- package/package.json +66 -4
- package/src/cli.js +242 -0
- package/src/commands/build.js +46 -0
- package/src/commands/debug.js +183 -0
- package/src/commands/device.js +309 -0
- package/src/commands/devices.js +23 -0
- package/src/commands/doctor.js +170 -0
- package/src/commands/init.js +488 -0
- package/src/commands/projects.js +31 -0
- package/src/commands/wgt.js +90 -0
- package/src/core/adb.js +292 -0
- package/src/core/build.js +438 -0
- package/src/core/config.js +208 -0
- package/src/core/debugPreset.js +56 -0
- package/src/core/devicePairing.js +153 -0
- package/src/core/errors.js +36 -0
- package/src/core/fsx.js +183 -0
- package/src/core/gradle.js +221 -0
- package/src/core/gradleLog.js +188 -0
- package/src/core/hash.js +18 -0
- package/src/core/hbuilderx.js +260 -0
- package/src/core/hbuilderxCli.js +168 -0
- package/src/core/initConfig.js +214 -0
- package/src/core/initEnv.js +140 -0
- package/src/core/interactive.js +93 -0
- package/src/core/logger.js +82 -0
- package/src/core/output.js +181 -0
- package/src/core/patch/assets.js +154 -0
- package/src/core/patch/gradle.js +166 -0
- package/src/core/patch/manifest.js +81 -0
- package/src/core/patch/nativePlugins.js +137 -0
- package/src/core/patch/projectManifest.js +66 -0
- package/src/core/patch/template.js +75 -0
- package/src/core/patch/utsPlugins.js +425 -0
- package/src/core/process.js +120 -0
- package/src/core/project.js +263 -0
- package/src/core/qrcode.js +13 -0
- package/src/core/resourceVersion.js +87 -0
- package/src/core/sdk.js +403 -0
- package/src/core/signing.js +102 -0
- package/src/core/templateCache.js +81 -0
- package/src/core/version.js +128 -0
- package/src/core/webBuild.js +77 -0
- package/src/core/wgt.js +98 -0
- package/src/core/workdir.js +44 -0
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { appendFile, copyFile, readdir, rm, stat } from 'node:fs/promises'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { PackError, EXIT } from './errors.js'
|
|
4
|
+
import { ensureDir, replaceHardLink, writeJson } from './fsx.js'
|
|
5
|
+
import { fileHash } from './hash.js'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* @param {string} dir
|
|
9
|
+
* @param {'release' | 'debug'} mode
|
|
10
|
+
*/
|
|
11
|
+
export async function findApk(dir, mode) {
|
|
12
|
+
if (!dir) {
|
|
13
|
+
throw new PackError('未指定 Gradle 输出目录', EXIT.GRADLE)
|
|
14
|
+
}
|
|
15
|
+
const entries = await readdir(dir, { withFileTypes: true }).catch(() => [])
|
|
16
|
+
const candidates = entries.filter((entry) => entry.isFile() && entry.name.endsWith('.apk'))
|
|
17
|
+
const preferred =
|
|
18
|
+
candidates.find((entry) => entry.name === `simpleDemo-${mode}.apk`) ??
|
|
19
|
+
candidates.find((entry) => entry.name === `app-${mode}.apk`) ??
|
|
20
|
+
candidates.find((entry) => entry.name.includes(mode)) ??
|
|
21
|
+
candidates[0]
|
|
22
|
+
if (!preferred) {
|
|
23
|
+
throw new PackError(`Gradle 未产出 APK:${dir}`, EXIT.GRADLE)
|
|
24
|
+
}
|
|
25
|
+
return path.join(dir, preferred.name)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* @typedef {Object} PublishApkOptions
|
|
30
|
+
* @property {string} apk Gradle 产出的 APK
|
|
31
|
+
* @property {string} outputDir 项目 apk 目录
|
|
32
|
+
* @property {string} baseName <展示名>_<版本>_<版本号>
|
|
33
|
+
* @property {'release' | 'debug'} mode
|
|
34
|
+
* @property {string} workDir 构建工作目录,用于写 .uni-pack-build.json
|
|
35
|
+
* @property {Record<string, unknown>} [record]
|
|
36
|
+
* @property {import('./logger.js').Logger} [logger]
|
|
37
|
+
* @property {number} [prune] 只保留最近 n 个时间戳包(0 表示只留 latest)
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* 发布 APK:时间戳副本 + latest 硬链 + 同名清单 + builds.jsonl + 可选清理。
|
|
42
|
+
* @param {PublishApkOptions} options
|
|
43
|
+
*/
|
|
44
|
+
export async function publishApk(options) {
|
|
45
|
+
await ensureDir(options.outputDir)
|
|
46
|
+
const stamp = timestamp()
|
|
47
|
+
const fileName = `${options.baseName}_${options.mode}_${stamp}.apk`
|
|
48
|
+
const target = path.join(options.outputDir, fileName)
|
|
49
|
+
const latest = path.join(options.outputDir, `${options.baseName}_${options.mode}_latest.apk`)
|
|
50
|
+
|
|
51
|
+
await copyFile(options.apk, target)
|
|
52
|
+
|
|
53
|
+
let latestLinked = true
|
|
54
|
+
try {
|
|
55
|
+
await replaceHardLink(target, latest)
|
|
56
|
+
} catch (error) {
|
|
57
|
+
latestLinked = false
|
|
58
|
+
const detail = error instanceof Error ? error.message : String(error)
|
|
59
|
+
options.logger?.warn(`latest 硬链失败(${detail}),已回退为复制`)
|
|
60
|
+
await copyFile(target, latest)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const size = (await stat(target)).size
|
|
64
|
+
const sha256 = await fileHash(target)
|
|
65
|
+
const builtAt = new Date().toISOString()
|
|
66
|
+
const record = {
|
|
67
|
+
...(options.record ?? {}),
|
|
68
|
+
mode: options.mode,
|
|
69
|
+
apk: target,
|
|
70
|
+
latest,
|
|
71
|
+
sha256,
|
|
72
|
+
size,
|
|
73
|
+
builtAt,
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const recordFile = `${target}.json`
|
|
77
|
+
await writeJson(recordFile, record)
|
|
78
|
+
await appendFile(path.join(options.outputDir, 'builds.jsonl'), `${JSON.stringify(record)}\n`, 'utf8')
|
|
79
|
+
await writeJson(path.join(options.workDir, '.uni-pack-build.json'), record)
|
|
80
|
+
|
|
81
|
+
if (options.prune !== undefined) {
|
|
82
|
+
await pruneApks({ outputDir: options.outputDir, mode: options.mode, keep: options.prune, logger: options.logger })
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return { target, latest, sha256, size, recordFile, latestLinked }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* 按时间保留最近 n 个时间戳包(同目录、同一 mode),latest 与 builds.jsonl 不动。
|
|
90
|
+
* @param {Object} options
|
|
91
|
+
* @param {string} options.outputDir
|
|
92
|
+
* @param {'release' | 'debug'} [options.mode] 只清理该 mode;不传时两种都清
|
|
93
|
+
* @param {number} options.keep
|
|
94
|
+
* @param {import('./logger.js').Logger} [options.logger]
|
|
95
|
+
* @returns {Promise<string[]>} 删除的文件名
|
|
96
|
+
*/
|
|
97
|
+
export async function pruneApks(options) {
|
|
98
|
+
const keep = Number(options.keep)
|
|
99
|
+
if (!Number.isInteger(keep) || keep < 0) {
|
|
100
|
+
throw new PackError(`--prune 需要一个非负整数,收到:${String(options.keep)}`, EXIT.CONFIG, {
|
|
101
|
+
hint: '例如 --prune 5 表示每个 mode 只保留最近 5 个时间戳 APK,latest 永远保留',
|
|
102
|
+
})
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const entries = await readdir(options.outputDir, { withFileTypes: true }).catch(() => [])
|
|
106
|
+
const modePattern = options.mode ? escapeRegExp(options.mode) : 'release|debug'
|
|
107
|
+
const pattern = new RegExp(`^(.+)_(${modePattern})_(\\d{8}_\\d{4})\\.apk$`)
|
|
108
|
+
/** @type {Map<'release' | 'debug', Array<{ name: string, stamp: string }>>} */
|
|
109
|
+
const groups = new Map()
|
|
110
|
+
for (const entry of entries) {
|
|
111
|
+
if (!entry.isFile()) {
|
|
112
|
+
continue
|
|
113
|
+
}
|
|
114
|
+
const match = pattern.exec(entry.name)
|
|
115
|
+
if (!match) {
|
|
116
|
+
continue
|
|
117
|
+
}
|
|
118
|
+
const mode = /** @type {'release' | 'debug'} */ (match[2])
|
|
119
|
+
const list = groups.get(mode) ?? []
|
|
120
|
+
list.push({ name: entry.name, stamp: match[3] })
|
|
121
|
+
groups.set(mode, list)
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const deleted = []
|
|
125
|
+
for (const list of groups.values()) {
|
|
126
|
+
list.sort((left, right) => right.stamp.localeCompare(left.stamp))
|
|
127
|
+
for (const item of list.slice(keep)) {
|
|
128
|
+
const apk = path.join(options.outputDir, item.name)
|
|
129
|
+
await rm(apk, { force: true })
|
|
130
|
+
await rm(`${apk}.json`, { force: true })
|
|
131
|
+
deleted.push(item.name)
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (deleted.length > 0) {
|
|
136
|
+
options.logger?.info(`已清理 ${deleted.length} 个旧 APK(保留最近 ${keep} 个时间戳包)`)
|
|
137
|
+
}
|
|
138
|
+
return deleted
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* @param {string} value
|
|
143
|
+
*/
|
|
144
|
+
function escapeRegExp(value) {
|
|
145
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function timestamp() {
|
|
149
|
+
const now = new Date()
|
|
150
|
+
const pad = (value) => String(value).padStart(2, '0')
|
|
151
|
+
return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}_${pad(now.getHours())}${pad(now.getMinutes())}`
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* APK 前缀:显式 outputPrefix > manifest 展示名 > 项目标识/appid。
|
|
156
|
+
* 中文展示名清洗后会变成空串,不能直接退化成 "app",否则多项目会互相撞名。
|
|
157
|
+
* @param {{ outputPrefix?: string, name?: string }} project
|
|
158
|
+
* @param {{ name?: string, appid?: string }} resolved
|
|
159
|
+
* @returns {string}
|
|
160
|
+
*/
|
|
161
|
+
export function resolveApkPrefix(project, resolved) {
|
|
162
|
+
const explicit = String(project.outputPrefix ?? '').trim()
|
|
163
|
+
if (explicit) {
|
|
164
|
+
return explicit
|
|
165
|
+
}
|
|
166
|
+
const display = String(resolved.name ?? '').trim()
|
|
167
|
+
if (display && display.replace(/[^\w.-]+/g, '').length > 0) {
|
|
168
|
+
return display
|
|
169
|
+
}
|
|
170
|
+
return String(project.name ?? resolved.appid ?? 'app')
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* @param {string} projectName
|
|
175
|
+
* @param {string} versionName
|
|
176
|
+
* @param {number} versionCode
|
|
177
|
+
*/
|
|
178
|
+
export function apkBaseName(projectName, versionName, versionCode) {
|
|
179
|
+
const safe = projectName.replace(/[^\w.-]+/g, '-').replace(/^-+|-+$/g, '') || 'app'
|
|
180
|
+
return `${safe}_${versionName}_${versionCode}`
|
|
181
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import path from 'node:path'
|
|
2
|
+
import { PackError, EXIT } from '../errors.js'
|
|
3
|
+
import { copyTree, ensureDir, exists, readText, writeText } from '../fsx.js'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* @typedef {Object} AssetsContext
|
|
7
|
+
* @property {string} moduleDir simpleDemo 目录
|
|
8
|
+
* @property {string} dataDir SDK assets/data
|
|
9
|
+
* @property {string} resourcesDir 构建产物 dist/build/app 或 unpackage/dist/build/app-plus
|
|
10
|
+
* @property {string} appid
|
|
11
|
+
* @property {string} appName
|
|
12
|
+
* @property {string} versionName
|
|
13
|
+
* @property {boolean} debug
|
|
14
|
+
* @property {string} projectDir
|
|
15
|
+
* @property {any} [manifest] 项目 manifest,用于读取图标与启动图路径
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @param {AssetsContext} context
|
|
20
|
+
*/
|
|
21
|
+
export async function applyAssets(context) {
|
|
22
|
+
const mainDir = path.join(context.moduleDir, 'src/main')
|
|
23
|
+
const appsDir = path.join(mainDir, 'assets/apps')
|
|
24
|
+
const assetsData = path.join(mainDir, 'assets/data')
|
|
25
|
+
|
|
26
|
+
await copyTree(context.dataDir, assetsData)
|
|
27
|
+
|
|
28
|
+
const wwwDir = path.join(appsDir, context.appid, 'www')
|
|
29
|
+
// UTS 插件的 utssdk 是编译期资源,HBuilderX 的产物不会打进 www
|
|
30
|
+
await copyTree(context.resourcesDir, wwwDir, (relative) => /^uni_modules\/[^/]+\/utssdk(\/|$)/.test(relative))
|
|
31
|
+
await writeControlFile(assetsData, context)
|
|
32
|
+
await patchStrings(mainDir, context.appName)
|
|
33
|
+
await applyIcons(mainDir, context.projectDir, context.manifest)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* @param {string} assetsData
|
|
38
|
+
* @param {AssetsContext} context
|
|
39
|
+
*/
|
|
40
|
+
async function writeControlFile(assetsData, context) {
|
|
41
|
+
const root = context.debug ? '<hbuilder debug="true">' : '<hbuilder>'
|
|
42
|
+
const xml = `${root}\n<apps>\n <app appid="${context.appid}" appver="${context.versionName}"/>\n</apps>\n</hbuilder>\n`
|
|
43
|
+
await writeText(path.join(assetsData, 'dcloud_control.xml'), xml)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* @param {string} mainDir
|
|
48
|
+
* @param {string} appName
|
|
49
|
+
*/
|
|
50
|
+
async function patchStrings(mainDir, appName) {
|
|
51
|
+
const file = path.join(mainDir, 'res/values/strings.xml')
|
|
52
|
+
const text = await readText(file)
|
|
53
|
+
if (!text.includes('name="app_name"')) {
|
|
54
|
+
throw new PackError('模板 strings.xml 缺少 app_name', EXIT.PREFLIGHT)
|
|
55
|
+
}
|
|
56
|
+
await writeText(file, text.replace(/(name="app_name">)[^<]*(<)/, `$1${escapeXml(appName)}$2`))
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const ICON_DENSITIES = ['hdpi', 'xhdpi', 'xxhdpi', 'xxxhdpi']
|
|
60
|
+
const CLIENT_ICON_FILES = { hdpi: '72x72.png', xhdpi: '96x96.png', xxhdpi: '144x144.png', xxxhdpi: '192x192.png' }
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 图标与启动图优先用 manifest 声明的路径(CLI 与 HBuilderX 都适用),
|
|
64
|
+
* 其次回退到两种项目各自的默认目录。
|
|
65
|
+
* @param {string} mainDir
|
|
66
|
+
* @param {string} projectDir
|
|
67
|
+
* @param {any} [manifest]
|
|
68
|
+
*/
|
|
69
|
+
async function applyIcons(mainDir, projectDir, manifest) {
|
|
70
|
+
const distribute = manifest?.['app-plus']?.distribute ?? {}
|
|
71
|
+
const manifestIcons = distribute.icons?.android ?? {}
|
|
72
|
+
const manifestSplash = distribute.splashscreen?.android ?? {}
|
|
73
|
+
|
|
74
|
+
for (const density of ICON_DENSITIES) {
|
|
75
|
+
const source = await firstExisting([
|
|
76
|
+
resolveMaybeRelative(projectDir, manifestIcons[density]),
|
|
77
|
+
path.join(projectDir, 'src/static/app/icons', CLIENT_ICON_FILES[density]),
|
|
78
|
+
path.join(projectDir, 'unpackage/res/icons', CLIENT_ICON_FILES[density]),
|
|
79
|
+
])
|
|
80
|
+
if (source) {
|
|
81
|
+
await copyFile(source, path.join(mainDir, `res/drawable-${density}/icon.png`))
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const splash = await firstExisting([
|
|
85
|
+
resolveMaybeRelative(projectDir, manifestSplash[density]),
|
|
86
|
+
path.join(projectDir, 'src/static/app/splash', `splash-${density}.png`),
|
|
87
|
+
path.join(projectDir, 'unpackage/res/splash/splash.png'),
|
|
88
|
+
path.join(projectDir, 'unpackage/res/splash', `splash-${density}.png`),
|
|
89
|
+
])
|
|
90
|
+
if (splash) {
|
|
91
|
+
await copyFile(splash, path.join(mainDir, `res/drawable-${density}/splash.png`))
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const fallbackIcon = await firstExisting([
|
|
96
|
+
resolveMaybeRelative(projectDir, manifestIcons.xxxhdpi),
|
|
97
|
+
path.join(projectDir, 'src/static/app/icons/192x192.png'),
|
|
98
|
+
path.join(projectDir, 'unpackage/res/icons/192x192.png'),
|
|
99
|
+
])
|
|
100
|
+
if (fallbackIcon) {
|
|
101
|
+
await copyFile(fallbackIcon, path.join(mainDir, 'res/drawable/icon.png'))
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const fallbackSplash = await firstExisting([
|
|
105
|
+
resolveMaybeRelative(projectDir, manifestSplash.xxhdpi),
|
|
106
|
+
path.join(projectDir, 'src/static/app/splash/splash-xxhdpi.png'),
|
|
107
|
+
path.join(projectDir, 'unpackage/res/splash/splash.png'),
|
|
108
|
+
])
|
|
109
|
+
if (fallbackSplash) {
|
|
110
|
+
await copyFile(fallbackSplash, path.join(mainDir, 'res/drawable/splash.png'))
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* @param {string} projectDir
|
|
116
|
+
* @param {unknown} value
|
|
117
|
+
* @returns {string}
|
|
118
|
+
*/
|
|
119
|
+
function resolveMaybeRelative(projectDir, value) {
|
|
120
|
+
if (typeof value !== 'string' || !value.trim()) {
|
|
121
|
+
return ''
|
|
122
|
+
}
|
|
123
|
+
return path.isAbsolute(value) ? value : path.join(projectDir, value)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* @param {string[]} candidates
|
|
128
|
+
* @returns {Promise<string>}
|
|
129
|
+
*/
|
|
130
|
+
async function firstExisting(candidates) {
|
|
131
|
+
for (const candidate of candidates) {
|
|
132
|
+
if (candidate && (await exists(candidate))) {
|
|
133
|
+
return candidate
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return ''
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* @param {string} from
|
|
141
|
+
* @param {string} to
|
|
142
|
+
*/
|
|
143
|
+
async function copyFile(from, to) {
|
|
144
|
+
await ensureDir(path.dirname(to))
|
|
145
|
+
const { copyFile: copy } = await import('node:fs/promises')
|
|
146
|
+
await copy(from, to)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* @param {string} value
|
|
151
|
+
*/
|
|
152
|
+
function escapeXml(value) {
|
|
153
|
+
return value.replace(/[<>&"]/g, (char) => ({ '<': '<', '>': '>', '&': '&', '"': '"' })[char] ?? char)
|
|
154
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import path from 'node:path'
|
|
2
|
+
import { PackError, EXIT } from '../errors.js'
|
|
3
|
+
import { readText, writeText } from '../fsx.js'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* 精确替换:匹配 0 次或多次都视为错误,避免模板变化后静默失效。
|
|
7
|
+
* @param {string} text
|
|
8
|
+
* @param {RegExp} pattern
|
|
9
|
+
* @param {string | ((...args: string[]) => string)} replacement
|
|
10
|
+
* @param {string} label
|
|
11
|
+
*/
|
|
12
|
+
export function replaceExactlyOnce(text, pattern, replacement, label) {
|
|
13
|
+
const flags = pattern.flags.includes('g') ? pattern.flags : `${pattern.flags}g`
|
|
14
|
+
const global = new RegExp(pattern.source, flags)
|
|
15
|
+
const matches = [...text.matchAll(global)]
|
|
16
|
+
if (matches.length !== 1) {
|
|
17
|
+
throw new PackError(`模板替换失败(${label}):期望命中 1 次,实际 ${matches.length} 次`, EXIT.GRADLE)
|
|
18
|
+
}
|
|
19
|
+
return text.replace(global, /** @type {any} */ (typeof replacement === 'string' ? replacement : replacement))
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const CORE_DEPENDENCIES = [
|
|
23
|
+
{ key: 'com.squareup.okhttp3:okhttp', line: 'implementation "com.squareup.okhttp3:okhttp:3.12.12"' },
|
|
24
|
+
{ key: 'com.facebook.fresco:middleware', line: 'implementation "com.facebook.fresco:middleware:3.4.0"' },
|
|
25
|
+
{ key: 'com.facebook.fresco:webpsupport', line: 'implementation "com.facebook.fresco:webpsupport:3.4.0"' },
|
|
26
|
+
{ key: 'com.facebook.fresco:animated-webp', line: 'implementation "com.facebook.fresco:animated-webp:3.4.0"' },
|
|
27
|
+
{
|
|
28
|
+
key: 'androidx.legacy:legacy-support-v4',
|
|
29
|
+
line: 'implementation "androidx.legacy:legacy-support-v4:1.0.0"',
|
|
30
|
+
},
|
|
31
|
+
{ key: 'net.lingala.zip4j:zip4j', line: 'implementation "net.lingala.zip4j:zip4j:2.11.5"' },
|
|
32
|
+
{
|
|
33
|
+
key: 'com.github.bumptech.glide:compiler',
|
|
34
|
+
line: 'annotationProcessor "com.github.bumptech.glide:compiler:4.9.0"',
|
|
35
|
+
},
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 部分 SDK 模板的核心依赖放在 SMARTPACK 标记块里,模板被清理或换成干净版本时可能缺失。
|
|
40
|
+
* zip4j 缺失会让 RuntimeFeatureImpl 在后台线程抛 NoClassDefFoundError 并闪退。
|
|
41
|
+
* @param {string} text
|
|
42
|
+
* @returns {string}
|
|
43
|
+
*/
|
|
44
|
+
export function ensureCoreDependencies(text) {
|
|
45
|
+
const missing = CORE_DEPENDENCIES.filter((item) => !text.includes(item.key))
|
|
46
|
+
if (missing.length === 0) {
|
|
47
|
+
return text
|
|
48
|
+
}
|
|
49
|
+
const snippet = missing.map((item) => ` ${item.line}`).join('\n')
|
|
50
|
+
const match = /dependencies\s*\{/.exec(text)
|
|
51
|
+
if (!match) {
|
|
52
|
+
throw new PackError('模板 build.gradle 缺少 dependencies 块', EXIT.GRADLE)
|
|
53
|
+
}
|
|
54
|
+
const open = match.index + match[0].length
|
|
55
|
+
return `${text.slice(0, open)}\n${snippet}${text.slice(open)}`
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @typedef {Object} GradlePatchContext
|
|
60
|
+
* @property {string} packageName
|
|
61
|
+
* @property {string} versionName
|
|
62
|
+
* @property {number} versionCode
|
|
63
|
+
* @property {number} minSdkVersion
|
|
64
|
+
* @property {number} targetSdkVersion
|
|
65
|
+
* @property {number} compileSdkVersion
|
|
66
|
+
* @property {string} buildToolsVersion
|
|
67
|
+
* @property {string[]} abiFilters
|
|
68
|
+
* @property {{ keyAlias: string, keyPassword: string, storePassword: string }} signing
|
|
69
|
+
*/
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* @param {string} file
|
|
73
|
+
* @param {GradlePatchContext} context
|
|
74
|
+
*/
|
|
75
|
+
export async function patchAppGradle(file, context) {
|
|
76
|
+
let text = await readText(file)
|
|
77
|
+
|
|
78
|
+
text = replaceExactlyOnce(text, /compileSdkVersion\s+\d+/, `compileSdkVersion ${context.compileSdkVersion}`, 'compileSdkVersion')
|
|
79
|
+
text = replaceExactlyOnce(
|
|
80
|
+
text,
|
|
81
|
+
/buildToolsVersion\s+'[^']*'/,
|
|
82
|
+
`buildToolsVersion '${context.buildToolsVersion}'`,
|
|
83
|
+
'buildToolsVersion',
|
|
84
|
+
)
|
|
85
|
+
text = replaceExactlyOnce(text, /namespace\s+'[^']*'/, `namespace '${context.packageName}'`, 'namespace')
|
|
86
|
+
text = replaceExactlyOnce(
|
|
87
|
+
text,
|
|
88
|
+
/applicationId\s+"[^"]*"/,
|
|
89
|
+
`applicationId "${context.packageName}"`,
|
|
90
|
+
'applicationId',
|
|
91
|
+
)
|
|
92
|
+
text = replaceExactlyOnce(text, /minSdkVersion\s+\d+/, `minSdkVersion ${context.minSdkVersion}`, 'minSdkVersion')
|
|
93
|
+
text = replaceExactlyOnce(
|
|
94
|
+
text,
|
|
95
|
+
/targetSdkVersion\s+\d+/,
|
|
96
|
+
`targetSdkVersion ${context.targetSdkVersion}`,
|
|
97
|
+
'targetSdkVersion',
|
|
98
|
+
)
|
|
99
|
+
text = replaceExactlyOnce(text, /versionCode\s+\d+/, `versionCode ${context.versionCode}`, 'versionCode')
|
|
100
|
+
text = replaceExactlyOnce(text, /versionName\s+"[^"]*"/, `versionName "${context.versionName}"`, 'versionName')
|
|
101
|
+
|
|
102
|
+
const abi = context.abiFilters.map((item) => `'${item}'`).join(', ')
|
|
103
|
+
const ndkPattern = /ndk\s*\{\s*abiFilters[^}]*\}/
|
|
104
|
+
if (ndkPattern.test(text)) {
|
|
105
|
+
text = replaceExactlyOnce(text, ndkPattern, `ndk {\n abiFilters ${abi}\n }`, 'abiFilters')
|
|
106
|
+
} else {
|
|
107
|
+
text = replaceExactlyOnce(
|
|
108
|
+
text,
|
|
109
|
+
/multiDexEnabled\s+true/,
|
|
110
|
+
`multiDexEnabled true\n ndk {\n abiFilters ${abi}\n }`,
|
|
111
|
+
'abiFilters(insert)',
|
|
112
|
+
)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// 密码不落盘:只写环境变量名,由 runGradle 在子进程 env 里注入
|
|
116
|
+
const signingBlock = [
|
|
117
|
+
'signingConfigs {',
|
|
118
|
+
' config {',
|
|
119
|
+
` keyAlias '${context.signing.keyAlias}'`,
|
|
120
|
+
" keyPassword System.getenv('UNI_PACK_KEY_PASS')",
|
|
121
|
+
" storeFile file('aw-pack.jks')",
|
|
122
|
+
" storePassword System.getenv('UNI_PACK_STORE_PASS')",
|
|
123
|
+
' v1SigningEnabled true',
|
|
124
|
+
' v2SigningEnabled true',
|
|
125
|
+
' }',
|
|
126
|
+
' }',
|
|
127
|
+
].join('\n')
|
|
128
|
+
text = replaceExactlyOnce(text, /signingConfigs\s*\{[\s\S]*?\n {4}\}/, signingBlock, 'signingConfigs')
|
|
129
|
+
|
|
130
|
+
// targetSdk 30 是电视端的既定配置,关掉对应的 lint 阻断
|
|
131
|
+
if (!text.includes('ExpiredTargetSdkVersion')) {
|
|
132
|
+
text = replaceExactlyOnce(
|
|
133
|
+
text,
|
|
134
|
+
/buildTypes\s*\{/,
|
|
135
|
+
"lint {\n disable 'ExpiredTargetSdkVersion'\n }\n buildTypes {",
|
|
136
|
+
'lint',
|
|
137
|
+
)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
text = ensureCoreDependencies(text)
|
|
141
|
+
await writeText(file, text)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* @param {string} file
|
|
146
|
+
* @param {string} androidSdkDir
|
|
147
|
+
*/
|
|
148
|
+
export async function patchRootGradle(file, androidSdkDir) {
|
|
149
|
+
let text = await readText(file)
|
|
150
|
+
if (!text.includes('maven { url \'https://jitpack.io\' }')) {
|
|
151
|
+
text = text.replace(
|
|
152
|
+
/allprojects\s*\{[\s\S]*?repositories\s*\{/,
|
|
153
|
+
(match) => `${match}\n maven { url 'https://jitpack.io' }`,
|
|
154
|
+
)
|
|
155
|
+
if (!text.includes('jitpack.io')) {
|
|
156
|
+
throw new PackError('模板根 build.gradle 结构异常,无法注入 jitpack 仓库', EXIT.GRADLE, {
|
|
157
|
+
hint: '换一份干净的离线 SDK 再试',
|
|
158
|
+
})
|
|
159
|
+
}
|
|
160
|
+
await writeText(file, text)
|
|
161
|
+
}
|
|
162
|
+
await writeText(
|
|
163
|
+
path.join(path.dirname(file), 'local.properties'),
|
|
164
|
+
`sdk.dir=${androidSdkDir.replace(/\\/g, '/')}\n`,
|
|
165
|
+
)
|
|
166
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { PackError, EXIT } from '../errors.js'
|
|
2
|
+
import { readText, writeText } from '../fsx.js'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @typedef {Object} ManifestPatchContext
|
|
6
|
+
* @property {string} packageName
|
|
7
|
+
* @property {string} appKey
|
|
8
|
+
* @property {string[]} permissions
|
|
9
|
+
* @property {{ name: string, required: string }[]} features
|
|
10
|
+
* @property {boolean} debug
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @param {string} file
|
|
15
|
+
* @param {ManifestPatchContext} context
|
|
16
|
+
*/
|
|
17
|
+
export async function patchAndroidManifest(file, context) {
|
|
18
|
+
let text = await readText(file)
|
|
19
|
+
|
|
20
|
+
if (!text.includes('package="')) {
|
|
21
|
+
throw new PackError('AndroidManifest.xml 缺少 package 属性', EXIT.PREFLIGHT)
|
|
22
|
+
}
|
|
23
|
+
text = text.replace(/package="[^"]*"/, `package="${context.packageName}"`)
|
|
24
|
+
|
|
25
|
+
text = removeBlocks(text, 'uses-permission')
|
|
26
|
+
text = removeBlocks(text, 'uses-feature')
|
|
27
|
+
|
|
28
|
+
const permissionLines = context.permissions
|
|
29
|
+
.filter((name, index, list) => list.indexOf(name) === index)
|
|
30
|
+
.map((name) => ` <uses-permission android:name="${name}"/>`)
|
|
31
|
+
.join('\n')
|
|
32
|
+
const featureLines = context.features
|
|
33
|
+
.map((feature) => ` <uses-feature android:name="${feature.name}" android:required="${feature.required}"/>`)
|
|
34
|
+
.join('\n')
|
|
35
|
+
|
|
36
|
+
const injected = [permissionLines, featureLines].filter(Boolean).join('\n')
|
|
37
|
+
text = text.replace(/<manifest([^>]*)>/, (match) => `${match}\n\n <!-- uni-pack 注入 -->\n${injected}\n`)
|
|
38
|
+
|
|
39
|
+
// 不硬编码 debuggable,交给 buildType 自动决定(否则 lint 的 HardcodedDebugMode 会直接失败)
|
|
40
|
+
text = text.replace(/\s*android:debuggable="[^"]*"/, '')
|
|
41
|
+
text = setApplicationAttr(text, 'android:usesCleartextTraffic', 'true')
|
|
42
|
+
|
|
43
|
+
if (text.includes('name="dcloud_appkey"')) {
|
|
44
|
+
text = text.replace(/(name="dcloud_appkey"\s*\n?\s*android:value=")[^"]*(")/, `$1${context.appKey}$2`)
|
|
45
|
+
} else {
|
|
46
|
+
text = text.replace(
|
|
47
|
+
/<\/application>/,
|
|
48
|
+
` <meta-data\n android:name="dcloud_appkey"\n android:value="${context.appKey}" />\n </application>`,
|
|
49
|
+
)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (!text.includes('LEANBACK_LAUNCHER')) {
|
|
53
|
+
text = text.replace(
|
|
54
|
+
/(<category android:name="android\.intent\.category\.LAUNCHER"\s*\/>)/,
|
|
55
|
+
'$1\n <category android:name="android.intent.category.LEANBACK_LAUNCHER" />',
|
|
56
|
+
)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
await writeText(file, text)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* @param {string} text
|
|
64
|
+
* @param {string} tagName
|
|
65
|
+
*/
|
|
66
|
+
function removeBlocks(text, tagName) {
|
|
67
|
+
return text.replace(new RegExp(`\\s*<${tagName}[^>]*/>`, 'g'), '')
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* @param {string} text
|
|
72
|
+
* @param {string} attr
|
|
73
|
+
* @param {string} value
|
|
74
|
+
*/
|
|
75
|
+
function setApplicationAttr(text, attr, value) {
|
|
76
|
+
const pattern = new RegExp(`${attr}="[^"]*"`)
|
|
77
|
+
if (pattern.test(text)) {
|
|
78
|
+
return text.replace(pattern, `${attr}="${value}"`)
|
|
79
|
+
}
|
|
80
|
+
return text.replace(/<application\b/, `<application\n ${attr}="${value}"`)
|
|
81
|
+
}
|