@hot-updater/android-helper 1.2.0-rc.3 → 1.2.0-rc.30

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 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
- let node_crypto = require("node:crypto");
39
- node_crypto = __toESM(node_crypto, 1);
40
- let node_http = require("node:http");
41
- node_http = __toESM(node_http, 1);
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
- importantLogPatterns: [
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({ tasks, logPrefix, args, env, androidProjectPath, appModuleName }) {
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 gradle = (0, execa.execa)(getGradleWrapper(), gradleArgs, {
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
- logger.stop("Build failed", false);
239
- throw new _hot_updater_cli_tools.BuildFailedError(`Build failed: ${describeFailure(e)}`, {
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 findBuildDirectory({
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,336 @@ 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, "&amp;").replace(/"/gu, "&quot;").replace(/</gu, "&lt;").replace(/>/gu, "&gt;");
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. `tools:replace` wins over
602
+ * a channel the app's manifest sets, as an Expo project's 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 = ({ channel, 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="com.hotupdater.CHANNEL" android:value="${xml(channel)}" tools:replace="android:value" />
614
+ <meta-data android:name="${_hot_updater_protocol_native_artifact.SANDBOX_META_DATA}" android:value="true" />
615
+ <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)}>
616
+ ${filterXml(launcher.filter)}
617
+ <intent-filter>
618
+ <action android:name="android.intent.action.VIEW" />
619
+ <category android:name="android.intent.category.DEFAULT" />
620
+ <category android:name="android.intent.category.BROWSABLE" />
621
+ <data android:scheme="${xml(urlScheme)}" />
622
+ </intent-filter>
623
+ <meta-data android:name="com.hotupdater.sandbox.HOST_ACTIVITY" android:value="${xml(launcher.name)}" />
624
+ <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)}" />`}
625
+ </activity>
626
+ <${launcher.kind} android:name="${xml(launcher.name)}"${optional("targetActivity", launcher.targetActivity)}>
627
+ ${filterXml(launcher.filter, " tools:node=\"remove\"")}${launcher.shortcuts === void 0 ? "" : `\n <meta-data android:name="${SHORTCUTS}" tools:node="remove" />`}
628
+ </${launcher.kind}>
629
+ <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" />
630
+ <provider android:name="com.hotupdater.HotUpdaterSandboxProcess" android:authorities="\${applicationId}.hotupdater.sandbox" android:exported="false" />
631
+ </application>
632
+ </manifest>
633
+ `;
634
+ /** Newest first: the manifest of the task that ran last, under `directory`. */
635
+ const manifestsUnder = (directory) => {
636
+ if (!fs.default.existsSync(directory)) return [];
637
+ 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);
638
+ };
639
+ /** The Gradle task that merges a variant's manifest. */
640
+ const mergeManifestTask = (variant) => `process${variant.charAt(0).toUpperCase()}${variant.slice(1)}MainManifest`;
641
+ /**
642
+ * The manifest the merge task of `variant` wrote: AGP 7 and 8 keep it under
643
+ * `build/intermediates/merged_manifest`, in a directory per variant.
644
+ */
645
+ const readMergedManifest = ({ androidProjectPath, appModuleName, variant }) => {
646
+ const variantDirectory = `${variant.charAt(0).toLowerCase()}${variant.slice(1)}`;
647
+ const intermediates = path.default.join(androidProjectPath, appModuleName, "build/intermediates");
648
+ const [manifest] = ["merged_manifest", "merged_manifests"].flatMap((name) => manifestsUnder(path.default.join(intermediates, name, variantDirectory)));
649
+ 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.`);
650
+ return fs.default.readFileSync(manifest, "utf-8");
651
+ };
652
+ //#endregion
653
+ //#region src/utils/sandboxGradle.ts
654
+ const UNSUPPORTED_DSL = `Sandbox builds don't support AGP 9's default DSL yet.
655
+ Set android.newDsl=false in android/gradle.properties.`;
656
+ /** The message when the build type has a manifest the overlay would replace. */
657
+ const ownManifest = (manifest) => `A sandbox build can't merge with ${manifest}.\nMove what it declares to src/main/AndroidManifest.xml.`;
658
+ /** The message when no project compiled the SDK from source, which a dev server needs. */
659
+ const PREBUILT_SDK = `This app takes @hot-updater/react-native as a prebuilt AAR, and a sandbox build compiles the SDK from source.
660
+ Add the SDK's autolinked project to this build instead of the AAR.`;
661
+ /** Text as a single-quoted Groovy string. */
662
+ const groovyString = (text) => `'${text.replace(/\\/gu, "\\\\").replace(/'/gu, "\\'").replace(/\n/gu, "\\n")}'`;
663
+ /**
664
+ * The init script of one sandbox build, so no project file changes: on the app
665
+ * module, it appends the sandbox's suffix to defaultConfig, where AGP puts any
666
+ * flavor's and build type's after it, and adds `overlay` to the variant's build
667
+ * type. It runs in `finalizeDsl`, after the project's own settings.
668
+ */
669
+ const sandboxInitScript = ({ appModuleName, variant, overlay, minVersionCode }) => `// Written by hot-updater for one sandbox build.
670
+ def appModule = ${groovyString(`:${appModuleName}`)}
671
+ def variant = ${groovyString(variant.toLowerCase())}
672
+ def overlay = new File(${groovyString(overlay)})
673
+ def minVersionCode = ${minVersionCode ?? "null"}
674
+ allprojects { project ->
675
+ if (project.path != appModule) return
676
+ // In this build alone: an init script also runs for React Native's included
677
+ // Gradle plugin. The SDK's sandbox script sets this on the project it compiles.
678
+ gradle.taskGraph.whenReady {
679
+ if (!gradle.rootProject.ext.has('hotUpdaterSandboxSdkProject')) {
680
+ throw new GradleException(${groovyString(PREBUILT_SDK)})
681
+ }
682
+ }
683
+ project.plugins.withId('com.android.application') {
684
+ def components = project.extensions.getByName('androidComponents')
685
+ if (components.pluginVersion.major >= 9 && project.findProperty('android.newDsl')?.toString() != 'false') {
686
+ throw new GradleException(${groovyString(UNSUPPORTED_DSL)})
687
+ }
688
+ components.finalizeDsl { dsl ->
689
+ def buildType = dsl.buildTypes.collect { it.name }
690
+ .findAll { variant.endsWith(it.toLowerCase()) }
691
+ .max { it.length() }
692
+ if (buildType == null) {
693
+ throw new GradleException("No build type of \${project.path} builds variant \${variant}.")
694
+ }
695
+ def manifest = dsl.sourceSets.getByName(buildType).manifest
696
+ def own = manifest.srcFile
697
+ if (own.exists()) {
698
+ throw new GradleException(${groovyString(ownManifest("@MANIFEST@"))}.replace('@MANIFEST@', 'android/' + project.rootDir.toPath().relativize(own.toPath())))
699
+ }
700
+ dsl.defaultConfig.applicationIdSuffix = (dsl.defaultConfig.applicationIdSuffix ?: '') + ${groovyString(_hot_updater_protocol_native_artifact.SANDBOX_APPLICATION_ID_SUFFIX)}
701
+ manifest.srcFile(overlay)
702
+ if (minVersionCode != null) {
703
+ dsl.defaultConfig.versionCode = Math.max(dsl.defaultConfig.versionCode ?: 0, minVersionCode)
704
+ dsl.productFlavors.each { flavor ->
705
+ if (flavor.versionCode != null) flavor.versionCode = Math.max(flavor.versionCode, minVersionCode)
706
+ }
707
+ }
708
+ }
709
+ }
710
+ }
711
+ `;
712
+ /**
713
+ * Runs `build` with the Gradle arguments of a scheme: none for a normal one. A
714
+ * sandbox scheme's attach the SDK's sandbox layer and name the init script,
715
+ * written outside the project with its manifest overlay, and removed after.
716
+ * Kotlin compiles from scratch, since the sandbox layer's sources come and go.
717
+ * `readEffectiveManifest` is the variant's merged manifest before the overlay,
718
+ * which the overlay takes the launcher from.
719
+ */
720
+ const withSandboxGradleArgs = async (scheme, readEffectiveManifest, build, { minVersionCode } = {}) => {
721
+ if (!scheme.sandbox) return build([]);
722
+ 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.`);
723
+ const effectiveManifest = await readEffectiveManifest();
724
+ const launcher = resolveSandboxLauncher(effectiveManifest);
725
+ const urlScheme = scheme.sandboxUrlScheme ?? (0, _hot_updater_protocol_native_artifact.sandboxUrlSchemeOf)(scheme.packageName);
726
+ 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.`);
727
+ const directory = await fs.default.promises.mkdtemp(path.default.join(os.default.tmpdir(), "hot-updater-sandbox-"));
728
+ try {
729
+ const overlay = path.default.join(directory, "AndroidManifest.xml");
730
+ const initScript = path.default.join(directory, "sandbox.init.gradle");
731
+ await fs.default.promises.writeFile(overlay, sandboxManifestOverlay({
732
+ channel: (0, _hot_updater_protocol_native_artifact.sandboxChannelOf)(scheme.hotUpdaterSchemeName),
733
+ urlScheme,
734
+ launcher
735
+ }));
736
+ await fs.default.promises.writeFile(initScript, sandboxInitScript({
737
+ appModuleName: scheme.appModuleName,
738
+ variant: scheme.variant,
739
+ overlay,
740
+ ...minVersionCode === void 0 ? {} : { minVersionCode }
741
+ }));
742
+ return await build([
743
+ "--init-script",
744
+ initScript,
745
+ `-PhotUpdaterSandbox=${scheme.hotUpdaterSchemeName}`,
746
+ "-Pkotlin.incremental=false"
747
+ ]);
748
+ } finally {
749
+ await fs.default.promises.rm(directory, {
750
+ recursive: true,
751
+ force: true
752
+ });
753
+ }
754
+ };
755
+ /** The major version of the Android Gradle Plugin the project pins, or null. */
756
+ const readAgpMajor = (androidProjectPath) => {
757
+ 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");
758
+ const pinned = /com\.android\.tools\.build:gradle:(\d+)/u.exec(rootBuild);
759
+ if (pinned) return Number(pinned[1]);
760
+ try {
761
+ const manifest = (0, module$1.createRequire)(path.default.join(androidProjectPath, "package.json")).resolve("react-native/package.json");
762
+ const catalog = fs.default.readFileSync(path.default.join(path.default.dirname(manifest), "gradle/libs.versions.toml"), "utf-8");
763
+ const agp = /^\s*agp\s*=\s*"(\d+)/mu.exec(catalog);
764
+ return agp ? Number(agp[1]) : null;
765
+ } catch {
766
+ return null;
767
+ }
768
+ };
769
+ /**
770
+ * Why a sandbox build of a scheme can't work, read from the project's files
771
+ * before anything is built, or null. The init script checks again, with what
772
+ * Gradle actually resolved.
773
+ */
774
+ const findSandboxGradleBlocker = ({ variant = "Release", appModuleName = "app" }) => {
775
+ const androidProjectPath = path.default.join((0, _hot_updater_cli_tools.getCwd)(), "android");
776
+ if (!fs.default.existsSync(androidProjectPath)) return null;
777
+ const properties = path.default.join(androidProjectPath, "gradle.properties");
778
+ const newDsl = fs.default.existsSync(properties) ? /^\s*android\.newDsl\s*=\s*(\S+)/mu.exec(fs.default.readFileSync(properties, "utf-8"))?.[1] : void 0;
779
+ if (newDsl === "true" || newDsl === void 0 && (readAgpMajor(androidProjectPath) ?? 0) >= 9) return UNSUPPORTED_DSL;
780
+ const buildType = /([A-Z]?[a-z0-9]+)$/u.exec(variant)?.[1]?.toLowerCase();
781
+ const manifest = `${appModuleName}/src/${buildType}/AndroidManifest.xml`;
782
+ return buildType && fs.default.existsSync(path.default.join(androidProjectPath, manifest)) ? ownManifest(`android/${manifest}`) : null;
783
+ };
784
+ //#endregion
544
785
  //#region src/buildAndroid.ts
545
- const buildAndroid = async ({ schemeConfig, minBundleId = (0, _hot_updater_cli_tools.createMinBundleId)(), credentials }) => {
786
+ const buildAndroid = async ({ schemeConfig, minBundleId = (0, _hot_updater_cli_tools.createMinBundleId)(), credentials, logHeader, minVersionCode }) => {
546
787
  const androidProjectPath = path.default.join((0, _hot_updater_cli_tools.getCwd)(), "android");
547
- const result = await runGradle({
548
- args: { extraParams: [`-PMIN_BUNDLE_ID=${minBundleId}`] },
549
- env: await resolveGradleSigningEnv({
550
- schemeConfig,
551
- credentials
552
- }),
788
+ const env = await resolveGradleSigningEnv({
789
+ schemeConfig,
790
+ credentials
791
+ });
792
+ const result = await withSandboxGradleArgs(schemeConfig, async () => {
793
+ await runGradleTasks({
794
+ args: { extraParams: [`-PMIN_BUNDLE_ID=${minBundleId}`] },
795
+ env,
796
+ appModuleName: schemeConfig.appModuleName,
797
+ tasks: [mergeManifestTask(schemeConfig.variant)],
798
+ logPrefix: `android-${schemeConfig.hotUpdaterSchemeName}-manifest`,
799
+ androidProjectPath,
800
+ logHeader
801
+ });
802
+ return readMergedManifest({
803
+ androidProjectPath,
804
+ appModuleName: schemeConfig.appModuleName,
805
+ variant: schemeConfig.variant
806
+ });
807
+ }, (sandboxArgs) => runGradle({
808
+ args: { extraParams: [`-PMIN_BUNDLE_ID=${minBundleId}`, ...sandboxArgs] },
809
+ env,
553
810
  appModuleName: schemeConfig.appModuleName,
554
811
  tasks: schemeConfig.aab ? [`bundle${schemeConfig.variant}`] : [`assemble${schemeConfig.variant}`],
555
812
  logPrefix: `android-${schemeConfig.hotUpdaterSchemeName}-build`,
556
- androidProjectPath
557
- });
813
+ androidProjectPath,
814
+ logHeader
815
+ }), minVersionCode === void 0 ? {} : { minVersionCode });
558
816
  return {
559
817
  ...result,
560
818
  builtApp: await readBuiltApp({
@@ -564,6 +822,105 @@ const buildAndroid = async ({ schemeConfig, minBundleId = (0, _hot_updater_cli_t
564
822
  };
565
823
  };
566
824
  //#endregion
825
+ //#region src/device.ts
826
+ /** The SDK's adb, or the one on the PATH without an SDK in the environment. */
827
+ const adbPath = () => {
828
+ const sdk = process.env["ANDROID_HOME"] || process.env["ANDROID_SDK_ROOT"];
829
+ const executable = process.platform.startsWith("win") ? "adb.exe" : "adb";
830
+ const fromSdk = sdk && path.default.join(sdk, "platform-tools", executable);
831
+ return fromSdk && fs.default.existsSync(fromSdk) ? fromSdk : executable;
832
+ };
833
+ const adb = async (args) => {
834
+ try {
835
+ return (await (0, execa.execa)(adbPath(), args)).stdout;
836
+ } catch (error) {
837
+ const { code, stderr, stdout, shortMessage } = error;
838
+ if (code === "ENOENT") throw new Error("adb isn't installed.\nInstall Android platform-tools, or set ANDROID_HOME.");
839
+ throw new Error(stderr?.trim() || stdout?.trim() || shortMessage || String(error));
840
+ }
841
+ };
842
+ /** What `adb devices` lists. */
843
+ const listAdbDevices = async () => (await adb(["devices"])).split("\n").slice(1).map((line) => line.trim().split(/\s+/u)).flatMap(([serial, state]) => serial && state ? [{
844
+ serial,
845
+ state
846
+ }] : []);
847
+ /**
848
+ * The device to install on: `serial`, as adb's own `ANDROID_SERIAL` names it
849
+ * too, or else the only one that takes commands.
850
+ */
851
+ const selectAdbDevice = (devices, serial = process.env["ANDROID_SERIAL"] || void 0) => {
852
+ if (serial !== void 0) {
853
+ const device = devices.find((candidate) => candidate.serial === serial);
854
+ if (device === void 0) throw new Error(`${serial} isn't connected.\nList them: adb devices`);
855
+ if (device.state !== "device") throw new Error(`${serial} is ${device.state}.\nList them: adb devices`);
856
+ return device;
857
+ }
858
+ const ready = devices.filter(({ state }) => state === "device");
859
+ const [only] = ready;
860
+ 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.");
861
+ if (ready.length > 1) throw new Error([
862
+ `${ready.length} Android devices are connected:`,
863
+ ...ready.map(({ serial }) => ` ${serial}`),
864
+ "Pick one with --device <serial>."
865
+ ].join("\n"));
866
+ return only;
867
+ };
868
+ /** A failure adb reports for an install another install of the app stands in the way of. */
869
+ const NEEDS_UNINSTALL = /^INSTALL_FAILED_(UPDATE_INCOMPATIBLE|VERSION_DOWNGRADE)\b/u;
870
+ const LAUNCHER_CATEGORY = "android.intent.category.LAUNCHER";
871
+ /** An application ID's form, checked before it reaches the device's shell. */
872
+ const APP_ID = /^[A-Za-z][A-Za-z0-9_.]*$/u;
873
+ /** `<application ID>/<activity>`, as `resolve-activity --brief` prints it. */
874
+ const ACTIVITY = /^[A-Za-z0-9_.]+\/[A-Za-z0-9_.$]+$/u;
875
+ /**
876
+ * Installs an APK on a device, and opens its launcher activity. `appId` is
877
+ * the APK's own application ID, whatever suffix its build gave it.
878
+ */
879
+ const installOnAndroidDevice = async ({ serial, apkPath, appId }) => {
880
+ if (!APP_ID.test(appId)) throw new Error(`The APK's application ID isn't valid: ${appId}`);
881
+ try {
882
+ await adb([
883
+ "-s",
884
+ serial,
885
+ "install",
886
+ "-r",
887
+ apkPath
888
+ ]);
889
+ } catch (error) {
890
+ const message = error instanceof Error ? error.message : String(error);
891
+ const failure = /Failure \[([^\]]+)\]/u.exec(message)?.[1] ?? message;
892
+ 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}`);
893
+ }
894
+ const activity = (await adb([
895
+ "-s",
896
+ serial,
897
+ "shell",
898
+ "cmd",
899
+ "package",
900
+ "resolve-activity",
901
+ "--brief",
902
+ "-c",
903
+ LAUNCHER_CATEGORY,
904
+ appId
905
+ ])).trim().split("\n").at(-1)?.trim();
906
+ if (activity === void 0 || !ACTIVITY.test(activity)) throw new Error(`${appId} is installed, and has no launcher activity to open.`);
907
+ const started = await adb([
908
+ "-s",
909
+ serial,
910
+ "shell",
911
+ "am",
912
+ "start",
913
+ "-a",
914
+ "android.intent.action.MAIN",
915
+ "-c",
916
+ LAUNCHER_CATEGORY,
917
+ "-n",
918
+ `'${activity}'`
919
+ ]);
920
+ const error = /^Error: .*$/mu.exec(started)?.[0];
921
+ if (error !== void 0) throw new Error(`${appId} is installed, and didn't open. ${error}`);
922
+ };
923
+ //#endregion
567
924
  //#region src/uploadToPlay.ts
568
925
  const API_URL = "https://androidpublisher.googleapis.com";
569
926
  /** Where Google serves resumable upload sessions, as its docs show both. */
@@ -667,7 +1024,7 @@ const explain = (error, packageName) => {
667
1024
  if (status === 401 || /does not have permission/i.test(apiMessage)) return new Error([
668
1025
  `The Play service account can't release ${packageName}.`,
669
1026
  "Invite its email in Play Console (Users and permissions) to release to",
670
- "testing tracks, and enable the Google Play Android Developer API."
1027
+ "testing tracks (Release to production for production), and enable the Google Play Android Developer API."
671
1028
  ].join("\n"), { cause: error });
672
1029
  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
1030
  if (/version code .*(already been used|already used)/i.test(apiMessage)) return new PlayVersionCodeUsedError({ cause: error });
@@ -676,7 +1033,8 @@ const explain = (error, packageName) => {
676
1033
  /**
677
1034
  * Requests to the Google Play Developer API for `packageName`, as the
678
1035
  * service account: each carries an access token, exchanged for a signed
679
- * assertion and replaced well before it expires.
1036
+ * assertion and replaced well before it expires. `checkPlayAccess`
1037
+ * checks a key's access with it too.
680
1038
  */
681
1039
  const createPlayClient = ({ json, packageName, fetch }) => {
682
1040
  const account = readServiceAccount(json);
@@ -725,11 +1083,69 @@ const createPlayClient = ({ json, packageName, fetch }) => {
725
1083
  };
726
1084
  };
727
1085
  /**
728
- * Whether Google Play's internal testing track already releases the
729
- * `.aab`'s version code, as when a reused native build was uploaded
730
- * before. It reads the track in an edit it then deletes, changing nothing.
1086
+ * Play Console's page that invites `email` as a user. `_` stands for the
1087
+ * developer account the browser is signed in to, so no ID is needed.
1088
+ */
1089
+ const playConsoleInviteUrl = (email) => `https://play.google.com/console/u/0/developers/_/users-and-permissions?invite=${encodeURIComponent(email)}`;
1090
+ const readClientEmail = (json) => {
1091
+ try {
1092
+ const { client_email } = JSON.parse(json);
1093
+ return typeof client_email === "string" ? client_email : "";
1094
+ } catch {
1095
+ return "";
1096
+ }
1097
+ };
1098
+ /**
1099
+ * Checks once whether the service account's key reaches `packageName`: it
1100
+ * opens an edit of the app and deletes it again, which changes nothing.
1101
+ * Throws only for what says nothing about access, such as a network error.
1102
+ */
1103
+ const checkPlayAccess = async ({ serviceAccount: { json }, packageName, fetch = globalThis.fetch }) => {
1104
+ const email = readClientEmail(json);
1105
+ const refused = (error) => ({
1106
+ status: "refused",
1107
+ email,
1108
+ reason: error instanceof Error ? error.message : String(error)
1109
+ });
1110
+ let play;
1111
+ try {
1112
+ play = createPlayClient({
1113
+ json,
1114
+ packageName,
1115
+ fetch
1116
+ });
1117
+ } catch (error) {
1118
+ return refused(error);
1119
+ }
1120
+ try {
1121
+ await play.authorization();
1122
+ } catch (error) {
1123
+ if (error instanceof TypeError) throw error;
1124
+ return refused(error);
1125
+ }
1126
+ const edits = `${API_URL}${play.app}/edits`;
1127
+ try {
1128
+ const edit = await play.request(`Opening an edit of ${packageName}`, "POST", edits, {});
1129
+ if (edit?.id) await play.request("Deleting the edit", "DELETE", `${edits}/${encodeURIComponent(edit.id)}`).catch(() => {});
1130
+ return { status: "ready" };
1131
+ } catch (error) {
1132
+ if (error instanceof GooglePlayError) {
1133
+ if (error.status === 401 || error.status === 403) return {
1134
+ status: "denied",
1135
+ email
1136
+ };
1137
+ if (error.status === 404) return {
1138
+ status: "not-found",
1139
+ email
1140
+ };
1141
+ }
1142
+ throw error;
1143
+ }
1144
+ };
1145
+ /**
1146
+ * Reads the app in an edit it then deletes, changing nothing.
731
1147
  */
732
- const findPlayInternalRelease = async ({ versionCode, packageName, serviceAccount: { json }, fetch = globalThis.fetch }) => {
1148
+ const readInEdit = async ({ packageName, serviceAccount: { json }, fetch }, read) => {
733
1149
  const { app, request } = createPlayClient({
734
1150
  json,
735
1151
  packageName,
@@ -743,8 +1159,7 @@ const findPlayInternalRelease = async ({ versionCode, packageName, serviceAccoun
743
1159
  }
744
1160
  const edit = `${API_URL}${app}/edits/${encodeURIComponent(editId)}`;
745
1161
  try {
746
- const { releases = [] } = await request("Reading the internal track", "GET", `${edit}/tracks/${INTERNAL_TRACK}`);
747
- return releases.some(({ versionCodes = [] }) => versionCodes.includes(String(versionCode)));
1162
+ return await read(request, edit);
748
1163
  } catch (error) {
749
1164
  throw explain(error, packageName);
750
1165
  } finally {
@@ -752,6 +1167,44 @@ const findPlayInternalRelease = async ({ versionCode, packageName, serviceAccoun
752
1167
  }
753
1168
  };
754
1169
  /**
1170
+ * The status of the selected track's release holding `versionCode`, defaulting
1171
+ * to internal testing, such as
1172
+ * `completed` or `draft`, or null when the track doesn't hold it: never
1173
+ * uploaded, or replaced by a newer release, which testers get instead.
1174
+ */
1175
+ const readPlayTrackRelease = ({ versionCode, track = INTERNAL_TRACK, packageName, serviceAccount, fetch = globalThis.fetch }) => readInEdit({
1176
+ packageName,
1177
+ serviceAccount,
1178
+ fetch
1179
+ }, async (request, edit) => {
1180
+ const { releases = [] } = await request(`Reading the ${track} track`, "GET", `${edit}/tracks/${encodeURIComponent(track)}`);
1181
+ const release = releases.find(({ versionCodes = [] }) => versionCodes.includes(String(versionCode)));
1182
+ return release ? release.status ?? "completed" : null;
1183
+ });
1184
+ /**
1185
+ * Whether Google Play's internal testing track already releases the
1186
+ * `.aab`'s version code, as when a reused native build was uploaded before.
1187
+ */
1188
+ const findPlayInternalRelease = async (options) => await readPlayTrackRelease(options) !== null;
1189
+ /**
1190
+ * The highest version code Google Play has taken for the app, on any track,
1191
+ * or null with none: a new `.aab` needs one above it.
1192
+ */
1193
+ const readPlayHighestVersionCode = ({ packageName, serviceAccount, fetch = globalThis.fetch }) => readInEdit({
1194
+ packageName,
1195
+ serviceAccount,
1196
+ fetch
1197
+ }, async (request, edit) => {
1198
+ const { bundles = [] } = await request("Reading the app's bundles", "GET", `${edit}/bundles`);
1199
+ const codes = bundles.flatMap(({ versionCode }) => versionCode ?? []);
1200
+ return codes.length > 0 ? Math.max(...codes) : null;
1201
+ });
1202
+ /**
1203
+ * The link that opts a tester in to the app's testing tracks. A build on the
1204
+ * internal track installs through it, for the testers Play Console lists.
1205
+ */
1206
+ const playTestingUrl = (packageName) => `https://play.google.com/apps/testing/${encodeURIComponent(packageName)}`;
1207
+ /**
755
1208
  * The common name of every Android debug certificate: Android Studio's and
756
1209
  * the Android Gradle plugin's (`CN=Android Debug, O=Android, C=US`), and React
757
1210
  * Native's template `debug.keystore` (`CN=Android Debug, OU=Android,
@@ -779,12 +1232,13 @@ const assertPlaySigned = async (aabPath) => {
779
1232
  ].join("\n"));
780
1233
  };
781
1234
  /**
782
- * Uploads an `.aab` to Google Play's internal testing track with the Google
1235
+ * Uploads or promotes an `.aab` to a Google Play track with the Google
783
1236
  * Play Developer API: it opens an edit, uploads the bundle, releases its
784
- * version code to the internal track, and commits the edit, which it
1237
+ * version code to the selected track, and commits the edit, which it
785
1238
  * deletes again when any step fails. The service account stays in memory.
786
1239
  */
787
- const uploadToPlay = async ({ aabPath, packageName, serviceAccount: { json }, fetch = globalThis.fetch, commitRetryDelayMs = 2e3 }) => {
1240
+ const uploadToPlay = async ({ aabPath, packageName, serviceAccount: { json }, fetch = globalThis.fetch, commitRetryDelayMs = 2e3, track = "internal", rollout = 100, existingVersionCode }) => {
1241
+ 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
1242
  const { app, authorization, request } = createPlayClient({
789
1243
  json,
790
1244
  packageName,
@@ -798,20 +1252,28 @@ const uploadToPlay = async ({ aabPath, packageName, serviceAccount: { json }, fe
798
1252
  }
799
1253
  const edit = `${API_URL}${app}/edits/${encodeURIComponent(editId)}`;
800
1254
  try {
801
- _hot_updater_cli_tools.p.log.info(`Uploading ${packageName}'s .aab to Google Play`);
802
- const versionCode = await uploadBundle({
1255
+ _hot_updater_cli_tools.p.log.info(`${existingVersionCode === void 0 ? "Uploading" : "Promoting"} ${packageName} to Google Play`);
1256
+ const versionCode = existingVersionCode ?? await uploadBundle({
803
1257
  aabPath,
804
1258
  sessionUrl: `${API_URL}/upload${app}/edits/${encodeURIComponent(editId)}/bundles?uploadType=resumable`,
805
1259
  authorization,
806
1260
  fetch
807
1261
  });
1262
+ 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
1263
  const release = async (status) => {
809
- await request("Releasing to the internal track", "PUT", `${edit}/tracks/${INTERNAL_TRACK}`, {
810
- track: INTERNAL_TRACK,
811
- releases: [{
812
- versionCodes: [String(versionCode)],
813
- status
814
- }]
1264
+ const updatedRelease = {
1265
+ ...existingRelease,
1266
+ versionCodes: existingRelease?.versionCodes ?? [String(versionCode)],
1267
+ status
1268
+ };
1269
+ if (status === "inProgress") updatedRelease.userFraction = rollout / 100;
1270
+ else {
1271
+ delete updatedRelease.userFraction;
1272
+ delete updatedRelease.countryTargeting;
1273
+ }
1274
+ await request(`Releasing to the ${track} track`, "PUT", `${edit}/tracks/${track}`, {
1275
+ track,
1276
+ releases: [updatedRelease]
815
1277
  });
816
1278
  await commit({
817
1279
  request,
@@ -820,10 +1282,11 @@ const uploadToPlay = async ({ aabPath, packageName, serviceAccount: { json }, fe
820
1282
  });
821
1283
  };
822
1284
  try {
823
- await release("completed");
1285
+ const status = rollout < 100 ? "inProgress" : "completed";
1286
+ await release(status);
824
1287
  return {
825
1288
  versionCode,
826
- status: "completed"
1289
+ status
827
1290
  };
828
1291
  } catch (error) {
829
1292
  if (!(error instanceof GooglePlayError) || !DRAFT_APP_ERRORS.some((message) => error.apiMessage.includes(message))) throw error;
@@ -855,7 +1318,7 @@ const commit = async ({ request, edit, retryDelayMs }) => {
855
1318
  if (!(error instanceof GooglePlayError) || error.status >= 500 || error.status === 429) throw new Error([
856
1319
  "Google Play didn't confirm the release.",
857
1320
  error instanceof Error ? error.message : String(error),
858
- "Check internal testing in Play Console before you upload it again."
1321
+ "Check the release in Play Console before you upload it again."
859
1322
  ].join("\n"), { cause: error });
860
1323
  if (error.status !== 400) throw error;
861
1324
  if (!changesNotSentForReview && error.apiMessage.includes(NEEDS_CHANGES_NOT_SENT_FOR_REVIEW)) {
@@ -1094,633 +1557,49 @@ const extractBuiltInBundle = async ({ artifactPath, outputPath }) => {
1094
1557
  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
1558
  };
1096
1559
  //#endregion
1097
- //#region src/google/googleApi.ts
1098
- /** A Google Cloud or Google Play API request that failed, with Google's error. */
1099
- var GoogleApiError = class extends Error {
1100
- status;
1101
- /** Google's canonical status, such as `PERMISSION_DENIED`. */
1102
- apiStatus;
1103
- apiMessage;
1104
- /** The `ErrorInfo` reasons, such as `SERVICE_DISABLED`. */
1105
- reasons;
1106
- /** The `PreconditionFailure` violation types, such as an org policy constraint. */
1107
- violations;
1108
- /** The `ErrorInfo` consumer of a disabled service, such as `projects/123`. */
1109
- consumer;
1110
- constructor(action, status, body = {}) {
1111
- const apiMessage = body.apiMessage ?? "";
1112
- super(`${action} failed (HTTP ${status})${apiMessage ? `: ${apiMessage}` : "."}`);
1113
- this.name = "GoogleApiError";
1114
- this.status = status;
1115
- this.apiStatus = body.apiStatus;
1116
- this.apiMessage = apiMessage;
1117
- this.reasons = body.reasons ?? [];
1118
- this.violations = body.violations ?? [];
1119
- this.consumer = body.consumer;
1560
+ //#region src/playTracks.ts
1561
+ /** Google Play destinations and their API tracks. */
1562
+ const PLAY_TRACKS = {
1563
+ "play-internal": {
1564
+ track: "internal",
1565
+ label: "Play internal",
1566
+ name: "Google Play internal testing"
1567
+ },
1568
+ "play-closed": {
1569
+ track: "alpha",
1570
+ label: "Play closed",
1571
+ name: "Google Play closed testing"
1572
+ },
1573
+ "play-open": {
1574
+ track: "beta",
1575
+ label: "Play open",
1576
+ name: "Google Play open testing"
1577
+ },
1578
+ "play-production": {
1579
+ track: "production",
1580
+ label: "Play production",
1581
+ name: "Google Play production"
1120
1582
  }
1121
1583
  };
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
1584
  //#endregion
1710
- exports.GOOGLE_OAUTH_CLIENT_ENV_NAMES = GOOGLE_OAUTH_CLIENT_ENV_NAMES;
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;
1585
+ exports.PLAY_TRACKS = PLAY_TRACKS;
1715
1586
  exports.PlayVersionCodeUsedError = PlayVersionCodeUsedError;
1716
1587
  exports.assertPlaySigned = assertPlaySigned;
1717
1588
  exports.buildAndroid = buildAndroid;
1589
+ exports.checkPlayAccess = checkPlayAccess;
1718
1590
  exports.enrichNativeBuildAndroidScheme = enrichNativeBuildAndroidScheme;
1719
1591
  exports.extractBuiltInBundle = extractBuiltInBundle;
1720
1592
  exports.findPlayInternalRelease = findPlayInternalRelease;
1721
- exports.issuePlayServiceAccount = issuePlayServiceAccount;
1593
+ exports.findSandboxGradleBlocker = findSandboxGradleBlocker;
1594
+ exports.installOnAndroidDevice = installOnAndroidDevice;
1595
+ exports.listAdbDevices = listAdbDevices;
1596
+ exports.playConsoleInviteUrl = playConsoleInviteUrl;
1597
+ exports.playTestingUrl = playTestingUrl;
1722
1598
  exports.readBuiltApp = readBuiltApp;
1723
1599
  exports.readBuiltPackageName = readBuiltPackageName;
1724
1600
  exports.readBuiltVersionCode = readBuiltVersionCode;
1601
+ exports.readPlayHighestVersionCode = readPlayHighestVersionCode;
1602
+ exports.readPlayTrackRelease = readPlayTrackRelease;
1725
1603
  exports.resolvePlayUploadServiceAccount = resolvePlayUploadServiceAccount;
1604
+ exports.selectAdbDevice = selectAdbDevice;
1726
1605
  exports.uploadToPlay = uploadToPlay;