@hot-updater/android-helper 1.2.0-rc.4 → 1.2.0-rc.41
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/dist/index.cjs +655 -778
- package/dist/index.d.cts +143 -123
- package/dist/index.d.mts +143 -123
- package/dist/index.mjs +646 -771
- package/package.json +5 -4
package/dist/index.cjs
CHANGED
|
@@ -31,125 +31,41 @@ let os = require("os");
|
|
|
31
31
|
os = __toESM(os, 1);
|
|
32
32
|
let jszip = require("jszip");
|
|
33
33
|
jszip = __toESM(jszip, 1);
|
|
34
|
+
let module$1 = require("module");
|
|
35
|
+
let _hot_updater_protocol_native_artifact = require("@hot-updater/protocol/native-artifact");
|
|
36
|
+
let fast_xml_parser = require("fast-xml-parser");
|
|
34
37
|
let crypto = require("crypto");
|
|
35
38
|
crypto = __toESM(crypto, 1);
|
|
36
39
|
let stream_promises = require("stream/promises");
|
|
37
40
|
let zlib = require("zlib");
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
41
|
+
//#region src/utils/gradlePhase.ts
|
|
42
|
+
/** `> Task :app:compileReleaseKotlin`, with an outcome such as `UP-TO-DATE`. */
|
|
43
|
+
const TASK = /^> Task (:\S+)/;
|
|
44
|
+
const CONFIGURE = /^> Configure project (:\S*)/;
|
|
45
|
+
/**
|
|
46
|
+
* Reads the phase of a Gradle build from its plain console output: the
|
|
47
|
+
* task it runs, after how many it has run, such as
|
|
48
|
+
* `312 tasks · :app:mergeReleaseResources`.
|
|
49
|
+
*/
|
|
50
|
+
const createGradlePhaseReader = () => {
|
|
51
|
+
let tasks = 0;
|
|
52
|
+
return (line) => {
|
|
53
|
+
const task = TASK.exec(line)?.[1];
|
|
54
|
+
if (task) {
|
|
55
|
+
tasks += 1;
|
|
56
|
+
return `${tasks} task${tasks === 1 ? "" : "s"} · ${task}`;
|
|
57
|
+
}
|
|
58
|
+
const project = CONFIGURE.exec(line)?.[1];
|
|
59
|
+
if (project) return `Configuring ${project}`;
|
|
60
|
+
if (line.startsWith("Starting a Gradle Daemon")) return "Starting the Gradle daemon";
|
|
61
|
+
if (line.startsWith("Downloading https://services.gradle.org/")) return "Downloading Gradle";
|
|
62
|
+
};
|
|
63
|
+
};
|
|
64
|
+
//#endregion
|
|
42
65
|
//#region src/utils/createGradleLogger.ts
|
|
43
66
|
const createGradleLogger = ({ logPrefix }) => new _hot_updater_cli_tools.BuildLogger({
|
|
44
67
|
logPrefix,
|
|
45
|
-
|
|
46
|
-
"error:",
|
|
47
|
-
"Error:",
|
|
48
|
-
"ERROR:",
|
|
49
|
-
"> Task :",
|
|
50
|
-
"BUILD FAILED",
|
|
51
|
-
"BUILD SUCCESSFUL",
|
|
52
|
-
"FAILURE: Build failed with an exception.",
|
|
53
|
-
"* What went wrong:",
|
|
54
|
-
"Execution failed for task",
|
|
55
|
-
"Could not resolve",
|
|
56
|
-
"Failed to",
|
|
57
|
-
"Unable to load script",
|
|
58
|
-
"Metro encountered an error",
|
|
59
|
-
"React Native CLI",
|
|
60
|
-
"Android resource compilation failed",
|
|
61
|
-
"Duplicate class",
|
|
62
|
-
"Program type already present",
|
|
63
|
-
"actionable tasks:",
|
|
64
|
-
"Deprecated Gradle features were used",
|
|
65
|
-
":app:configureCMake",
|
|
66
|
-
":app:buildCMake",
|
|
67
|
-
":app:compileDebugKotlin",
|
|
68
|
-
":app:compileReleaseKotlin",
|
|
69
|
-
":app:compileDebugJavaWithJavac",
|
|
70
|
-
":app:compileReleaseJavaWithJavac",
|
|
71
|
-
":app:mergeDebugResources",
|
|
72
|
-
":app:mergeReleaseResources",
|
|
73
|
-
":app:processDebugResources",
|
|
74
|
-
":app:processReleaseResources",
|
|
75
|
-
":app:packageDebug",
|
|
76
|
-
":app:packageRelease",
|
|
77
|
-
":app:assembleDebug",
|
|
78
|
-
":app:assembleRelease"
|
|
79
|
-
],
|
|
80
|
-
progressStages: [
|
|
81
|
-
[
|
|
82
|
-
"buildKotlinToolingMetadata",
|
|
83
|
-
"generateAutolinkingNewArchitectureFiles",
|
|
84
|
-
"generateAutolinkingPackageList",
|
|
85
|
-
"generateCodegenSchemaFromJavaScript",
|
|
86
|
-
"generateCodegenArtifactsFromSchema",
|
|
87
|
-
"generateReactNativeEntryPoint"
|
|
88
|
-
],
|
|
89
|
-
[
|
|
90
|
-
"createBundleReleaseJsAndAssets",
|
|
91
|
-
"bundleReleaseJsAndAssets",
|
|
92
|
-
"bundleDebugJsAndAssets"
|
|
93
|
-
],
|
|
94
|
-
[
|
|
95
|
-
"generateReleaseResValues",
|
|
96
|
-
"generateDebugResValues",
|
|
97
|
-
"generateReleaseResources",
|
|
98
|
-
"generateDebugResources",
|
|
99
|
-
"mergeReleaseResources",
|
|
100
|
-
"mergeDebugResources"
|
|
101
|
-
],
|
|
102
|
-
[
|
|
103
|
-
"processReleaseResources",
|
|
104
|
-
"processDebugResources",
|
|
105
|
-
"processReleaseManifest",
|
|
106
|
-
"processDebugManifest",
|
|
107
|
-
"processDebugMainManifest",
|
|
108
|
-
"parseReleaseLocalResources",
|
|
109
|
-
"parseDebugLocalResources"
|
|
110
|
-
],
|
|
111
|
-
["compileReleaseKotlin", "compileDebugKotlin"],
|
|
112
|
-
["compileReleaseJavaWithJavac", "compileDebugJavaWithJavac"],
|
|
113
|
-
[
|
|
114
|
-
/configureCMake\w+\[/,
|
|
115
|
-
/buildCMake\w+\[/,
|
|
116
|
-
"mergeReleaseJniLibFolders",
|
|
117
|
-
"mergeDebugJniLibFolders",
|
|
118
|
-
"mergeReleaseNativeLibs",
|
|
119
|
-
"mergeDebugNativeLibs"
|
|
120
|
-
],
|
|
121
|
-
[
|
|
122
|
-
"desugarReleaseFileDependencies",
|
|
123
|
-
"desugarDebugFileDependencies",
|
|
124
|
-
"dexBuilderRelease",
|
|
125
|
-
"dexBuilderDebug",
|
|
126
|
-
"mergeDexRelease",
|
|
127
|
-
"mergeExtDexRelease",
|
|
128
|
-
"mergeExtDexDebug",
|
|
129
|
-
"mergeProjectDexRelease",
|
|
130
|
-
"mergeProjectDexDebug",
|
|
131
|
-
"mergeLibDexRelease",
|
|
132
|
-
"mergeLibDexDebug",
|
|
133
|
-
"mergeDebugGlobalSynthetics",
|
|
134
|
-
"mergeReleaseGlobalSynthetics",
|
|
135
|
-
"transformClassesWithDex"
|
|
136
|
-
],
|
|
137
|
-
[
|
|
138
|
-
"compressReleaseAssets",
|
|
139
|
-
"compressDebugAssets",
|
|
140
|
-
"optimizeReleaseResources",
|
|
141
|
-
"mergeReleaseAssets",
|
|
142
|
-
"mergeDebugAssets"
|
|
143
|
-
],
|
|
144
|
-
[
|
|
145
|
-
"packageRelease",
|
|
146
|
-
"packageDebug",
|
|
147
|
-
"assembleRelease",
|
|
148
|
-
"assembleDebug"
|
|
149
|
-
],
|
|
150
|
-
["bundleRelease", "bundleDebug"],
|
|
151
|
-
["BUILD SUCCESSFUL", /\d+ actionable tasks:/]
|
|
152
|
-
],
|
|
68
|
+
createPhaseReader: createGradlePhaseReader,
|
|
153
69
|
failureSummary: {
|
|
154
70
|
lines: [
|
|
155
71
|
/^e: /,
|
|
@@ -203,26 +119,54 @@ function getTaskNames(moduleName, tasks) {
|
|
|
203
119
|
* Get gradle wrapper command based on platform
|
|
204
120
|
*/
|
|
205
121
|
const getGradleWrapper = () => process.platform.startsWith("win") ? "gradlew.bat" : "./gradlew";
|
|
122
|
+
/** A variable a POSIX shell can't name, as the signing environment's are. */
|
|
123
|
+
const isShellName = (name) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(name);
|
|
124
|
+
/**
|
|
125
|
+
* The command that runs the wrapper with `env`. The wrapper's `#!/bin/sh` is
|
|
126
|
+
* dash on Debian and Ubuntu, which silently drops a variable whose name isn't
|
|
127
|
+
* a shell name, such as `ORG_GRADLE_PROJECT_android.injected.signing.store.file`:
|
|
128
|
+
* the build then signs with the project's own config. bash keeps them.
|
|
129
|
+
*/
|
|
130
|
+
const gradleCommand = (env) => {
|
|
131
|
+
const wrapper = getGradleWrapper();
|
|
132
|
+
return wrapper === "./gradlew" && Object.keys(env ?? {}).some((name) => !isShellName(name)) ? ["bash", [wrapper]] : [wrapper, []];
|
|
133
|
+
};
|
|
206
134
|
/**
|
|
207
135
|
* Run gradle build with specified tasks and arguments
|
|
208
136
|
*/
|
|
209
|
-
async function runGradle(
|
|
137
|
+
async function runGradle(args) {
|
|
138
|
+
const logFilePath = await runGradleTasks(args);
|
|
139
|
+
return {
|
|
140
|
+
...await findBuildDirectory({
|
|
141
|
+
androidProjectPath: args.androidProjectPath,
|
|
142
|
+
moduleName: args.appModuleName,
|
|
143
|
+
tasks: args.tasks
|
|
144
|
+
}),
|
|
145
|
+
logFilePath
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
/** Runs tasks that leave no artifact to find, and returns the build log, or null. */
|
|
149
|
+
async function runGradleTasks({ tasks, logPrefix, args, env, androidProjectPath, appModuleName, logHeader = [] }) {
|
|
210
150
|
const gradleArgs = getTaskNames(appModuleName, tasks);
|
|
211
151
|
gradleArgs.push("-x", "lint");
|
|
212
152
|
if (args.extraParams) gradleArgs.push(...args.extraParams);
|
|
213
|
-
_hot_updater_cli_tools.p.log.info([
|
|
214
|
-
"Gradle build",
|
|
215
|
-
`Project ${path.default.relative((0, _hot_updater_cli_tools.getCwd)(), androidProjectPath) || "."}`,
|
|
216
|
-
`App module ${appModuleName}`,
|
|
217
|
-
`Tasks ${tasks.join(", ")}`,
|
|
218
|
-
"Command",
|
|
219
|
-
formatCommand([path.default.basename(getGradleWrapper()), ...gradleArgs])
|
|
220
|
-
].join("\n"));
|
|
221
153
|
if ("port" in args && args.port != null) gradleArgs.push(`-PreactNativeDevServerPort=${args.port}`);
|
|
222
154
|
const logger = createGradleLogger({ logPrefix });
|
|
223
|
-
await logger.start(
|
|
155
|
+
await logger.start({
|
|
156
|
+
title: `Building ${tasks.join(", ")}`,
|
|
157
|
+
header: [
|
|
158
|
+
...logHeader,
|
|
159
|
+
`Project ${path.default.relative((0, _hot_updater_cli_tools.getCwd)(), androidProjectPath) || "."}`,
|
|
160
|
+
`App module ${appModuleName}`,
|
|
161
|
+
`Tasks ${tasks.join(", ")}`,
|
|
162
|
+
`$ ${formatCommand([path.default.basename(getGradleWrapper()), ...gradleArgs])}`,
|
|
163
|
+
""
|
|
164
|
+
]
|
|
165
|
+
});
|
|
166
|
+
let logFilePath = null;
|
|
224
167
|
try {
|
|
225
|
-
const
|
|
168
|
+
const [command, prefix] = gradleCommand(env);
|
|
169
|
+
const gradle = (0, execa.execa)(command, [...prefix, ...gradleArgs], {
|
|
226
170
|
cwd: androidProjectPath,
|
|
227
171
|
env,
|
|
228
172
|
all: true,
|
|
@@ -232,11 +176,13 @@ async function runGradle({ tasks, logPrefix, args, env, androidProjectPath, appM
|
|
|
232
176
|
const [gradleResult, loggingResult] = await Promise.allSettled([gradle, outputStream ? logger.processStream(outputStream) : void 0]);
|
|
233
177
|
if (gradleResult.status === "rejected") throw gradleResult.reason;
|
|
234
178
|
if (loggingResult.status === "rejected") throw loggingResult.reason;
|
|
235
|
-
logger.stop();
|
|
179
|
+
logger.stop(`Built ${tasks.join(", ")}`);
|
|
180
|
+
logFilePath = logger.logFilePath;
|
|
236
181
|
} catch (e) {
|
|
237
182
|
logger.writeError(e);
|
|
238
|
-
|
|
239
|
-
|
|
183
|
+
const reason = describeFailure(e);
|
|
184
|
+
logger.stop(`Build failed · ${reason.replace(/\.$/, "")}`, false);
|
|
185
|
+
throw new _hot_updater_cli_tools.BuildFailedError(`Build failed: ${reason}`, {
|
|
240
186
|
logPath: logger.logPath,
|
|
241
187
|
summary: logger.failureSummary,
|
|
242
188
|
cause: e
|
|
@@ -244,11 +190,7 @@ async function runGradle({ tasks, logPrefix, args, env, androidProjectPath, appM
|
|
|
244
190
|
} finally {
|
|
245
191
|
await logger.close();
|
|
246
192
|
}
|
|
247
|
-
return
|
|
248
|
-
androidProjectPath,
|
|
249
|
-
moduleName: appModuleName,
|
|
250
|
-
tasks
|
|
251
|
-
});
|
|
193
|
+
return logFilePath;
|
|
252
194
|
}
|
|
253
195
|
/**
|
|
254
196
|
* Find the build output directory and artifact path
|
|
@@ -541,20 +483,334 @@ const readBuiltVersionCode = async ({ artifactPath, androidProjectPath }) => {
|
|
|
541
483
|
}
|
|
542
484
|
};
|
|
543
485
|
//#endregion
|
|
486
|
+
//#region src/utils/sandboxManifest.ts
|
|
487
|
+
const MAIN = "android.intent.action.MAIN";
|
|
488
|
+
const LAUNCHER = "android.intent.category.LAUNCHER";
|
|
489
|
+
const SHORTCUTS = "android.app.shortcuts";
|
|
490
|
+
const ANDROID = "android:";
|
|
491
|
+
const asArray = (value) => value === void 0 || value === null || value === "" ? [] : Array.isArray(value) ? value : [value];
|
|
492
|
+
const attribute = (element, name) => {
|
|
493
|
+
const value = element[`${ANDROID}${name}`];
|
|
494
|
+
return typeof value === "string" ? value : void 0;
|
|
495
|
+
};
|
|
496
|
+
const filtersOf = (component) => asArray(component["intent-filter"]).map((filter) => ({
|
|
497
|
+
actions: asArray(filter["action"]),
|
|
498
|
+
categories: asArray(filter["category"]),
|
|
499
|
+
data: asArray(filter["data"]),
|
|
500
|
+
attributes: Object.fromEntries(Object.entries(filter).filter(([name]) => name.startsWith(ANDROID)))
|
|
501
|
+
}));
|
|
502
|
+
const opensAsLauncher = ({ actions, categories }) => actions.some((action) => attribute(action, "name") === MAIN) && categories.some((category) => attribute(category, "name") === LAUNCHER);
|
|
503
|
+
/** Task settings a sandbox activity can't share a task with: what, and how to fix it. */
|
|
504
|
+
const taskRefusal = (name, activity) => {
|
|
505
|
+
const launchMode = attribute(activity, "launchMode");
|
|
506
|
+
if (launchMode === "singleInstance" || launchMode === "singleInstancePerTask") return `Sandbox builds don't support launchMode ${launchMode} on the launcher ${name}.\nUse singleTask or the default launch mode.`;
|
|
507
|
+
if (attribute(activity, "taskAffinity") !== void 0) return `Sandbox builds don't support taskAffinity on the launcher ${name}.\nRemove it from this build variant.`;
|
|
508
|
+
const documents = attribute(activity, "documentLaunchMode");
|
|
509
|
+
if (documents !== void 0 && documents !== "none") return `Sandbox builds don't support documentLaunchMode ${documents} on the launcher ${name}.\nRemove it from this build variant.`;
|
|
510
|
+
return null;
|
|
511
|
+
};
|
|
512
|
+
/**
|
|
513
|
+
* The launcher entry of a variant's merged manifest, which already holds what
|
|
514
|
+
* its flavors, build type and libraries declare. It refuses what a sandbox
|
|
515
|
+
* build can't take over: none or several entries, a filter it can't move whole,
|
|
516
|
+
* and task settings its activity can't share a task with.
|
|
517
|
+
*/
|
|
518
|
+
const resolveSandboxLauncher = (mergedManifest) => {
|
|
519
|
+
const application = new fast_xml_parser.XMLParser({
|
|
520
|
+
ignoreAttributes: false,
|
|
521
|
+
attributeNamePrefix: ""
|
|
522
|
+
}).parse(mergedManifest)?.manifest?.application;
|
|
523
|
+
const activities = asArray(application?.["activity"]);
|
|
524
|
+
const aliases = asArray(application?.["activity-alias"]);
|
|
525
|
+
const entries = [...activities.map((element) => ({
|
|
526
|
+
kind: "activity",
|
|
527
|
+
element
|
|
528
|
+
})), ...aliases.map((element) => ({
|
|
529
|
+
kind: "activity-alias",
|
|
530
|
+
element
|
|
531
|
+
}))].flatMap(({ kind, element }) => {
|
|
532
|
+
const filters = filtersOf(element).filter(opensAsLauncher);
|
|
533
|
+
return filters.length === 0 ? [] : [{
|
|
534
|
+
kind,
|
|
535
|
+
element,
|
|
536
|
+
filters
|
|
537
|
+
}];
|
|
538
|
+
});
|
|
539
|
+
const names = entries.map(({ element }) => attribute(element, "name") ?? "?");
|
|
540
|
+
if (entries.length === 0) throw new Error("A sandbox build needs a launcher, and this variant's manifest has none.\nAdd a MAIN + LAUNCHER intent filter to an activity.");
|
|
541
|
+
if (entries.length > 1) throw new Error(`A sandbox build needs one launcher, and this variant has ${names.length}: ${names.join(", ")}.\nKeep one for this build variant.`);
|
|
542
|
+
const { kind, element, filters } = entries[0];
|
|
543
|
+
const name = names[0];
|
|
544
|
+
if (filters.length > 1) throw new Error(`The launcher ${name} has ${filters.length} MAIN + LAUNCHER filters, and a sandbox build can move one.\nKeep one for this build variant.`);
|
|
545
|
+
if (attribute(element, "enabled") === "false") throw new Error(`The launcher ${name} is disabled in the manifest, and a sandbox build can't tell when it would open.\nEnable it for this build variant.`);
|
|
546
|
+
const targetActivity = kind === "activity-alias" ? attribute(element, "targetActivity") : void 0;
|
|
547
|
+
const activity = kind === "activity" ? element : activities.find((item) => attribute(item, "name") === targetActivity);
|
|
548
|
+
if (activity === void 0) throw new Error(`The launcher ${name} targets ${targetActivity ?? "no activity"}, which this variant's manifest doesn't declare.\nFix its android:targetActivity.`);
|
|
549
|
+
const refusal = taskRefusal(name, activity);
|
|
550
|
+
if (refusal !== null) throw new Error(refusal);
|
|
551
|
+
const launcherProcess = attribute(activity, "process");
|
|
552
|
+
if (launcherProcess !== void 0 && launcherProcess !== attribute(application ?? {}, "process")) throw new Error(`Sandbox builds run the launcher in the application's process, and ${name} sets android:process ${launcherProcess}.\nRemove it, or set the same android:process on <application>, for this build variant.`);
|
|
553
|
+
const shortcuts = asArray(element["meta-data"]).find((item) => attribute(item, "name") === SHORTCUTS);
|
|
554
|
+
const label = attribute(element, "label");
|
|
555
|
+
const icon = attribute(element, "icon");
|
|
556
|
+
const roundIcon = attribute(element, "roundIcon");
|
|
557
|
+
const shortcutsResource = shortcuts && attribute(shortcuts, "resource");
|
|
558
|
+
return {
|
|
559
|
+
kind,
|
|
560
|
+
name,
|
|
561
|
+
...targetActivity === void 0 ? {} : { targetActivity },
|
|
562
|
+
filter: filters[0],
|
|
563
|
+
...label === void 0 ? {} : { label },
|
|
564
|
+
...icon === void 0 ? {} : { icon },
|
|
565
|
+
...roundIcon === void 0 ? {} : { roundIcon },
|
|
566
|
+
...shortcutsResource === void 0 ? {} : { shortcuts: shortcutsResource }
|
|
567
|
+
};
|
|
568
|
+
};
|
|
569
|
+
const COMPONENTS = [
|
|
570
|
+
"activity",
|
|
571
|
+
"activity-alias",
|
|
572
|
+
"service",
|
|
573
|
+
"receiver"
|
|
574
|
+
];
|
|
575
|
+
/**
|
|
576
|
+
* The URL schemes a variant's merged manifest declares in its components'
|
|
577
|
+
* intent filters, in lower case: a sandbox build registers none of them.
|
|
578
|
+
*/
|
|
579
|
+
const declaredUrlSchemes = (mergedManifest) => {
|
|
580
|
+
const application = new fast_xml_parser.XMLParser({
|
|
581
|
+
ignoreAttributes: false,
|
|
582
|
+
attributeNamePrefix: ""
|
|
583
|
+
}).parse(mergedManifest)?.manifest?.application;
|
|
584
|
+
return COMPONENTS.flatMap((component) => asArray(application?.[component])).flatMap((element) => filtersOf(element).flatMap(({ data }) => data.flatMap((item) => {
|
|
585
|
+
const scheme = attribute(item, "scheme");
|
|
586
|
+
return scheme === void 0 ? [] : [scheme.toLowerCase()];
|
|
587
|
+
})));
|
|
588
|
+
};
|
|
589
|
+
const xml = (text) => text.replace(/&/gu, "&").replace(/"/gu, """).replace(/</gu, "<").replace(/>/gu, ">");
|
|
590
|
+
const attributesOf = (element) => Object.entries(element).filter(([, value]) => typeof value === "string").map(([name, value]) => ` ${name}="${xml(value)}"`).join("");
|
|
591
|
+
/** A launcher filter, element by element: the merger matches a filter by content. */
|
|
592
|
+
const filterXml = ({ actions, categories, data, attributes }, extra = "") => [
|
|
593
|
+
`<intent-filter${attributesOf(attributes)}${extra}>`,
|
|
594
|
+
...actions.map((item) => ` <action${attributesOf(item)} />`),
|
|
595
|
+
...categories.map((item) => ` <category${attributesOf(item)} />`),
|
|
596
|
+
...data.map((item) => ` <data${attributesOf(item)} />`),
|
|
597
|
+
"</intent-filter>"
|
|
598
|
+
].map((line) => ` ${line}`).join("\n");
|
|
599
|
+
const optional = (name, value) => value === void 0 ? "" : ` android:${name}="${xml(value)}"`;
|
|
600
|
+
/**
|
|
601
|
+
* The manifest a sandbox build overlays on the app's, which keeps the app's
|
|
602
|
+
* channel: a sandbox build embeds the project's, as any build does. The launcher's
|
|
603
|
+
* filter, label, icon and static shortcuts move to the sandbox's activity, which
|
|
604
|
+
* also takes the links of `urlScheme`, which its `<meta-data>` names for the
|
|
605
|
+
* build to read; the rest of the app's activity stays, so its own links still
|
|
606
|
+
* reach it.
|
|
607
|
+
* The dev server is plain http, which a project's network security config can
|
|
608
|
+
* still refuse: the screen then says so.
|
|
609
|
+
*/
|
|
610
|
+
const sandboxManifestOverlay = ({ urlScheme, launcher }) => `<?xml version="1.0" encoding="utf-8"?>
|
|
611
|
+
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
|
|
612
|
+
<application android:usesCleartextTraffic="true" tools:replace="android:usesCleartextTraffic">
|
|
613
|
+
<meta-data android:name="${_hot_updater_protocol_native_artifact.SANDBOX_META_DATA}" android:value="true" />
|
|
614
|
+
<activity android:name="${_hot_updater_protocol_native_artifact.SANDBOX_ACTIVITY}" android:exported="true" android:launchMode="singleTop" android:theme="@style/HotUpdaterSandboxTheme" android:configChanges="density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode" android:enableOnBackInvokedCallback="true"${optional("label", launcher.label)}${optional("icon", launcher.icon)}${optional("roundIcon", launcher.roundIcon)}>
|
|
615
|
+
${filterXml(launcher.filter)}
|
|
616
|
+
<intent-filter>
|
|
617
|
+
<action android:name="android.intent.action.VIEW" />
|
|
618
|
+
<category android:name="android.intent.category.DEFAULT" />
|
|
619
|
+
<category android:name="android.intent.category.BROWSABLE" />
|
|
620
|
+
<data android:scheme="${xml(urlScheme)}" />
|
|
621
|
+
</intent-filter>
|
|
622
|
+
<meta-data android:name="com.hotupdater.sandbox.HOST_ACTIVITY" android:value="${xml(launcher.name)}" />
|
|
623
|
+
<meta-data android:name="${_hot_updater_protocol_native_artifact.SANDBOX_URL_SCHEME_META_DATA}" android:value="${xml(urlScheme)}" />${launcher.shortcuts === void 0 ? "" : `\n <meta-data android:name="${SHORTCUTS}" android:resource="${xml(launcher.shortcuts)}" />`}
|
|
624
|
+
</activity>
|
|
625
|
+
<${launcher.kind} android:name="${xml(launcher.name)}"${optional("targetActivity", launcher.targetActivity)}>
|
|
626
|
+
${filterXml(launcher.filter, " tools:node=\"remove\"")}${launcher.shortcuts === void 0 ? "" : `\n <meta-data android:name="${SHORTCUTS}" tools:node="remove" />`}
|
|
627
|
+
</${launcher.kind}>
|
|
628
|
+
<activity android:name="com.hotupdater.HotUpdaterSandboxRelaunchActivity" android:excludeFromRecents="true" android:exported="false" android:launchMode="singleTask" android:noHistory="true" android:process=":hotupdater_restart" android:theme="@android:style/Theme.NoDisplay" />
|
|
629
|
+
<provider android:name="com.hotupdater.HotUpdaterSandboxProcess" android:authorities="\${applicationId}.hotupdater.sandbox" android:exported="false" />
|
|
630
|
+
</application>
|
|
631
|
+
</manifest>
|
|
632
|
+
`;
|
|
633
|
+
/** Newest first: the manifest of the task that ran last, under `directory`. */
|
|
634
|
+
const manifestsUnder = (directory) => {
|
|
635
|
+
if (!fs.default.existsSync(directory)) return [];
|
|
636
|
+
return fs.default.readdirSync(directory, { recursive: true }).map(String).filter((file) => path.default.basename(file) === "AndroidManifest.xml").map((file) => path.default.join(directory, file)).sort((a, b) => fs.default.statSync(b).mtimeMs - fs.default.statSync(a).mtimeMs);
|
|
637
|
+
};
|
|
638
|
+
/** The Gradle task that merges a variant's manifest. */
|
|
639
|
+
const mergeManifestTask = (variant) => `process${variant.charAt(0).toUpperCase()}${variant.slice(1)}MainManifest`;
|
|
640
|
+
/**
|
|
641
|
+
* The manifest the merge task of `variant` wrote: AGP 7 and 8 keep it under
|
|
642
|
+
* `build/intermediates/merged_manifest`, in a directory per variant.
|
|
643
|
+
*/
|
|
644
|
+
const readMergedManifest = ({ androidProjectPath, appModuleName, variant }) => {
|
|
645
|
+
const variantDirectory = `${variant.charAt(0).toLowerCase()}${variant.slice(1)}`;
|
|
646
|
+
const intermediates = path.default.join(androidProjectPath, appModuleName, "build/intermediates");
|
|
647
|
+
const [manifest] = ["merged_manifest", "merged_manifests"].flatMap((name) => manifestsUnder(path.default.join(intermediates, name, variantDirectory)));
|
|
648
|
+
if (manifest === void 0) throw new Error(`Couldn't find the merged manifest of ${variant} under android/${appModuleName}/build/intermediates.\nBuild the variant once, then try again.`);
|
|
649
|
+
return fs.default.readFileSync(manifest, "utf-8");
|
|
650
|
+
};
|
|
651
|
+
//#endregion
|
|
652
|
+
//#region src/utils/sandboxGradle.ts
|
|
653
|
+
const UNSUPPORTED_DSL = `Sandbox builds don't support AGP 9's default DSL yet.
|
|
654
|
+
Set android.newDsl=false in android/gradle.properties.`;
|
|
655
|
+
/** The message when the build type has a manifest the overlay would replace. */
|
|
656
|
+
const ownManifest = (manifest) => `A sandbox build can't merge with ${manifest}.\nMove what it declares to src/main/AndroidManifest.xml.`;
|
|
657
|
+
/** The message when no project compiled the SDK from source, which a dev server needs. */
|
|
658
|
+
const PREBUILT_SDK = `This app takes @hot-updater/react-native as a prebuilt AAR, and a sandbox build compiles the SDK from source.
|
|
659
|
+
Add the SDK's autolinked project to this build instead of the AAR.`;
|
|
660
|
+
/** Text as a single-quoted Groovy string. */
|
|
661
|
+
const groovyString = (text) => `'${text.replace(/\\/gu, "\\\\").replace(/'/gu, "\\'").replace(/\n/gu, "\\n")}'`;
|
|
662
|
+
/**
|
|
663
|
+
* The init script of one sandbox build, so no project file changes: on the app
|
|
664
|
+
* module, it appends the sandbox's suffix to defaultConfig, where AGP puts any
|
|
665
|
+
* flavor's and build type's after it, and adds `overlay` to the variant's build
|
|
666
|
+
* type. It runs in `finalizeDsl`, after the project's own settings.
|
|
667
|
+
*/
|
|
668
|
+
const sandboxInitScript = ({ appModuleName, variant, overlay, minVersionCode }) => `// Written by hot-updater for one sandbox build.
|
|
669
|
+
def appModule = ${groovyString(`:${appModuleName}`)}
|
|
670
|
+
def variant = ${groovyString(variant.toLowerCase())}
|
|
671
|
+
def overlay = new File(${groovyString(overlay)})
|
|
672
|
+
def minVersionCode = ${minVersionCode ?? "null"}
|
|
673
|
+
allprojects { project ->
|
|
674
|
+
if (project.path != appModule) return
|
|
675
|
+
// In this build alone: an init script also runs for React Native's included
|
|
676
|
+
// Gradle plugin. The SDK's sandbox script sets this on the project it compiles.
|
|
677
|
+
gradle.taskGraph.whenReady {
|
|
678
|
+
if (!gradle.rootProject.ext.has('hotUpdaterSandboxSdkProject')) {
|
|
679
|
+
throw new GradleException(${groovyString(PREBUILT_SDK)})
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
project.plugins.withId('com.android.application') {
|
|
683
|
+
def components = project.extensions.getByName('androidComponents')
|
|
684
|
+
if (components.pluginVersion.major >= 9 && project.findProperty('android.newDsl')?.toString() != 'false') {
|
|
685
|
+
throw new GradleException(${groovyString(UNSUPPORTED_DSL)})
|
|
686
|
+
}
|
|
687
|
+
components.finalizeDsl { dsl ->
|
|
688
|
+
def buildType = dsl.buildTypes.collect { it.name }
|
|
689
|
+
.findAll { variant.endsWith(it.toLowerCase()) }
|
|
690
|
+
.max { it.length() }
|
|
691
|
+
if (buildType == null) {
|
|
692
|
+
throw new GradleException("No build type of \${project.path} builds variant \${variant}.")
|
|
693
|
+
}
|
|
694
|
+
def manifest = dsl.sourceSets.getByName(buildType).manifest
|
|
695
|
+
def own = manifest.srcFile
|
|
696
|
+
if (own.exists()) {
|
|
697
|
+
throw new GradleException(${groovyString(ownManifest("@MANIFEST@"))}.replace('@MANIFEST@', 'android/' + project.rootDir.toPath().relativize(own.toPath())))
|
|
698
|
+
}
|
|
699
|
+
dsl.defaultConfig.applicationIdSuffix = (dsl.defaultConfig.applicationIdSuffix ?: '') + ${groovyString(_hot_updater_protocol_native_artifact.SANDBOX_APPLICATION_ID_SUFFIX)}
|
|
700
|
+
manifest.srcFile(overlay)
|
|
701
|
+
if (minVersionCode != null) {
|
|
702
|
+
dsl.defaultConfig.versionCode = Math.max(dsl.defaultConfig.versionCode ?: 0, minVersionCode)
|
|
703
|
+
dsl.productFlavors.each { flavor ->
|
|
704
|
+
if (flavor.versionCode != null) flavor.versionCode = Math.max(flavor.versionCode, minVersionCode)
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
`;
|
|
711
|
+
/**
|
|
712
|
+
* Runs `build` with the Gradle arguments of a scheme: none for a normal one. A
|
|
713
|
+
* sandbox scheme's attach the SDK's sandbox layer and name the init script,
|
|
714
|
+
* written outside the project with its manifest overlay, and removed after.
|
|
715
|
+
* Kotlin compiles from scratch, since the sandbox layer's sources come and go.
|
|
716
|
+
* `readEffectiveManifest` is the variant's merged manifest before the overlay,
|
|
717
|
+
* which the overlay takes the launcher from.
|
|
718
|
+
*/
|
|
719
|
+
const withSandboxGradleArgs = async (scheme, readEffectiveManifest, build, { minVersionCode } = {}) => {
|
|
720
|
+
if (!scheme.sandbox) return build([]);
|
|
721
|
+
if (!scheme.packageName) throw new Error(`The sandbox scheme ${scheme.hotUpdaterSchemeName} sets no packageName, which its URL scheme comes from.\nSet packageName on the scheme.`);
|
|
722
|
+
const effectiveManifest = await readEffectiveManifest();
|
|
723
|
+
const launcher = resolveSandboxLauncher(effectiveManifest);
|
|
724
|
+
const urlScheme = scheme.sandboxUrlScheme ?? (0, _hot_updater_protocol_native_artifact.sandboxUrlSchemeOf)(scheme.packageName);
|
|
725
|
+
if (declaredUrlSchemes(effectiveManifest).includes(urlScheme.toLowerCase())) throw new Error(`The sandbox scheme ${scheme.hotUpdaterSchemeName} registers URL scheme ${urlScheme}, which the app registers itself.\nSet sandbox.urlScheme to a scheme the app doesn't register.`);
|
|
726
|
+
const directory = await fs.default.promises.mkdtemp(path.default.join(os.default.tmpdir(), "hot-updater-sandbox-"));
|
|
727
|
+
try {
|
|
728
|
+
const overlay = path.default.join(directory, "AndroidManifest.xml");
|
|
729
|
+
const initScript = path.default.join(directory, "sandbox.init.gradle");
|
|
730
|
+
await fs.default.promises.writeFile(overlay, sandboxManifestOverlay({
|
|
731
|
+
urlScheme,
|
|
732
|
+
launcher
|
|
733
|
+
}));
|
|
734
|
+
await fs.default.promises.writeFile(initScript, sandboxInitScript({
|
|
735
|
+
appModuleName: scheme.appModuleName,
|
|
736
|
+
variant: scheme.variant,
|
|
737
|
+
overlay,
|
|
738
|
+
...minVersionCode === void 0 ? {} : { minVersionCode }
|
|
739
|
+
}));
|
|
740
|
+
return await build([
|
|
741
|
+
"--init-script",
|
|
742
|
+
initScript,
|
|
743
|
+
`-PhotUpdaterSandbox=${scheme.hotUpdaterSchemeName}`,
|
|
744
|
+
"-Pkotlin.incremental=false"
|
|
745
|
+
]);
|
|
746
|
+
} finally {
|
|
747
|
+
await fs.default.promises.rm(directory, {
|
|
748
|
+
recursive: true,
|
|
749
|
+
force: true
|
|
750
|
+
});
|
|
751
|
+
}
|
|
752
|
+
};
|
|
753
|
+
/** The major version of the Android Gradle Plugin the project pins, or null. */
|
|
754
|
+
const readAgpMajor = (androidProjectPath) => {
|
|
755
|
+
const rootBuild = ["build.gradle", "build.gradle.kts"].map((file) => path.default.join(androidProjectPath, file)).filter((file) => fs.default.existsSync(file)).map((file) => fs.default.readFileSync(file, "utf-8")).join("\n");
|
|
756
|
+
const pinned = /com\.android\.tools\.build:gradle:(\d+)/u.exec(rootBuild);
|
|
757
|
+
if (pinned) return Number(pinned[1]);
|
|
758
|
+
try {
|
|
759
|
+
const manifest = (0, module$1.createRequire)(path.default.join(androidProjectPath, "package.json")).resolve("react-native/package.json");
|
|
760
|
+
const catalog = fs.default.readFileSync(path.default.join(path.default.dirname(manifest), "gradle/libs.versions.toml"), "utf-8");
|
|
761
|
+
const agp = /^\s*agp\s*=\s*"(\d+)/mu.exec(catalog);
|
|
762
|
+
return agp ? Number(agp[1]) : null;
|
|
763
|
+
} catch {
|
|
764
|
+
return null;
|
|
765
|
+
}
|
|
766
|
+
};
|
|
767
|
+
/**
|
|
768
|
+
* Why a sandbox build of a scheme can't work, read from the project's files
|
|
769
|
+
* before anything is built, or null. The init script checks again, with what
|
|
770
|
+
* Gradle actually resolved.
|
|
771
|
+
*/
|
|
772
|
+
const findSandboxGradleBlocker = ({ variant = "Release", appModuleName = "app" }) => {
|
|
773
|
+
const androidProjectPath = path.default.join((0, _hot_updater_cli_tools.getCwd)(), "android");
|
|
774
|
+
if (!fs.default.existsSync(androidProjectPath)) return null;
|
|
775
|
+
const properties = path.default.join(androidProjectPath, "gradle.properties");
|
|
776
|
+
const newDsl = fs.default.existsSync(properties) ? /^\s*android\.newDsl\s*=\s*(\S+)/mu.exec(fs.default.readFileSync(properties, "utf-8"))?.[1] : void 0;
|
|
777
|
+
if (newDsl === "true" || newDsl === void 0 && (readAgpMajor(androidProjectPath) ?? 0) >= 9) return UNSUPPORTED_DSL;
|
|
778
|
+
const buildType = /([A-Z]?[a-z0-9]+)$/u.exec(variant)?.[1]?.toLowerCase();
|
|
779
|
+
const manifest = `${appModuleName}/src/${buildType}/AndroidManifest.xml`;
|
|
780
|
+
return buildType && fs.default.existsSync(path.default.join(androidProjectPath, manifest)) ? ownManifest(`android/${manifest}`) : null;
|
|
781
|
+
};
|
|
782
|
+
//#endregion
|
|
544
783
|
//#region src/buildAndroid.ts
|
|
545
|
-
const buildAndroid = async ({ schemeConfig, minBundleId = (0, _hot_updater_cli_tools.createMinBundleId)(), credentials }) => {
|
|
784
|
+
const buildAndroid = async ({ schemeConfig, minBundleId = (0, _hot_updater_cli_tools.createMinBundleId)(), credentials, logHeader, minVersionCode }) => {
|
|
546
785
|
const androidProjectPath = path.default.join((0, _hot_updater_cli_tools.getCwd)(), "android");
|
|
547
|
-
const
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
786
|
+
const env = await resolveGradleSigningEnv({
|
|
787
|
+
schemeConfig,
|
|
788
|
+
credentials
|
|
789
|
+
});
|
|
790
|
+
const result = await withSandboxGradleArgs(schemeConfig, async () => {
|
|
791
|
+
await runGradleTasks({
|
|
792
|
+
args: { extraParams: [`-PMIN_BUNDLE_ID=${minBundleId}`] },
|
|
793
|
+
env,
|
|
794
|
+
appModuleName: schemeConfig.appModuleName,
|
|
795
|
+
tasks: [mergeManifestTask(schemeConfig.variant)],
|
|
796
|
+
logPrefix: `android-${schemeConfig.hotUpdaterSchemeName}-manifest`,
|
|
797
|
+
androidProjectPath,
|
|
798
|
+
logHeader
|
|
799
|
+
});
|
|
800
|
+
return readMergedManifest({
|
|
801
|
+
androidProjectPath,
|
|
802
|
+
appModuleName: schemeConfig.appModuleName,
|
|
803
|
+
variant: schemeConfig.variant
|
|
804
|
+
});
|
|
805
|
+
}, (sandboxArgs) => runGradle({
|
|
806
|
+
args: { extraParams: [`-PMIN_BUNDLE_ID=${minBundleId}`, ...sandboxArgs] },
|
|
807
|
+
env,
|
|
553
808
|
appModuleName: schemeConfig.appModuleName,
|
|
554
809
|
tasks: schemeConfig.aab ? [`bundle${schemeConfig.variant}`] : [`assemble${schemeConfig.variant}`],
|
|
555
810
|
logPrefix: `android-${schemeConfig.hotUpdaterSchemeName}-build`,
|
|
556
|
-
androidProjectPath
|
|
557
|
-
|
|
811
|
+
androidProjectPath,
|
|
812
|
+
logHeader
|
|
813
|
+
}), minVersionCode === void 0 ? {} : { minVersionCode });
|
|
558
814
|
return {
|
|
559
815
|
...result,
|
|
560
816
|
builtApp: await readBuiltApp({
|
|
@@ -564,6 +820,105 @@ const buildAndroid = async ({ schemeConfig, minBundleId = (0, _hot_updater_cli_t
|
|
|
564
820
|
};
|
|
565
821
|
};
|
|
566
822
|
//#endregion
|
|
823
|
+
//#region src/device.ts
|
|
824
|
+
/** The SDK's adb, or the one on the PATH without an SDK in the environment. */
|
|
825
|
+
const adbPath = () => {
|
|
826
|
+
const sdk = process.env["ANDROID_HOME"] || process.env["ANDROID_SDK_ROOT"];
|
|
827
|
+
const executable = process.platform.startsWith("win") ? "adb.exe" : "adb";
|
|
828
|
+
const fromSdk = sdk && path.default.join(sdk, "platform-tools", executable);
|
|
829
|
+
return fromSdk && fs.default.existsSync(fromSdk) ? fromSdk : executable;
|
|
830
|
+
};
|
|
831
|
+
const adb = async (args) => {
|
|
832
|
+
try {
|
|
833
|
+
return (await (0, execa.execa)(adbPath(), args)).stdout;
|
|
834
|
+
} catch (error) {
|
|
835
|
+
const { code, stderr, stdout, shortMessage } = error;
|
|
836
|
+
if (code === "ENOENT") throw new Error("adb isn't installed.\nInstall Android platform-tools, or set ANDROID_HOME.");
|
|
837
|
+
throw new Error(stderr?.trim() || stdout?.trim() || shortMessage || String(error));
|
|
838
|
+
}
|
|
839
|
+
};
|
|
840
|
+
/** What `adb devices` lists. */
|
|
841
|
+
const listAdbDevices = async () => (await adb(["devices"])).split("\n").slice(1).map((line) => line.trim().split(/\s+/u)).flatMap(([serial, state]) => serial && state ? [{
|
|
842
|
+
serial,
|
|
843
|
+
state
|
|
844
|
+
}] : []);
|
|
845
|
+
/**
|
|
846
|
+
* The device to install on: `serial`, as adb's own `ANDROID_SERIAL` names it
|
|
847
|
+
* too, or else the only one that takes commands.
|
|
848
|
+
*/
|
|
849
|
+
const selectAdbDevice = (devices, serial = process.env["ANDROID_SERIAL"] || void 0) => {
|
|
850
|
+
if (serial !== void 0) {
|
|
851
|
+
const device = devices.find((candidate) => candidate.serial === serial);
|
|
852
|
+
if (device === void 0) throw new Error(`${serial} isn't connected.\nList them: adb devices`);
|
|
853
|
+
if (device.state !== "device") throw new Error(`${serial} is ${device.state}.\nList them: adb devices`);
|
|
854
|
+
return device;
|
|
855
|
+
}
|
|
856
|
+
const ready = devices.filter(({ state }) => state === "device");
|
|
857
|
+
const [only] = ready;
|
|
858
|
+
if (only === void 0) throw new Error("No Android device or emulator is connected.\nStart an emulator or connect a phone, then run this again.");
|
|
859
|
+
if (ready.length > 1) throw new Error([
|
|
860
|
+
`${ready.length} Android devices are connected:`,
|
|
861
|
+
...ready.map(({ serial }) => ` ${serial}`),
|
|
862
|
+
"Pick one with --device <serial>."
|
|
863
|
+
].join("\n"));
|
|
864
|
+
return only;
|
|
865
|
+
};
|
|
866
|
+
/** A failure adb reports for an install another install of the app stands in the way of. */
|
|
867
|
+
const NEEDS_UNINSTALL = /^INSTALL_FAILED_(UPDATE_INCOMPATIBLE|VERSION_DOWNGRADE)\b/u;
|
|
868
|
+
const LAUNCHER_CATEGORY = "android.intent.category.LAUNCHER";
|
|
869
|
+
/** An application ID's form, checked before it reaches the device's shell. */
|
|
870
|
+
const APP_ID = /^[A-Za-z][A-Za-z0-9_.]*$/u;
|
|
871
|
+
/** `<application ID>/<activity>`, as `resolve-activity --brief` prints it. */
|
|
872
|
+
const ACTIVITY = /^[A-Za-z0-9_.]+\/[A-Za-z0-9_.$]+$/u;
|
|
873
|
+
/**
|
|
874
|
+
* Installs an APK on a device, and opens its launcher activity. `appId` is
|
|
875
|
+
* the APK's own application ID, whatever suffix its build gave it.
|
|
876
|
+
*/
|
|
877
|
+
const installOnAndroidDevice = async ({ serial, apkPath, appId }) => {
|
|
878
|
+
if (!APP_ID.test(appId)) throw new Error(`The APK's application ID isn't valid: ${appId}`);
|
|
879
|
+
try {
|
|
880
|
+
await adb([
|
|
881
|
+
"-s",
|
|
882
|
+
serial,
|
|
883
|
+
"install",
|
|
884
|
+
"-r",
|
|
885
|
+
apkPath
|
|
886
|
+
]);
|
|
887
|
+
} catch (error) {
|
|
888
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
889
|
+
const failure = /Failure \[([^\]]+)\]/u.exec(message)?.[1] ?? message;
|
|
890
|
+
throw new Error(NEEDS_UNINSTALL.test(failure) ? `The installed ${appId} can't be replaced: ${failure}\nUninstall it: adb -s ${serial} uninstall ${appId}` : `adb couldn't install the APK: ${failure}`);
|
|
891
|
+
}
|
|
892
|
+
const activity = (await adb([
|
|
893
|
+
"-s",
|
|
894
|
+
serial,
|
|
895
|
+
"shell",
|
|
896
|
+
"cmd",
|
|
897
|
+
"package",
|
|
898
|
+
"resolve-activity",
|
|
899
|
+
"--brief",
|
|
900
|
+
"-c",
|
|
901
|
+
LAUNCHER_CATEGORY,
|
|
902
|
+
appId
|
|
903
|
+
])).trim().split("\n").at(-1)?.trim();
|
|
904
|
+
if (activity === void 0 || !ACTIVITY.test(activity)) throw new Error(`${appId} is installed, and has no launcher activity to open.`);
|
|
905
|
+
const started = await adb([
|
|
906
|
+
"-s",
|
|
907
|
+
serial,
|
|
908
|
+
"shell",
|
|
909
|
+
"am",
|
|
910
|
+
"start",
|
|
911
|
+
"-a",
|
|
912
|
+
"android.intent.action.MAIN",
|
|
913
|
+
"-c",
|
|
914
|
+
LAUNCHER_CATEGORY,
|
|
915
|
+
"-n",
|
|
916
|
+
`'${activity}'`
|
|
917
|
+
]);
|
|
918
|
+
const error = /^Error: .*$/mu.exec(started)?.[0];
|
|
919
|
+
if (error !== void 0) throw new Error(`${appId} is installed, and didn't open. ${error}`);
|
|
920
|
+
};
|
|
921
|
+
//#endregion
|
|
567
922
|
//#region src/uploadToPlay.ts
|
|
568
923
|
const API_URL = "https://androidpublisher.googleapis.com";
|
|
569
924
|
/** Where Google serves resumable upload sessions, as its docs show both. */
|
|
@@ -667,7 +1022,7 @@ const explain = (error, packageName) => {
|
|
|
667
1022
|
if (status === 401 || /does not have permission/i.test(apiMessage)) return new Error([
|
|
668
1023
|
`The Play service account can't release ${packageName}.`,
|
|
669
1024
|
"Invite its email in Play Console (Users and permissions) to release to",
|
|
670
|
-
"testing tracks, and enable the Google Play Android Developer API."
|
|
1025
|
+
"testing tracks (Release to production for production), and enable the Google Play Android Developer API."
|
|
671
1026
|
].join("\n"), { cause: error });
|
|
672
1027
|
if (/package not found/i.test(apiMessage)) return new Error(`Google Play has no app ${packageName}.\nCreate it in Play Console and upload its first .aab there.`, { cause: error });
|
|
673
1028
|
if (/version code .*(already been used|already used)/i.test(apiMessage)) return new PlayVersionCodeUsedError({ cause: error });
|
|
@@ -676,7 +1031,8 @@ const explain = (error, packageName) => {
|
|
|
676
1031
|
/**
|
|
677
1032
|
* Requests to the Google Play Developer API for `packageName`, as the
|
|
678
1033
|
* service account: each carries an access token, exchanged for a signed
|
|
679
|
-
* assertion and replaced well before it expires.
|
|
1034
|
+
* assertion and replaced well before it expires. `checkPlayAccess`
|
|
1035
|
+
* checks a key's access with it too.
|
|
680
1036
|
*/
|
|
681
1037
|
const createPlayClient = ({ json, packageName, fetch }) => {
|
|
682
1038
|
const account = readServiceAccount(json);
|
|
@@ -725,11 +1081,69 @@ const createPlayClient = ({ json, packageName, fetch }) => {
|
|
|
725
1081
|
};
|
|
726
1082
|
};
|
|
727
1083
|
/**
|
|
728
|
-
*
|
|
729
|
-
*
|
|
730
|
-
|
|
1084
|
+
* Play Console's page that invites `email` as a user. `_` stands for the
|
|
1085
|
+
* developer account the browser is signed in to, so no ID is needed.
|
|
1086
|
+
*/
|
|
1087
|
+
const playConsoleInviteUrl = (email) => `https://play.google.com/console/u/0/developers/_/users-and-permissions?invite=${encodeURIComponent(email)}`;
|
|
1088
|
+
const readClientEmail = (json) => {
|
|
1089
|
+
try {
|
|
1090
|
+
const { client_email } = JSON.parse(json);
|
|
1091
|
+
return typeof client_email === "string" ? client_email : "";
|
|
1092
|
+
} catch {
|
|
1093
|
+
return "";
|
|
1094
|
+
}
|
|
1095
|
+
};
|
|
1096
|
+
/**
|
|
1097
|
+
* Checks once whether the service account's key reaches `packageName`: it
|
|
1098
|
+
* opens an edit of the app and deletes it again, which changes nothing.
|
|
1099
|
+
* Throws only for what says nothing about access, such as a network error.
|
|
1100
|
+
*/
|
|
1101
|
+
const checkPlayAccess = async ({ serviceAccount: { json }, packageName, fetch = globalThis.fetch }) => {
|
|
1102
|
+
const email = readClientEmail(json);
|
|
1103
|
+
const refused = (error) => ({
|
|
1104
|
+
status: "refused",
|
|
1105
|
+
email,
|
|
1106
|
+
reason: error instanceof Error ? error.message : String(error)
|
|
1107
|
+
});
|
|
1108
|
+
let play;
|
|
1109
|
+
try {
|
|
1110
|
+
play = createPlayClient({
|
|
1111
|
+
json,
|
|
1112
|
+
packageName,
|
|
1113
|
+
fetch
|
|
1114
|
+
});
|
|
1115
|
+
} catch (error) {
|
|
1116
|
+
return refused(error);
|
|
1117
|
+
}
|
|
1118
|
+
try {
|
|
1119
|
+
await play.authorization();
|
|
1120
|
+
} catch (error) {
|
|
1121
|
+
if (error instanceof TypeError) throw error;
|
|
1122
|
+
return refused(error);
|
|
1123
|
+
}
|
|
1124
|
+
const edits = `${API_URL}${play.app}/edits`;
|
|
1125
|
+
try {
|
|
1126
|
+
const edit = await play.request(`Opening an edit of ${packageName}`, "POST", edits, {});
|
|
1127
|
+
if (edit?.id) await play.request("Deleting the edit", "DELETE", `${edits}/${encodeURIComponent(edit.id)}`).catch(() => {});
|
|
1128
|
+
return { status: "ready" };
|
|
1129
|
+
} catch (error) {
|
|
1130
|
+
if (error instanceof GooglePlayError) {
|
|
1131
|
+
if (error.status === 401 || error.status === 403) return {
|
|
1132
|
+
status: "denied",
|
|
1133
|
+
email
|
|
1134
|
+
};
|
|
1135
|
+
if (error.status === 404) return {
|
|
1136
|
+
status: "not-found",
|
|
1137
|
+
email
|
|
1138
|
+
};
|
|
1139
|
+
}
|
|
1140
|
+
throw error;
|
|
1141
|
+
}
|
|
1142
|
+
};
|
|
1143
|
+
/**
|
|
1144
|
+
* Reads the app in an edit it then deletes, changing nothing.
|
|
731
1145
|
*/
|
|
732
|
-
const
|
|
1146
|
+
const readInEdit = async ({ packageName, serviceAccount: { json }, fetch }, read) => {
|
|
733
1147
|
const { app, request } = createPlayClient({
|
|
734
1148
|
json,
|
|
735
1149
|
packageName,
|
|
@@ -743,8 +1157,7 @@ const findPlayInternalRelease = async ({ versionCode, packageName, serviceAccoun
|
|
|
743
1157
|
}
|
|
744
1158
|
const edit = `${API_URL}${app}/edits/${encodeURIComponent(editId)}`;
|
|
745
1159
|
try {
|
|
746
|
-
|
|
747
|
-
return releases.some(({ versionCodes = [] }) => versionCodes.includes(String(versionCode)));
|
|
1160
|
+
return await read(request, edit);
|
|
748
1161
|
} catch (error) {
|
|
749
1162
|
throw explain(error, packageName);
|
|
750
1163
|
} finally {
|
|
@@ -752,6 +1165,44 @@ const findPlayInternalRelease = async ({ versionCode, packageName, serviceAccoun
|
|
|
752
1165
|
}
|
|
753
1166
|
};
|
|
754
1167
|
/**
|
|
1168
|
+
* The status of the selected track's release holding `versionCode`, defaulting
|
|
1169
|
+
* to internal testing, such as
|
|
1170
|
+
* `completed` or `draft`, or null when the track doesn't hold it: never
|
|
1171
|
+
* uploaded, or replaced by a newer release, which testers get instead.
|
|
1172
|
+
*/
|
|
1173
|
+
const readPlayTrackRelease = ({ versionCode, track = INTERNAL_TRACK, packageName, serviceAccount, fetch = globalThis.fetch }) => readInEdit({
|
|
1174
|
+
packageName,
|
|
1175
|
+
serviceAccount,
|
|
1176
|
+
fetch
|
|
1177
|
+
}, async (request, edit) => {
|
|
1178
|
+
const { releases = [] } = await request(`Reading the ${track} track`, "GET", `${edit}/tracks/${encodeURIComponent(track)}`);
|
|
1179
|
+
const release = releases.find(({ versionCodes = [] }) => versionCodes.includes(String(versionCode)));
|
|
1180
|
+
return release ? release.status ?? "completed" : null;
|
|
1181
|
+
});
|
|
1182
|
+
/**
|
|
1183
|
+
* Whether Google Play's internal testing track already releases the
|
|
1184
|
+
* `.aab`'s version code, as when a reused native build was uploaded before.
|
|
1185
|
+
*/
|
|
1186
|
+
const findPlayInternalRelease = async (options) => await readPlayTrackRelease(options) !== null;
|
|
1187
|
+
/**
|
|
1188
|
+
* The highest version code Google Play has taken for the app, on any track,
|
|
1189
|
+
* or null with none: a new `.aab` needs one above it.
|
|
1190
|
+
*/
|
|
1191
|
+
const readPlayHighestVersionCode = ({ packageName, serviceAccount, fetch = globalThis.fetch }) => readInEdit({
|
|
1192
|
+
packageName,
|
|
1193
|
+
serviceAccount,
|
|
1194
|
+
fetch
|
|
1195
|
+
}, async (request, edit) => {
|
|
1196
|
+
const { bundles = [] } = await request("Reading the app's bundles", "GET", `${edit}/bundles`);
|
|
1197
|
+
const codes = bundles.flatMap(({ versionCode }) => versionCode ?? []);
|
|
1198
|
+
return codes.length > 0 ? Math.max(...codes) : null;
|
|
1199
|
+
});
|
|
1200
|
+
/**
|
|
1201
|
+
* The link that opts a tester in to the app's testing tracks. A build on the
|
|
1202
|
+
* internal track installs through it, for the testers Play Console lists.
|
|
1203
|
+
*/
|
|
1204
|
+
const playTestingUrl = (packageName) => `https://play.google.com/apps/testing/${encodeURIComponent(packageName)}`;
|
|
1205
|
+
/**
|
|
755
1206
|
* The common name of every Android debug certificate: Android Studio's and
|
|
756
1207
|
* the Android Gradle plugin's (`CN=Android Debug, O=Android, C=US`), and React
|
|
757
1208
|
* Native's template `debug.keystore` (`CN=Android Debug, OU=Android,
|
|
@@ -779,12 +1230,13 @@ const assertPlaySigned = async (aabPath) => {
|
|
|
779
1230
|
].join("\n"));
|
|
780
1231
|
};
|
|
781
1232
|
/**
|
|
782
|
-
* Uploads an `.aab` to Google Play
|
|
1233
|
+
* Uploads or promotes an `.aab` to a Google Play track with the Google
|
|
783
1234
|
* Play Developer API: it opens an edit, uploads the bundle, releases its
|
|
784
|
-
* version code to the
|
|
1235
|
+
* version code to the selected track, and commits the edit, which it
|
|
785
1236
|
* deletes again when any step fails. The service account stays in memory.
|
|
786
1237
|
*/
|
|
787
|
-
const uploadToPlay = async ({ aabPath, packageName, serviceAccount: { json }, fetch = globalThis.fetch, commitRetryDelayMs = 2e3 }) => {
|
|
1238
|
+
const uploadToPlay = async ({ aabPath, packageName, serviceAccount: { json }, fetch = globalThis.fetch, commitRetryDelayMs = 2e3, track = "internal", rollout = 100, existingVersionCode }) => {
|
|
1239
|
+
if (!Number.isInteger(rollout) || rollout < 1 || rollout > 100 || track === "internal" && rollout < 100) throw new Error(track === "internal" && rollout < 100 ? "Play internal testing does not support staged rollout." : "Rollout must be an integer from 1 to 100.");
|
|
788
1240
|
const { app, authorization, request } = createPlayClient({
|
|
789
1241
|
json,
|
|
790
1242
|
packageName,
|
|
@@ -798,20 +1250,28 @@ const uploadToPlay = async ({ aabPath, packageName, serviceAccount: { json }, fe
|
|
|
798
1250
|
}
|
|
799
1251
|
const edit = `${API_URL}${app}/edits/${encodeURIComponent(editId)}`;
|
|
800
1252
|
try {
|
|
801
|
-
_hot_updater_cli_tools.p.log.info(
|
|
802
|
-
const versionCode = await uploadBundle({
|
|
1253
|
+
_hot_updater_cli_tools.p.log.info(`${existingVersionCode === void 0 ? "Uploading" : "Promoting"} ${packageName} to Google Play`);
|
|
1254
|
+
const versionCode = existingVersionCode ?? await uploadBundle({
|
|
803
1255
|
aabPath,
|
|
804
1256
|
sessionUrl: `${API_URL}/upload${app}/edits/${encodeURIComponent(editId)}/bundles?uploadType=resumable`,
|
|
805
1257
|
authorization,
|
|
806
1258
|
fetch
|
|
807
1259
|
});
|
|
1260
|
+
const existingRelease = (existingVersionCode === void 0 ? void 0 : await request("Reading the Google Play track", "GET", `${edit}/tracks/${track}`))?.releases?.find((release) => release.versionCodes?.includes(String(versionCode)));
|
|
808
1261
|
const release = async (status) => {
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
1262
|
+
const updatedRelease = {
|
|
1263
|
+
...existingRelease,
|
|
1264
|
+
versionCodes: existingRelease?.versionCodes ?? [String(versionCode)],
|
|
1265
|
+
status
|
|
1266
|
+
};
|
|
1267
|
+
if (status === "inProgress") updatedRelease.userFraction = rollout / 100;
|
|
1268
|
+
else {
|
|
1269
|
+
delete updatedRelease.userFraction;
|
|
1270
|
+
delete updatedRelease.countryTargeting;
|
|
1271
|
+
}
|
|
1272
|
+
await request(`Releasing to the ${track} track`, "PUT", `${edit}/tracks/${track}`, {
|
|
1273
|
+
track,
|
|
1274
|
+
releases: [updatedRelease]
|
|
815
1275
|
});
|
|
816
1276
|
await commit({
|
|
817
1277
|
request,
|
|
@@ -820,10 +1280,11 @@ const uploadToPlay = async ({ aabPath, packageName, serviceAccount: { json }, fe
|
|
|
820
1280
|
});
|
|
821
1281
|
};
|
|
822
1282
|
try {
|
|
823
|
-
|
|
1283
|
+
const status = rollout < 100 ? "inProgress" : "completed";
|
|
1284
|
+
await release(status);
|
|
824
1285
|
return {
|
|
825
1286
|
versionCode,
|
|
826
|
-
status
|
|
1287
|
+
status
|
|
827
1288
|
};
|
|
828
1289
|
} catch (error) {
|
|
829
1290
|
if (!(error instanceof GooglePlayError) || !DRAFT_APP_ERRORS.some((message) => error.apiMessage.includes(message))) throw error;
|
|
@@ -855,7 +1316,7 @@ const commit = async ({ request, edit, retryDelayMs }) => {
|
|
|
855
1316
|
if (!(error instanceof GooglePlayError) || error.status >= 500 || error.status === 429) throw new Error([
|
|
856
1317
|
"Google Play didn't confirm the release.",
|
|
857
1318
|
error instanceof Error ? error.message : String(error),
|
|
858
|
-
"Check
|
|
1319
|
+
"Check the release in Play Console before you upload it again."
|
|
859
1320
|
].join("\n"), { cause: error });
|
|
860
1321
|
if (error.status !== 400) throw error;
|
|
861
1322
|
if (!changesNotSentForReview && error.apiMessage.includes(NEEDS_CHANGES_NOT_SENT_FOR_REVIEW)) {
|
|
@@ -1094,633 +1555,49 @@ const extractBuiltInBundle = async ({ artifactPath, outputPath }) => {
|
|
|
1094
1555
|
await (entry.method === 8 ? (0, stream_promises.pipeline)(source, (0, zlib.createInflateRaw)(), fs.default.createWriteStream(outputPath)) : (0, stream_promises.pipeline)(source, fs.default.createWriteStream(outputPath)));
|
|
1095
1556
|
};
|
|
1096
1557
|
//#endregion
|
|
1097
|
-
//#region src/
|
|
1098
|
-
/**
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
this.consumer = body.consumer;
|
|
1558
|
+
//#region src/playTracks.ts
|
|
1559
|
+
/** Google Play destinations and their API tracks. */
|
|
1560
|
+
const PLAY_TRACKS = {
|
|
1561
|
+
"play-internal": {
|
|
1562
|
+
track: "internal",
|
|
1563
|
+
label: "Play internal",
|
|
1564
|
+
name: "Google Play internal testing"
|
|
1565
|
+
},
|
|
1566
|
+
"play-closed": {
|
|
1567
|
+
track: "alpha",
|
|
1568
|
+
label: "Play closed",
|
|
1569
|
+
name: "Google Play closed testing"
|
|
1570
|
+
},
|
|
1571
|
+
"play-open": {
|
|
1572
|
+
track: "beta",
|
|
1573
|
+
label: "Play open",
|
|
1574
|
+
name: "Google Play open testing"
|
|
1575
|
+
},
|
|
1576
|
+
"play-production": {
|
|
1577
|
+
track: "production",
|
|
1578
|
+
label: "Play production",
|
|
1579
|
+
name: "Google Play production"
|
|
1120
1580
|
}
|
|
1121
1581
|
};
|
|
1122
|
-
/** Google's error body, `{ error: { code, status, message, details } }`. */
|
|
1123
|
-
const readError = async (action, response) => {
|
|
1124
|
-
let error;
|
|
1125
|
-
try {
|
|
1126
|
-
error = (await response.json()).error;
|
|
1127
|
-
} catch {}
|
|
1128
|
-
const details = Array.isArray(error?.details) ? error.details : [];
|
|
1129
|
-
const info = details.filter((detail) => typeof detail.reason === "string");
|
|
1130
|
-
return new GoogleApiError(action, response.status, {
|
|
1131
|
-
...typeof error?.status === "string" ? { apiStatus: error.status } : {},
|
|
1132
|
-
...typeof error?.message === "string" ? { apiMessage: error.message } : {},
|
|
1133
|
-
reasons: info.map((detail) => detail.reason),
|
|
1134
|
-
violations: details.flatMap((detail) => (detail.violations ?? []).flatMap((violation) => typeof violation.type === "string" ? [violation.type] : [])),
|
|
1135
|
-
...info.find((detail) => detail.metadata?.["consumer"]) ? { consumer: info.find((detail) => detail.metadata?.["consumer"]).metadata["consumer"] } : {}
|
|
1136
|
-
});
|
|
1137
|
-
};
|
|
1138
|
-
/** Whether Google answered that a service is disabled in a project. */
|
|
1139
|
-
const isServiceDisabled = (error) => error instanceof GoogleApiError && (error.reasons.includes("SERVICE_DISABLED") || /has not been used in project .* or it is disabled/i.test(error.apiMessage));
|
|
1140
|
-
/** Requests with the signed-in user's access token, throwing `GoogleApiError`. */
|
|
1141
|
-
const createGoogleRequest = ({ accessToken, fetch }) => async (action, method, url, body) => {
|
|
1142
|
-
const response = await fetch(url, {
|
|
1143
|
-
method,
|
|
1144
|
-
headers: {
|
|
1145
|
-
authorization: `Bearer ${accessToken}`,
|
|
1146
|
-
...body === void 0 ? {} : { "content-type": "application/json" }
|
|
1147
|
-
},
|
|
1148
|
-
...body === void 0 ? {} : { body: JSON.stringify(body) }
|
|
1149
|
-
});
|
|
1150
|
-
if (!response.ok) throw await readError(action, response);
|
|
1151
|
-
const text = await response.text();
|
|
1152
|
-
return text ? JSON.parse(text) : {};
|
|
1153
|
-
};
|
|
1154
|
-
/**
|
|
1155
|
-
* Polls `operation` at `origin` until it is done, returning its response or
|
|
1156
|
-
* throwing its error as a `GoogleApiError` with the operation's code.
|
|
1157
|
-
*/
|
|
1158
|
-
const waitForOperation = async ({ request, origin, operation, action, sleep, intervalMs = 2e3, attempts = 60 }) => {
|
|
1159
|
-
let current = operation;
|
|
1160
|
-
for (let attempt = 0; !current.done; attempt++) {
|
|
1161
|
-
if (attempt >= attempts || !current.name) throw new Error(`${action} did not finish in time.`);
|
|
1162
|
-
await sleep(intervalMs);
|
|
1163
|
-
current = await request(action, "GET", `${origin}/${current.name}`);
|
|
1164
|
-
}
|
|
1165
|
-
if (current.error) throw new GoogleApiError(action, 400, {
|
|
1166
|
-
apiMessage: current.error.message ?? "",
|
|
1167
|
-
...current.error.code === 7 ? { apiStatus: "PERMISSION_DENIED" } : {},
|
|
1168
|
-
...current.error.code === 8 ? { apiStatus: "RESOURCE_EXHAUSTED" } : {}
|
|
1169
|
-
});
|
|
1170
|
-
return current.response;
|
|
1171
|
-
};
|
|
1172
|
-
//#endregion
|
|
1173
|
-
//#region src/google/types.ts
|
|
1174
|
-
/** A named failure of `issuePlayServiceAccount`, with what to do in its message. */
|
|
1175
|
-
var PlayServiceAccountError = class extends Error {
|
|
1176
|
-
code;
|
|
1177
|
-
constructor(code, message, options) {
|
|
1178
|
-
super(message, options);
|
|
1179
|
-
this.name = "PlayServiceAccountError";
|
|
1180
|
-
this.code = code;
|
|
1181
|
-
}
|
|
1182
|
-
};
|
|
1183
|
-
/** The environment variables that replace Hot Updater's Google OAuth client. */
|
|
1184
|
-
const GOOGLE_OAUTH_CLIENT_ENV_NAMES = {
|
|
1185
|
-
clientId: "HOT_UPDATER_GOOGLE_OAUTH_CLIENT_ID",
|
|
1186
|
-
clientSecret: "HOT_UPDATER_GOOGLE_OAUTH_CLIENT_SECRET"
|
|
1187
|
-
};
|
|
1188
|
-
/** The service account Hot Updater creates, `hot-updater-play@<project>.iam.gserviceaccount.com`. */
|
|
1189
|
-
const PLAY_SERVICE_ACCOUNT_ID = "hot-updater-play";
|
|
1190
|
-
/** Where a Play Console admin finds the developer account ID. */
|
|
1191
|
-
const PLAY_CONSOLE_URL = "https://play.google.com/console";
|
|
1192
|
-
//#endregion
|
|
1193
|
-
//#region src/google/googleSignIn.ts
|
|
1194
|
-
const AUTHORIZATION_URL = "https://accounts.google.com/o/oauth2/v2/auth";
|
|
1195
|
-
const TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
1196
|
-
const REVOKE_URL = "https://oauth2.googleapis.com/revoke";
|
|
1197
|
-
/** How long the browser has to come back with the sign-in. */
|
|
1198
|
-
const SIGN_IN_TIMEOUT_MS = 3e5;
|
|
1199
|
-
const base64url = (bytes) => bytes.toString("base64url");
|
|
1200
|
-
const page = (message) => `<!doctype html><meta charset="utf-8"><title>Hot Updater</title><body style="font-family:system-ui;margin:3rem"><p>${message}</p></body>`;
|
|
1201
|
-
/**
|
|
1202
|
-
* Signs in with Google as an installed app does (RFC 8252): the browser
|
|
1203
|
-
* opens Google's own consent screen, so the password and the second factor
|
|
1204
|
-
* stay with Google, and the authorization code comes back to a loopback
|
|
1205
|
-
* server on 127.0.0.1, bound to a random port for this sign-in only. The
|
|
1206
|
-
* code is exchanged with PKCE (S256), and `state` ties the answer to this
|
|
1207
|
-
* request.
|
|
1208
|
-
*
|
|
1209
|
-
* @param onUrl Sees the sign-in URL, to print and open in a browser.
|
|
1210
|
-
*/
|
|
1211
|
-
const signInWithGoogle = async ({ client, scopes, onUrl, fetch = globalThis.fetch, timeoutMs = SIGN_IN_TIMEOUT_MS }) => {
|
|
1212
|
-
const verifier = base64url(node_crypto.default.randomBytes(32));
|
|
1213
|
-
const challenge = base64url(node_crypto.default.createHash("sha256").update(verifier).digest());
|
|
1214
|
-
const state = base64url(node_crypto.default.randomBytes(16));
|
|
1215
|
-
const server = node_http.default.createServer();
|
|
1216
|
-
await new Promise((resolve, reject) => {
|
|
1217
|
-
server.once("error", reject);
|
|
1218
|
-
server.listen(0, "127.0.0.1", () => resolve());
|
|
1219
|
-
});
|
|
1220
|
-
try {
|
|
1221
|
-
const { port } = server.address();
|
|
1222
|
-
const redirectUri = `http://127.0.0.1:${port}`;
|
|
1223
|
-
const code = new Promise((resolve, reject) => {
|
|
1224
|
-
const timer = setTimeout(() => reject(new PlayServiceAccountError("sign-in-cancelled", "The Google sign-in did not finish in time.")), timeoutMs);
|
|
1225
|
-
timer.unref();
|
|
1226
|
-
server.on("request", (req, res) => {
|
|
1227
|
-
const query = new URL(req.url ?? "/", redirectUri).searchParams;
|
|
1228
|
-
if (query.get("state") !== state) {
|
|
1229
|
-
res.writeHead(404).end();
|
|
1230
|
-
return;
|
|
1231
|
-
}
|
|
1232
|
-
const error = query.get("error");
|
|
1233
|
-
const answer = query.get("code");
|
|
1234
|
-
res.writeHead(error || !answer ? 400 : 200, { "content-type": "text/html; charset=utf-8" }).end(page(error || !answer ? "The sign-in did not finish. Return to the terminal." : "Signed in. Close this tab and return to the terminal."));
|
|
1235
|
-
clearTimeout(timer);
|
|
1236
|
-
if (error || !answer) reject(new PlayServiceAccountError("sign-in-cancelled", error === "access_denied" ? "The Google sign-in was cancelled." : `The Google sign-in failed: ${error ?? "no authorization code"}.`));
|
|
1237
|
-
else resolve(answer);
|
|
1238
|
-
});
|
|
1239
|
-
});
|
|
1240
|
-
code.catch(() => {});
|
|
1241
|
-
const url = new URL(AUTHORIZATION_URL);
|
|
1242
|
-
url.search = new URLSearchParams({
|
|
1243
|
-
client_id: client.clientId,
|
|
1244
|
-
redirect_uri: redirectUri,
|
|
1245
|
-
response_type: "code",
|
|
1246
|
-
scope: scopes.join(" "),
|
|
1247
|
-
code_challenge: challenge,
|
|
1248
|
-
code_challenge_method: "S256",
|
|
1249
|
-
state,
|
|
1250
|
-
prompt: "select_account"
|
|
1251
|
-
}).toString();
|
|
1252
|
-
await onUrl(url.toString());
|
|
1253
|
-
const authorizationCode = await code;
|
|
1254
|
-
(0, _hot_updater_cli_tools.registerSecretValue)(authorizationCode);
|
|
1255
|
-
const response = await fetch(TOKEN_URL, {
|
|
1256
|
-
method: "POST",
|
|
1257
|
-
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
1258
|
-
body: new URLSearchParams({
|
|
1259
|
-
code: authorizationCode,
|
|
1260
|
-
client_id: client.clientId,
|
|
1261
|
-
...client.clientSecret ? { client_secret: client.clientSecret } : {},
|
|
1262
|
-
redirect_uri: redirectUri,
|
|
1263
|
-
grant_type: "authorization_code",
|
|
1264
|
-
code_verifier: verifier
|
|
1265
|
-
}).toString()
|
|
1266
|
-
});
|
|
1267
|
-
const token = await response.json().catch(() => ({}));
|
|
1268
|
-
if (!response.ok || typeof token.access_token !== "string") throw new PlayServiceAccountError(token.error === "invalid_client" ? "sign-in-not-configured" : "sign-in-cancelled", `Google refused the sign-in (HTTP ${response.status}).${typeof token.error_description === "string" ? `\n${token.error_description}` : typeof token.error === "string" ? `\n${token.error}` : ""}`);
|
|
1269
|
-
(0, _hot_updater_cli_tools.registerSecretValue)(token.access_token);
|
|
1270
|
-
return {
|
|
1271
|
-
accessToken: token.access_token,
|
|
1272
|
-
scopes: typeof token.scope === "string" ? token.scope.split(" ") : []
|
|
1273
|
-
};
|
|
1274
|
-
} finally {
|
|
1275
|
-
server.closeAllConnections();
|
|
1276
|
-
await new Promise((resolve) => server.close(() => resolve()));
|
|
1277
|
-
}
|
|
1278
|
-
};
|
|
1279
|
-
/** Ends a sign-in: Google revokes its access token. Whether Google did. */
|
|
1280
|
-
const revokeGoogleToken = async (accessToken, fetch = globalThis.fetch) => {
|
|
1281
|
-
try {
|
|
1282
|
-
return (await fetch(REVOKE_URL, {
|
|
1283
|
-
method: "POST",
|
|
1284
|
-
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
1285
|
-
body: new URLSearchParams({ token: accessToken }).toString()
|
|
1286
|
-
})).ok;
|
|
1287
|
-
} catch {
|
|
1288
|
-
return false;
|
|
1289
|
-
}
|
|
1290
|
-
};
|
|
1291
|
-
//#endregion
|
|
1292
|
-
//#region src/google/googleKeyIssuer.ts
|
|
1293
|
-
const CLOUD_PLATFORM_SCOPE = "https://www.googleapis.com/auth/cloud-platform";
|
|
1294
|
-
const ANDROID_PUBLISHER_SCOPE = "https://www.googleapis.com/auth/androidpublisher";
|
|
1295
|
-
const SCOPES = [CLOUD_PLATFORM_SCOPE, ANDROID_PUBLISHER_SCOPE];
|
|
1296
|
-
const PUBLISHER_API = "https://androidpublisher.googleapis.com/androidpublisher/v3";
|
|
1297
|
-
const RESOURCE_MANAGER_API = "https://cloudresourcemanager.googleapis.com";
|
|
1298
|
-
const SERVICE_USAGE_API = "https://serviceusage.googleapis.com";
|
|
1299
|
-
const IAM_API = "https://iam.googleapis.com/v1";
|
|
1300
|
-
/** IAM creates the service account; the Play Developer API is what it calls. */
|
|
1301
|
-
const SERVICES = ["iam.googleapis.com", "androidpublisher.googleapis.com"];
|
|
1302
|
-
/**
|
|
1303
|
-
* What the service account may do in Play Console, for the app only: read
|
|
1304
|
-
* it, and release to testing tracks, which `--submit play-internal` does.
|
|
1305
|
-
*/
|
|
1306
|
-
const APP_PERMISSIONS = ["CAN_VIEW_NON_FINANCIAL_DATA", "CAN_MANAGE_TRACK_APKS"];
|
|
1307
|
-
const KEY_CREATION_CONSTRAINT = "constraints/iam.disableServiceAccountKeyCreation";
|
|
1308
|
-
/** Retries while Google enables an API or creates a service account. */
|
|
1309
|
-
const PROPAGATION_ATTEMPTS = 12;
|
|
1310
|
-
const PROPAGATION_DELAY_MS = 1e4;
|
|
1311
|
-
const sleepFor = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
1312
|
-
/** The developer account ID in `input`, a number or a Play Console URL. */
|
|
1313
|
-
const parseDeveloperId = (input) => {
|
|
1314
|
-
const trimmed = input.trim();
|
|
1315
|
-
if (/^\d+$/u.test(trimmed)) return trimmed;
|
|
1316
|
-
return trimmed.match(/\/developers\/(\d+)(?:[/?#]|$)/u)?.[1];
|
|
1317
|
-
};
|
|
1318
|
-
/** A project ID nobody has: Google Cloud's are global. */
|
|
1319
|
-
const newProjectId = () => `${PLAY_SERVICE_ACCOUNT_ID}-${node_crypto.default.randomBytes(3).toString("hex")}`;
|
|
1320
|
-
const isNotFound = (error) => error instanceof GoogleApiError && error.status === 404;
|
|
1321
|
-
const isConflict = (error) => error instanceof GoogleApiError && error.status === 409;
|
|
1322
|
-
/** The API is disabled in the OAuth client's own project: waiting does not help. */
|
|
1323
|
-
const clientApiDisabled = (error) => new PlayServiceAccountError("api-not-enabled", `${error.apiMessage}\nEnable it in the OAuth client's project (${GOOGLE_OAUTH_CLIENT_ENV_NAMES.clientId}).`, { cause: error });
|
|
1324
|
-
/** Google's own words, after a message that names the likely cause. */
|
|
1325
|
-
const googleSays = (error) => error instanceof GoogleApiError && error.apiMessage ? `\nGoogle: ${error.apiMessage}` : "";
|
|
1326
|
-
/** A Play Console refusal, as `not-play-admin`. */
|
|
1327
|
-
const notPlayAdmin = (developerId, error) => new PlayServiceAccountError("not-play-admin", `This Google Account isn't an admin of Play Console developer ${developerId}.${googleSays(error)}\nSign in with an account that has the Admin permission there.`, { cause: error });
|
|
1328
|
-
const isDenied = (error) => error instanceof GoogleApiError && (error.status === 403 || error.apiStatus === "PERMISSION_DENIED");
|
|
1329
|
-
/**
|
|
1330
|
-
* `IssuePlayServiceAccount` with Google's own APIs, after a sign-in on
|
|
1331
|
-
* Google's consent screen (OAuth for installed apps, with PKCE and a
|
|
1332
|
-
* loopback redirect):
|
|
1333
|
-
*
|
|
1334
|
-
* 1. the Play Console side is checked first, with no change anywhere: the
|
|
1335
|
-
* developer account answers to the account as its admin, and has the app;
|
|
1336
|
-
* 2. the chosen Google Cloud project, or a new one, gets the IAM and Play
|
|
1337
|
-
* Developer APIs enabled, and the service account `hot-updater-play`;
|
|
1338
|
-
* 3. the service account becomes a Play Console user that may release the
|
|
1339
|
-
* app to testing tracks;
|
|
1340
|
-
* 4. only then is its JSON key created, the last step, so a failure before
|
|
1341
|
-
* it leaves no key behind.
|
|
1342
|
-
*
|
|
1343
|
-
* Each step reuses what an earlier run created: the project, the service
|
|
1344
|
-
* account, and its Play Console access.
|
|
1345
|
-
*/
|
|
1346
|
-
const createGoogleKeyIssuer = ({ fetch = globalThis.fetch, sleep = sleepFor } = {}) => async (request) => {
|
|
1347
|
-
const { packageName, oauthClient, onStep = () => {} } = request;
|
|
1348
|
-
if (!oauthClient?.clientId) throw new PlayServiceAccountError("sign-in-not-configured", [
|
|
1349
|
-
"This build of Hot Updater has no Google OAuth client to sign in with.",
|
|
1350
|
-
"Set these to a \"Desktop app\" OAuth client:",
|
|
1351
|
-
`${GOOGLE_OAUTH_CLIENT_ENV_NAMES.clientId}, ${GOOGLE_OAUTH_CLIENT_ENV_NAMES.clientSecret}`
|
|
1352
|
-
].join("\n"));
|
|
1353
|
-
const signIn = await signInWithGoogle({
|
|
1354
|
-
client: oauthClient,
|
|
1355
|
-
scopes: SCOPES,
|
|
1356
|
-
onUrl: request.onSignInUrl,
|
|
1357
|
-
fetch
|
|
1358
|
-
});
|
|
1359
|
-
const dispose = async () => {
|
|
1360
|
-
await revokeGoogleToken(signIn.accessToken, fetch);
|
|
1361
|
-
};
|
|
1362
|
-
try {
|
|
1363
|
-
const missing = SCOPES.filter((scope) => !signIn.scopes.includes(scope));
|
|
1364
|
-
if (missing.length > 0) throw new PlayServiceAccountError("scope-not-granted", `The sign-in didn't allow ${missing.map((scope) => scope === ANDROID_PUBLISHER_SCOPE ? "managing Google Play" : "managing Google Cloud").join(" or ")}.\nRun this again and keep every box on Google's consent screen ticked.`);
|
|
1365
|
-
const google = createGoogleRequest({
|
|
1366
|
-
accessToken: signIn.accessToken,
|
|
1367
|
-
fetch
|
|
1368
|
-
});
|
|
1369
|
-
const developerInput = await request.askDeveloperId();
|
|
1370
|
-
const developerId = parseDeveloperId(developerInput);
|
|
1371
|
-
if (developerId === void 0) throw new PlayServiceAccountError("developer-not-found", `"${developerInput.trim()}" is not a developer account ID.\nIt is the number after /developers/ in Play Console's address.`);
|
|
1372
|
-
onStep("Checking the Play Console developer account");
|
|
1373
|
-
await checkPlayConsole({
|
|
1374
|
-
google,
|
|
1375
|
-
developerId,
|
|
1376
|
-
packageName
|
|
1377
|
-
});
|
|
1378
|
-
const project = await chooseProject({
|
|
1379
|
-
google,
|
|
1380
|
-
request,
|
|
1381
|
-
sleep,
|
|
1382
|
-
onStep
|
|
1383
|
-
});
|
|
1384
|
-
const { projectId } = project;
|
|
1385
|
-
onStep(`Enabling the Google Play Developer API in ${projectId}`);
|
|
1386
|
-
await enableServices({
|
|
1387
|
-
google,
|
|
1388
|
-
projectId,
|
|
1389
|
-
sleep
|
|
1390
|
-
});
|
|
1391
|
-
onStep(`Creating the service account in ${projectId}`);
|
|
1392
|
-
const email = await ensureServiceAccount({
|
|
1393
|
-
google,
|
|
1394
|
-
project,
|
|
1395
|
-
sleep
|
|
1396
|
-
});
|
|
1397
|
-
onStep(`Giving ${email} release access to ${packageName}`);
|
|
1398
|
-
await grantPlayAccess({
|
|
1399
|
-
google,
|
|
1400
|
-
developerId,
|
|
1401
|
-
email,
|
|
1402
|
-
packageName
|
|
1403
|
-
});
|
|
1404
|
-
onStep("Creating the service account's JSON key");
|
|
1405
|
-
const key = await createKey({
|
|
1406
|
-
google,
|
|
1407
|
-
project,
|
|
1408
|
-
email,
|
|
1409
|
-
sleep
|
|
1410
|
-
});
|
|
1411
|
-
return {
|
|
1412
|
-
json: key.json,
|
|
1413
|
-
keyId: key.keyId,
|
|
1414
|
-
email,
|
|
1415
|
-
projectId,
|
|
1416
|
-
developerId,
|
|
1417
|
-
revoke: async () => {
|
|
1418
|
-
try {
|
|
1419
|
-
await google("Deleting the key", "DELETE", `${IAM_API}/${key.name}`);
|
|
1420
|
-
return true;
|
|
1421
|
-
} catch (error) {
|
|
1422
|
-
return isNotFound(error);
|
|
1423
|
-
}
|
|
1424
|
-
},
|
|
1425
|
-
dispose
|
|
1426
|
-
};
|
|
1427
|
-
} catch (error) {
|
|
1428
|
-
await dispose();
|
|
1429
|
-
throw error;
|
|
1430
|
-
}
|
|
1431
|
-
};
|
|
1432
|
-
/**
|
|
1433
|
-
* Whether the signed-in account administers `developerId`, and Google Play
|
|
1434
|
-
* has `packageName` there, asked without changing anything: listing the
|
|
1435
|
-
* account's users takes the admin permission, and an edit opened on the app
|
|
1436
|
-
* is deleted again.
|
|
1437
|
-
*/
|
|
1438
|
-
const checkPlayConsole = async ({ google, developerId, packageName }) => {
|
|
1439
|
-
try {
|
|
1440
|
-
await google("Listing the Play Console users", "GET", `${PUBLISHER_API}/developers/${developerId}/users?pageSize=1`);
|
|
1441
|
-
} catch (error) {
|
|
1442
|
-
if (isServiceDisabled(error)) throw clientApiDisabled(error);
|
|
1443
|
-
if (isNotFound(error)) throw new PlayServiceAccountError("developer-not-found", `Play Console has no developer account ${developerId}.${googleSays(error)}\nIt is the number after /developers/ in Play Console's address.`, { cause: error });
|
|
1444
|
-
if (isDenied(error)) throw notPlayAdmin(developerId, error);
|
|
1445
|
-
throw error;
|
|
1446
|
-
}
|
|
1447
|
-
let edit;
|
|
1448
|
-
try {
|
|
1449
|
-
edit = await google(`Opening an edit of ${packageName}`, "POST", `${PUBLISHER_API}/applications/${encodeURIComponent(packageName)}/edits`);
|
|
1450
|
-
} catch (error) {
|
|
1451
|
-
if (isServiceDisabled(error)) throw clientApiDisabled(error);
|
|
1452
|
-
if (isNotFound(error) || isDenied(error)) throw appNotFound(packageName, developerId, error);
|
|
1453
|
-
throw error;
|
|
1454
|
-
}
|
|
1455
|
-
if (edit.id) await google("Deleting the edit", "DELETE", `${PUBLISHER_API}/applications/${encodeURIComponent(packageName)}/edits/${edit.id}`).catch(() => {});
|
|
1456
|
-
};
|
|
1457
|
-
const appNotFound = (packageName, developerId, cause) => new PlayServiceAccountError("app-not-found", `Google Play has no app ${packageName} in the developer account ${developerId}. Google takes the first .aab of a new app only in Play Console: create the app there, upload one .aab by hand (for example to internal testing), then run this again${googleSays(cause)}.`, { cause });
|
|
1458
|
-
/** The account's active projects, every page of them. */
|
|
1459
|
-
const listProjects = async (google) => {
|
|
1460
|
-
const projects = [];
|
|
1461
|
-
let pageToken;
|
|
1462
|
-
do {
|
|
1463
|
-
const page = await google("Listing the Google Cloud projects", "GET", `${RESOURCE_MANAGER_API}/v3/projects:search?${new URLSearchParams({
|
|
1464
|
-
query: "state:ACTIVE",
|
|
1465
|
-
...pageToken ? { pageToken } : {}
|
|
1466
|
-
})}`);
|
|
1467
|
-
for (const project of page.projects ?? []) if (project.projectId) projects.push({
|
|
1468
|
-
projectId: project.projectId,
|
|
1469
|
-
...project.displayName ? { displayName: project.displayName } : {},
|
|
1470
|
-
...projectNumberOf(project.name)
|
|
1471
|
-
});
|
|
1472
|
-
pageToken = page.nextPageToken || void 0;
|
|
1473
|
-
} while (pageToken);
|
|
1474
|
-
return projects;
|
|
1475
|
-
};
|
|
1476
|
-
/** The project the developer picks, or a new one when there is none or they ask. */
|
|
1477
|
-
const chooseProject = async ({ google, request, sleep, onStep }) => {
|
|
1478
|
-
const projects = await listProjects(google);
|
|
1479
|
-
const chosen = projects.length > 0 ? await request.chooseProject(projects.map(({ projectId, displayName }) => ({
|
|
1480
|
-
projectId,
|
|
1481
|
-
...displayName ? { displayName } : {}
|
|
1482
|
-
}))) : void 0;
|
|
1483
|
-
if (chosen !== void 0) return projects.find((project) => project.projectId === chosen) ?? { projectId: chosen };
|
|
1484
|
-
const projectId = newProjectId();
|
|
1485
|
-
onStep(`Creating the Google Cloud project ${projectId}`);
|
|
1486
|
-
try {
|
|
1487
|
-
const operation = await google("Creating the Google Cloud project", "POST", `${RESOURCE_MANAGER_API}/v3/projects`, {
|
|
1488
|
-
projectId,
|
|
1489
|
-
displayName: "Hot Updater Play"
|
|
1490
|
-
});
|
|
1491
|
-
const created = await waitForOperation({
|
|
1492
|
-
request: google,
|
|
1493
|
-
origin: `${RESOURCE_MANAGER_API}/v3`,
|
|
1494
|
-
operation,
|
|
1495
|
-
action: "Creating the Google Cloud project",
|
|
1496
|
-
sleep
|
|
1497
|
-
});
|
|
1498
|
-
return {
|
|
1499
|
-
projectId,
|
|
1500
|
-
...projectNumberOf(created?.name)
|
|
1501
|
-
};
|
|
1502
|
-
} catch (error) {
|
|
1503
|
-
if (!(error instanceof GoogleApiError)) throw error;
|
|
1504
|
-
if (error.status === 429 || error.apiStatus === "RESOURCE_EXHAUSTED" || /quota/iu.test(error.apiMessage)) throw new PlayServiceAccountError("project-quota", [
|
|
1505
|
-
"Google Cloud has no project quota left for this account.",
|
|
1506
|
-
error.apiMessage || "Quota exceeded.",
|
|
1507
|
-
"Run this again and pick an existing project, or delete one at:",
|
|
1508
|
-
"https://console.cloud.google.com/cloud-resource-manager"
|
|
1509
|
-
].join("\n"), { cause: error });
|
|
1510
|
-
if (/terms of service/iu.test(error.apiMessage)) throw new PlayServiceAccountError("project-create-denied", "This Google Account hasn't accepted the Google Cloud Terms of Service.\nAccept them at https://console.cloud.google.com, then run this again.", { cause: error });
|
|
1511
|
-
if (isDenied(error) || error.apiStatus === "FAILED_PRECONDITION") throw new PlayServiceAccountError("project-create-denied", [
|
|
1512
|
-
"This Google Account may not create Google Cloud projects.",
|
|
1513
|
-
error.apiMessage || "Permission denied.",
|
|
1514
|
-
"Pick an existing project, or ask an admin for the Project Creator role."
|
|
1515
|
-
].join("\n"), { cause: error });
|
|
1516
|
-
throw error;
|
|
1517
|
-
}
|
|
1518
|
-
};
|
|
1519
|
-
/** `projectNumber` from a resource name `projects/<number>`. */
|
|
1520
|
-
const projectNumberOf = (name) => {
|
|
1521
|
-
const number = name?.match(/^projects\/(\d+)$/u)?.[1];
|
|
1522
|
-
return number === void 0 ? {} : { projectNumber: number };
|
|
1523
|
-
};
|
|
1524
|
-
/**
|
|
1525
|
-
* Runs `run` again while Google is still enabling an API in `project`,
|
|
1526
|
-
* or, with `notFound`, still creating what it reads.
|
|
1527
|
-
*/
|
|
1528
|
-
const whilePropagating = async ({ run, project, sleep, notFound = false }) => {
|
|
1529
|
-
for (let attempt = 1;; attempt++) try {
|
|
1530
|
-
return await run();
|
|
1531
|
-
} catch (error) {
|
|
1532
|
-
const disabled = isServiceDisabled(error);
|
|
1533
|
-
if (disabled && !consumerIs(error, project)) throw clientApiDisabled(error);
|
|
1534
|
-
if (!disabled && !(notFound && isNotFound(error)) || attempt >= PROPAGATION_ATTEMPTS) {
|
|
1535
|
-
if (disabled) throw new PlayServiceAccountError("api-not-enabled", `Google is still enabling the APIs in ${project.projectId}.\n${error.apiMessage}\nWait a few minutes, then run this again.`, { cause: error });
|
|
1536
|
-
throw error;
|
|
1537
|
-
}
|
|
1538
|
-
await sleep(PROPAGATION_DELAY_MS);
|
|
1539
|
-
}
|
|
1540
|
-
};
|
|
1541
|
-
/**
|
|
1542
|
-
* Whether a disabled-service error is about `project` itself, which waiting
|
|
1543
|
-
* fixes: Google names the consumer by number, and an error naming none
|
|
1544
|
-
* counts as the project's own.
|
|
1545
|
-
*/
|
|
1546
|
-
const consumerIs = (error, project) => error.consumer === void 0 || error.consumer === `projects/${project.projectId}` || (project.projectNumber === void 0 ? true : error.consumer === `projects/${project.projectNumber}`);
|
|
1547
|
-
const enableServices = async ({ google, projectId, sleep }) => {
|
|
1548
|
-
try {
|
|
1549
|
-
const operation = await google("Enabling the APIs", "POST", `${SERVICE_USAGE_API}/v1/projects/${projectId}/services:batchEnable`, { serviceIds: SERVICES });
|
|
1550
|
-
await waitForOperation({
|
|
1551
|
-
request: google,
|
|
1552
|
-
origin: `${SERVICE_USAGE_API}/v1`,
|
|
1553
|
-
operation,
|
|
1554
|
-
action: "Enabling the APIs",
|
|
1555
|
-
sleep
|
|
1556
|
-
});
|
|
1557
|
-
} catch (error) {
|
|
1558
|
-
if (isDenied(error) && !isServiceDisabled(error)) throw new PlayServiceAccountError("project-access-denied", [
|
|
1559
|
-
`This Google Account may not enable APIs in ${projectId}.`,
|
|
1560
|
-
error.apiMessage || "Permission denied.",
|
|
1561
|
-
"Pick a project you own, or ask its owner for the Editor role."
|
|
1562
|
-
].join("\n"), { cause: error });
|
|
1563
|
-
throw error;
|
|
1564
|
-
}
|
|
1565
|
-
};
|
|
1566
|
-
/** The `hot-updater-play` service account's email, created unless it exists. */
|
|
1567
|
-
const ensureServiceAccount = async ({ google, project, sleep }) => {
|
|
1568
|
-
const { projectId } = project;
|
|
1569
|
-
const email = `${PLAY_SERVICE_ACCOUNT_ID}@${projectId}.iam.gserviceaccount.com`;
|
|
1570
|
-
try {
|
|
1571
|
-
return (await whilePropagating({
|
|
1572
|
-
project,
|
|
1573
|
-
sleep,
|
|
1574
|
-
run: () => google("Creating the service account", "POST", `${IAM_API}/projects/${projectId}/serviceAccounts`, {
|
|
1575
|
-
accountId: "hot-updater-play",
|
|
1576
|
-
serviceAccount: {
|
|
1577
|
-
displayName: "Hot Updater Play uploads",
|
|
1578
|
-
description: "Uploads Android App Bundles to Google Play for hot-updater native-build android --submit play-internal."
|
|
1579
|
-
}
|
|
1580
|
-
})
|
|
1581
|
-
})).email ?? email;
|
|
1582
|
-
} catch (error) {
|
|
1583
|
-
if (isConflict(error)) return email;
|
|
1584
|
-
if (isDenied(error) && !isServiceDisabled(error)) throw new PlayServiceAccountError("project-access-denied", [
|
|
1585
|
-
`This Google Account may not create service accounts in ${projectId}.`,
|
|
1586
|
-
error.apiMessage || "Permission denied.",
|
|
1587
|
-
"Pick a project you own, or ask for the Service Account Admin role."
|
|
1588
|
-
].join("\n"), { cause: error });
|
|
1589
|
-
throw error;
|
|
1590
|
-
}
|
|
1591
|
-
};
|
|
1592
|
-
/**
|
|
1593
|
-
* Makes `email` a Play Console user that may release `packageName`, keeping
|
|
1594
|
-
* any permission it has: the user and the app's grant are created, or the
|
|
1595
|
-
* grant gains the release permissions.
|
|
1596
|
-
*/
|
|
1597
|
-
const grantPlayAccess = async ({ google, developerId, email, packageName }) => {
|
|
1598
|
-
const developer = `${PUBLISHER_API}/developers/${developerId}`;
|
|
1599
|
-
const user = `${developer}/users/${encodeURIComponent(email)}`;
|
|
1600
|
-
try {
|
|
1601
|
-
await google("Adding the Play Console user", "POST", `${developer}/users`, {
|
|
1602
|
-
name: `developers/${developerId}/users/${email}`,
|
|
1603
|
-
email
|
|
1604
|
-
});
|
|
1605
|
-
} catch (error) {
|
|
1606
|
-
if (isDenied(error)) throw notPlayAdmin(developerId, error);
|
|
1607
|
-
if (!isConflict(error)) throw error;
|
|
1608
|
-
}
|
|
1609
|
-
try {
|
|
1610
|
-
await google("Granting access to the app", "POST", `${user}/grants`, {
|
|
1611
|
-
name: `developers/${developerId}/users/${email}/grants/${packageName}`,
|
|
1612
|
-
packageName,
|
|
1613
|
-
appLevelPermissions: APP_PERMISSIONS
|
|
1614
|
-
});
|
|
1615
|
-
return;
|
|
1616
|
-
} catch (error) {
|
|
1617
|
-
if (isNotFound(error)) throw appNotFound(packageName, developerId, error);
|
|
1618
|
-
if (isDenied(error)) throw notPlayAdmin(developerId, error);
|
|
1619
|
-
if (!isConflict(error)) throw error;
|
|
1620
|
-
}
|
|
1621
|
-
const granted = await findGrant({
|
|
1622
|
-
google,
|
|
1623
|
-
developer,
|
|
1624
|
-
email,
|
|
1625
|
-
packageName
|
|
1626
|
-
});
|
|
1627
|
-
const missing = APP_PERMISSIONS.filter((permission) => !granted.includes(permission));
|
|
1628
|
-
if (missing.length === 0) return;
|
|
1629
|
-
await google("Granting access to the app", "PATCH", `${user}/grants/${encodeURIComponent(packageName)}?updateMask=appLevelPermissions`, { appLevelPermissions: [...granted, ...missing] });
|
|
1630
|
-
};
|
|
1631
|
-
/** The app permissions `email` holds on `packageName`, from the user list. */
|
|
1632
|
-
const findGrant = async ({ google, developer, email, packageName }) => {
|
|
1633
|
-
let pageToken;
|
|
1634
|
-
do {
|
|
1635
|
-
const page = await google("Listing the Play Console users", "GET", `${developer}/users?${new URLSearchParams({
|
|
1636
|
-
pageSize: "100",
|
|
1637
|
-
...pageToken ? { pageToken } : {}
|
|
1638
|
-
})}`);
|
|
1639
|
-
const found = page.users?.find((candidate) => candidate.email === email);
|
|
1640
|
-
if (found) return found.grants?.find((grant) => grant.packageName === packageName)?.appLevelPermissions ?? [];
|
|
1641
|
-
pageToken = page.nextPageToken || void 0;
|
|
1642
|
-
} while (pageToken);
|
|
1643
|
-
return [];
|
|
1644
|
-
};
|
|
1645
|
-
/** A new JSON key of the service account, checked and masked in the CLI's output. */
|
|
1646
|
-
const createKey = async ({ google, project, email, sleep }) => {
|
|
1647
|
-
const { projectId } = project;
|
|
1648
|
-
let key;
|
|
1649
|
-
try {
|
|
1650
|
-
key = await whilePropagating({
|
|
1651
|
-
project,
|
|
1652
|
-
sleep,
|
|
1653
|
-
notFound: true,
|
|
1654
|
-
run: () => google("Creating the key", "POST", `${IAM_API}/projects/${projectId}/serviceAccounts/${email}/keys`, {
|
|
1655
|
-
privateKeyType: "TYPE_GOOGLE_CREDENTIALS_FILE",
|
|
1656
|
-
keyAlgorithm: "KEY_ALG_RSA_2048"
|
|
1657
|
-
})
|
|
1658
|
-
});
|
|
1659
|
-
} catch (error) {
|
|
1660
|
-
if (error instanceof GoogleApiError && (error.violations.includes(KEY_CREATION_CONSTRAINT) || /disableServiceAccountKeyCreation/u.test(error.apiMessage))) throw new PlayServiceAccountError("key-creation-disabled", [
|
|
1661
|
-
`iam.disableServiceAccountKeyCreation forbids keys in ${projectId}.`,
|
|
1662
|
-
"Ask an organization policy admin to allow keys for this project,",
|
|
1663
|
-
"or run this again with a project outside the organization."
|
|
1664
|
-
].join("\n"), { cause: error });
|
|
1665
|
-
throw error;
|
|
1666
|
-
}
|
|
1667
|
-
if (!key.name || !key.privateKeyData) throw new Error("Google Cloud created the key without its JSON file.");
|
|
1668
|
-
(0, _hot_updater_cli_tools.registerSecretValue)(key.privateKeyData);
|
|
1669
|
-
const json = Buffer.from(key.privateKeyData, "base64").toString("utf-8");
|
|
1670
|
-
(0, _hot_updater_cli_tools.registerSecretValue)(json);
|
|
1671
|
-
let parsed;
|
|
1672
|
-
try {
|
|
1673
|
-
parsed = JSON.parse(json);
|
|
1674
|
-
} catch {
|
|
1675
|
-
parsed = {};
|
|
1676
|
-
}
|
|
1677
|
-
if (typeof parsed.private_key !== "string") {
|
|
1678
|
-
await google("Deleting the key", "DELETE", `${IAM_API}/${key.name}`).catch(() => {});
|
|
1679
|
-
throw new Error("Google Cloud created a key that is no JSON key file.");
|
|
1680
|
-
}
|
|
1681
|
-
(0, _hot_updater_cli_tools.registerSecretValue)(parsed.private_key);
|
|
1682
|
-
return {
|
|
1683
|
-
json,
|
|
1684
|
-
name: key.name,
|
|
1685
|
-
keyId: key.name.split("/").pop()
|
|
1686
|
-
};
|
|
1687
|
-
};
|
|
1688
|
-
//#endregion
|
|
1689
|
-
//#region src/playServiceAccount.ts
|
|
1690
|
-
/**
|
|
1691
|
-
* Hot Updater's Google OAuth client, a "Desktop app" client the sign-in
|
|
1692
|
-
* opens Google's consent screen for. Empty in a build that has none, where
|
|
1693
|
-
* `HOT_UPDATER_GOOGLE_OAUTH_CLIENT_ID` and `_SECRET` name one.
|
|
1694
|
-
*/
|
|
1695
|
-
const HOT_UPDATER_GOOGLE_OAUTH_CLIENT = {
|
|
1696
|
-
clientId: "",
|
|
1697
|
-
clientSecret: ""
|
|
1698
|
-
};
|
|
1699
|
-
/**
|
|
1700
|
-
* Hot Updater's issuer, the one place that picks how it is done: Google's
|
|
1701
|
-
* OAuth for installed apps, then the Cloud Resource Manager, Service Usage,
|
|
1702
|
-
* IAM, and Play Developer APIs. Another implementation of
|
|
1703
|
-
* `IssuePlayServiceAccount` replaces it here without touching its callers.
|
|
1704
|
-
*/
|
|
1705
|
-
const issuePlayServiceAccount = (request) => createGoogleKeyIssuer()({
|
|
1706
|
-
...request,
|
|
1707
|
-
oauthClient: request.oauthClient ?? HOT_UPDATER_GOOGLE_OAUTH_CLIENT
|
|
1708
|
-
});
|
|
1709
1582
|
//#endregion
|
|
1710
|
-
exports.
|
|
1711
|
-
exports.HOT_UPDATER_GOOGLE_OAUTH_CLIENT = HOT_UPDATER_GOOGLE_OAUTH_CLIENT;
|
|
1712
|
-
exports.PLAY_CONSOLE_URL = PLAY_CONSOLE_URL;
|
|
1713
|
-
exports.PLAY_SERVICE_ACCOUNT_ID = PLAY_SERVICE_ACCOUNT_ID;
|
|
1714
|
-
exports.PlayServiceAccountError = PlayServiceAccountError;
|
|
1583
|
+
exports.PLAY_TRACKS = PLAY_TRACKS;
|
|
1715
1584
|
exports.PlayVersionCodeUsedError = PlayVersionCodeUsedError;
|
|
1716
1585
|
exports.assertPlaySigned = assertPlaySigned;
|
|
1717
1586
|
exports.buildAndroid = buildAndroid;
|
|
1587
|
+
exports.checkPlayAccess = checkPlayAccess;
|
|
1718
1588
|
exports.enrichNativeBuildAndroidScheme = enrichNativeBuildAndroidScheme;
|
|
1719
1589
|
exports.extractBuiltInBundle = extractBuiltInBundle;
|
|
1720
1590
|
exports.findPlayInternalRelease = findPlayInternalRelease;
|
|
1721
|
-
exports.
|
|
1591
|
+
exports.findSandboxGradleBlocker = findSandboxGradleBlocker;
|
|
1592
|
+
exports.installOnAndroidDevice = installOnAndroidDevice;
|
|
1593
|
+
exports.listAdbDevices = listAdbDevices;
|
|
1594
|
+
exports.playConsoleInviteUrl = playConsoleInviteUrl;
|
|
1595
|
+
exports.playTestingUrl = playTestingUrl;
|
|
1722
1596
|
exports.readBuiltApp = readBuiltApp;
|
|
1723
1597
|
exports.readBuiltPackageName = readBuiltPackageName;
|
|
1724
1598
|
exports.readBuiltVersionCode = readBuiltVersionCode;
|
|
1599
|
+
exports.readPlayHighestVersionCode = readPlayHighestVersionCode;
|
|
1600
|
+
exports.readPlayTrackRelease = readPlayTrackRelease;
|
|
1725
1601
|
exports.resolvePlayUploadServiceAccount = resolvePlayUploadServiceAccount;
|
|
1602
|
+
exports.selectAdbDevice = selectAdbDevice;
|
|
1726
1603
|
exports.uploadToPlay = uploadToPlay;
|