Compare commits

...
10 Commits
Author SHA1 Message Date
Expo CI 01e3be71aa v24.12.1 2026-10-08 21:49:04 +00:00
SJ Kim 991bbeae8c [eas-cli] Move the #4522 and #4483 changelog entries to their releases (#4576) 2026-10-08 17:43:35 -04:00
SJ Kim 6c342abb97 [eas-cli] Stop a simulator session created after Ctrl+C during create (ENG-27606) (#4522)
* [eas-cli] Log client request events for simulator sessions (ENG-27138)

* [eas-cli] Flush analytics and exit with 130 when Ctrl+C cancels a simulator session request (ENG-27138)

* [eas-cli] Add changelog entry for simulator request events (ENG-27138)

* [eas-cli] Bound the Ctrl+C analytics flush and tighten its tests (ENG-27138)

* [eas-cli] Stop a session created after Ctrl+C during create (ENG-27138)

* [eas-cli] Don't count an HTTP error answer as a failed simulator session request (ENG-27138)

* [eas-cli] Add changelog entry for #4522 (ENG-27606)

* [eas-cli] Keep the simulator request analytics wrapper with its only caller (ENG-27138)

* [eas-cli] Keep a failed Ctrl+C stop test from hanging later simulator tests (ENG-27606)

* [eas-cli] Accept an unsent create request when stopping a session after Ctrl+C
2026-10-08 16:28:09 -04:00
Stanisław Chmiela 1016aa35f3 [build-tools] Skip WDA cache for DeviceLab Runner versions (#4560)
# Why

<img width="487" height="329" alt="Zrzut ekranu 2026-10-7 o 10 29 04" src="https://github.com/user-attachments/assets/a63f0550-bf93-46ed-83c7-187faa2ac20b" />

# How

Skip WDA cache preparation for detected Runner versions 1.1.28 and later.

# Test Plan

CI should pass.
2026-10-08 14:16:53 +02:00
Stanisław Chmiela ceb8f846c2 [build-tools] Address Android app info review feedback (#4567)
# Why

I merged pull request without noticing review comments. #4514.

# How

Adhered to review comments. Added integration tests using real APK/AAB and real tools, fixed error code.

# Test Plan

CI should pass. Validated locally.
2026-10-08 12:10:43 +02:00
Stanisław Chmiela 53cb3a7263 [build-tools] Add typed Google Play API client (#4515)
* [build-tools] Add authenticated Google Play API client

* [build-tools] Remove Android fixture dependency from client tests

* [build-tools] Add typed Google Play API methods with separate OAuth transport

* [build-tools] Simplify Google Play client and remove retry changes

* [build-tools] Improve Google Play client error details

* [build-tools] Load Google Play tokens with service account keys

* [build-tools] Extract Google Play assertion helper

* [build-tools] Move token creation into GooglePlayAuthUtils

* [build-tools] Make assertion helper private and capitalize utility filename

* [build-tools] Remove upload support from Google Play client PR

* [build-tools] Improve Google Play client schema spacing

* [build-tools] Reuse Google Play release schema
2026-10-08 10:39:56 +02:00
Stanisław Chmiela 09188ab271 [build-tools] Add typed Google Play OAuth API client (#4542)
* [build-tools] Add typed Google Play OAuth API client

* [build-tools] Align Google Play OAuth errors and response parsing

* [build-tools] Include Google Play OAuth error diagnostics

* [build-tools] Keep OAuth diagnostics without response secrets
2026-10-08 10:30:18 +02:00
Stanisław Chmiela c4ffc1605e [build-tools] Add Android artifact inspection function (#4514)
* [build-tools] Add Android artifact inspection function

* [build-tools] Use Android tools to inspect app artifacts

* [build-tools] Read Android info from downloaded binary paths

* [build-tools] Detect Android type before reading package name

* [build-tools] Read APK package name with aapt2 packagename

* [build-tools] Keep Android package readers explicit

* [build-tools] Pass step cancellation to Android app inspection

* [build-tools] Simplify Android type dispatch and ZIP lookup

* [build-tools] use caller cancellation for Android artifact inspection

* [build-tools] Run checks after rebasing Android artifact inspection
2026-10-08 10:23:15 +02:00
Expo CI d90f022966 bump STAGING and PRODUCTION to 24.12.0 in cli-versions.json 2026-10-07 21:20:27 +00:00
Expo CI 8b8362e4ae update CHANGELOG.md for v24.12.0 2026-10-07 21:17:55 +00:00
26 changed files with 1466 additions and 282 deletions

No files matched your search

+12 -1
View File
@@ -8,6 +8,16 @@ This is the log of notable changes to EAS CLI and related packages.
### 🎉 New features
### 🐛 Bug fixes
- [eas-cli] Stop a simulator session that the server creates after Ctrl+C lands during `eas simulator` create. ([#4522](https://github.com/expo/eas-cli/pull/4522) by [@sjkim-expo](https://github.com/sjkim-expo))
### 🧹 Chores
## [24.12.0](https://github.com/expo/eas-cli/releases/tag/v24.12.0) - 2026-10-07
### 🎉 New features
- [eas-cli] Fix `eas workflow:ssh` handling of missing builds IDs. ([#4529](https://github.com/expo/eas-cli/pull/4529) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
- [build-tools] Upload the embedded bundle from custom builds that use `eas/build`. ([#4494](https://github.com/expo/eas-cli/pull/4494) by [@gwdp](https://github.com/gwdp))
- [build-tools] Add the `eas/upload_embedded_bundle` step for custom build configs. ([#4494](https://github.com/expo/eas-cli/pull/4494) by [@gwdp](https://github.com/gwdp))
@@ -21,6 +31,8 @@ This is the log of notable changes to EAS CLI and related packages.
### 🧹 Chores
- [eas-cli] Log analytics events when an `eas simulator` session request is sent, cancelled, or fails before the server answers. ([#4483](https://github.com/expo/eas-cli/pull/4483) by [@sjkim-expo](https://github.com/sjkim-expo))
## [24.11.0](https://github.com/expo/eas-cli/releases/tag/v24.11.0) - 2026-10-05
### 🎉 New features
@@ -38,7 +50,6 @@ This is the log of notable changes to EAS CLI and related packages.
### 🧹 Chores
- [eas-cli] Log analytics events when an `eas simulator` session request is sent, cancelled, or fails before the server answers. ([#4483](https://github.com/expo/eas-cli/pull/4483) by [@sjkim-expo](https://github.com/sjkim-expo))
- [build-tools] Remove the `eas/start_agent_device_remote_session` step; agent-device sessions use `eas/start_agent_device_session`. ([#4518](https://github.com/expo/eas-cli/pull/4518) by [@szdziedzic](https://github.com/szdziedzic))
- [eas-cli] Report `eas-cli` as the request origin, and the coding agent when one is detected, when `eas simulator` creates a session, for analytics. ([#4523](https://github.com/expo/eas-cli/pull/4523) by [@sjkim-expo](https://github.com/sjkim-expo))
+2 -2
View File
@@ -1,4 +1,4 @@
{
"STAGING": "24.11.0",
"PRODUCTION": "24.11.0"
"STAGING": "24.12.0",
"PRODUCTION": "24.12.0"
}
+1 -1
View File
@@ -1,5 +1,5 @@
{
"npmClient": "yarn",
"version": "24.12.0",
"version": "24.12.1",
"$schema": "node_modules/lerna/schemas/lerna-schema.json"
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@expo/build-tools",
"version": "24.12.0",
"version": "24.12.1",
"bugs": "https://github.com/expo/eas-cli/issues",
"license": "BUSL-1.1",
"author": "Expo <[email protected]>",
@@ -27,6 +27,7 @@ import { createLaunchApplicationFunction } from './functions/launchApplication';
import { createPrebuildBuildFunction } from './functions/prebuild';
import { createReadAppConfigBuildFunction } from './functions/readAppConfig';
import { createReadIpaInfoBuildFunction } from './functions/readIpaInfo';
import { createReadAndroidAppInfoBuildFunction } from './functions/readAndroidAppInfo';
import { createReadPackageJsonBuildFunction } from './functions/readPackageJson';
import { createRepackBuildFunction } from './functions/repack';
import { createReportMaestroTestResultsFunction } from './functions/reportMaestroTestResults';
@@ -82,6 +83,7 @@ export function getEasFunctions(ctx: CustomBuildContext): BuildFunction[] {
createInstallNodeModulesBuildFunction(),
createPrebuildBuildFunction(),
createReadIpaInfoBuildFunction(),
createReadAndroidAppInfoBuildFunction(),
createDownloadBuildFunction(ctx),
createInstallBuildFunction(),
createLaunchApplicationFunction(),
@@ -0,0 +1,47 @@
import { UserError } from '@expo/eas-build-job';
import path from 'node:path';
import { createGlobalContextMock } from '../../../__tests__/utils/context';
import { readAndroidArtifactInfoAsync } from '../../utils/android/appArtifact';
import { createReadAndroidAppInfoBuildFunction } from '../readAndroidAppInfo';
jest.unmock('fs');
jest.unmock('node:fs');
jest.unmock('fs/promises');
jest.unmock('node:fs/promises');
jest.unmock('@expo/spawn-async');
const fixturesDirectory = path.join(__dirname, 'fixtures/android-app-info');
it.each(['apk', 'aab'])('reads a real %s and publishes build step outputs', async type => {
const step = createReadAndroidAppInfoBuildFunction().createBuildStepFromFunctionCall(
createGlobalContextMock({
projectTargetDirectory: fixturesDirectory,
staticContextContent: { job: {} },
}),
{ callInputs: { artifact_path: `app.${type}` } }
);
await step.executeAsync();
expect(step.outputById.artifact_type.value).toBe(type);
expect(step.outputById.package_name.value).toBe('com.example.app');
});
it('reports an invalid ZIP as a user error', async () => {
await expect(readAndroidArtifactInfoAsync(__filename)).rejects.toMatchObject({
constructor: UserError,
errorCode: 'EAS_READ_ANDROID_APP_INFO_INVALID_ARTIFACT',
cause: expect.any(Error),
});
});
it.each(['apk', 'aab'])('retains the native tool error for an invalid %s manifest', async type => {
await expect(
readAndroidArtifactInfoAsync(path.join(fixturesDirectory, `invalid-manifest-${type}.zip`))
).rejects.toMatchObject({
constructor: UserError,
errorCode: 'EAS_READ_ANDROID_APP_INFO_INVALID_MANIFEST',
cause: expect.any(Error),
});
});
@@ -463,114 +463,127 @@ describe('createInstallMaestroBuildFunction', () => {
}
});
it('installs the prebuilt WDA cache for each available iOS runtime', async () => {
const homeDirectory = await fs.promises.mkdtemp(
path.join(os.tmpdir(), 'install-maestro-test-')
);
mockedSpawn.mockImplementation((async (command: string, args: string[]) => {
if (command === 'maestro-runner') {
return { stdout: 'maestro-runner 1.2.3\n' };
}
if (command === 'xcrun') {
return {
stdout: JSON.stringify({
runtimes: [
{
identifier: 'com.apple.CoreSimulator.SimRuntime.iOS-18-3',
isAvailable: true,
version: '18.3.1',
},
{
identifier: 'com.apple.CoreSimulator.SimRuntime.iOS-26-0',
isAvailable: true,
version: '26.0',
},
{
identifier: 'com.apple.CoreSimulator.SimRuntime.iOS-17-5',
isAvailable: false,
version: '17.5',
},
],
}),
};
}
if (command === 'xcodebuild') {
return { stdout: 'Xcode 26.0\nBuild version 17A324\n' };
}
if (command === 'tar') {
const maestroRunnerHome = args[args.indexOf('-C') + 1];
const productsDirectory = path.join(
maestroRunnerHome,
'cache',
'wda-builds',
'generic',
'DerivedData',
'Build',
'Products'
);
await fs.promises.mkdir(productsDirectory, { recursive: true });
await fs.promises.writeFile(
path.join(productsDirectory, 'WebDriverAgentRunner.xctestrun'),
'cached'
);
}
return { stdout: '' };
}) as any);
try {
await writeInstalledWdaVersion(homeDirectory, '11.1.3');
const installMaestro = createInstallMaestroBuildFunction();
const globalCtx = createGlobalContextMock({
runtimePlatform: BuildRuntimePlatform.DARWIN,
});
globalCtx.updateEnv({
EAS_BUILD_RUNNER: 'eas-build',
EAS_BUILD_COCOAPODS_CACHE_URL: 'https://cache.example.com',
HOME: homeDirectory,
});
const step = installMaestro.createBuildStepFromFunctionCall(globalCtx, {
callInputs: { backend: 'maestro-runner' },
});
await step.executeAsync();
expect(mockedDownloadFile).toHaveBeenCalledWith(
'https://cache.example.com/storage.googleapis.com/turtle-v2/maestro-runner-wda-cache/xcode-26.0-wda-11.1.3.tar.gz',
expect.stringMatching(/install_maestro_runner_wda_cache.*\/wda-cache\.tar\.gz$/),
{ retry: 3, timeout: 20_000 }
it.each(['1.1.27', '1.1.28', '1.2.3'])(
'prepares the WDA cache only for legacy Runner versions (%s)',
async version => {
const homeDirectory = await fs.promises.mkdtemp(
path.join(os.tmpdir(), 'install-maestro-test-')
);
for (const runtimeVersion of ['18.3', '26.0']) {
mockedSpawn.mockImplementation((async (command: string, args: string[]) => {
if (command === 'maestro-runner') {
return { stdout: `maestro-runner ${version}\n` };
}
if (command === 'xcrun') {
return {
stdout: JSON.stringify({
runtimes: [
{
identifier: 'com.apple.CoreSimulator.SimRuntime.iOS-18-3',
isAvailable: true,
version: '18.3.1',
},
{
identifier: 'com.apple.CoreSimulator.SimRuntime.iOS-26-0',
isAvailable: true,
version: '26.0',
},
{
identifier: 'com.apple.CoreSimulator.SimRuntime.iOS-17-5',
isAvailable: false,
version: '17.5',
},
],
}),
};
}
if (command === 'xcodebuild') {
return { stdout: 'Xcode 26.0\nBuild version 17A324\n' };
}
if (command === 'tar') {
const maestroRunnerHome = args[args.indexOf('-C') + 1];
const productsDirectory = path.join(
maestroRunnerHome,
'cache',
'wda-builds',
'generic',
'DerivedData',
'Build',
'Products'
);
await fs.promises.mkdir(productsDirectory, { recursive: true });
await fs.promises.writeFile(
path.join(productsDirectory, 'WebDriverAgentRunner.xctestrun'),
'cached'
);
}
return { stdout: '' };
}) as any);
try {
await writeInstalledWdaVersion(homeDirectory, '11.1.3');
const installMaestro = createInstallMaestroBuildFunction();
const globalCtx = createGlobalContextMock({
runtimePlatform: BuildRuntimePlatform.DARWIN,
});
globalCtx.updateEnv({
EAS_BUILD_RUNNER: 'eas-build',
EAS_BUILD_COCOAPODS_CACHE_URL: 'https://cache.example.com',
HOME: homeDirectory,
});
const step = installMaestro.createBuildStepFromFunctionCall(globalCtx, {
callInputs: { backend: 'maestro-runner' },
});
await step.executeAsync();
expect(step.getOutputValueByName('maestro_version')).toBe(version);
if (version !== '1.1.27') {
expect(mockedDownloadFile).not.toHaveBeenCalled();
expect(mockedSpawn.mock.calls.map(([command]) => command)).not.toContain('xcrun');
await expect(
fs.promises.access(path.join(homeDirectory, '.maestro-runner', 'cache'))
).rejects.toThrow();
return;
}
expect(mockedDownloadFile).toHaveBeenCalledWith(
'https://cache.example.com/storage.googleapis.com/turtle-v2/maestro-runner-wda-cache/xcode-26.0-wda-11.1.3.tar.gz',
expect.stringMatching(/install_maestro_runner_wda_cache.*\/wda-cache\.tar\.gz$/),
{ retry: 3, timeout: 20_000 }
);
for (const runtimeVersion of ['18.3', '26.0']) {
await expect(
fs.promises.readFile(
path.join(
homeDirectory,
'.maestro-runner',
'cache',
'wda-builds',
`sim-ios${runtimeVersion}-iphone`,
'DerivedData',
'Build',
'Products',
'WebDriverAgentRunner.xctestrun'
),
'utf8'
)
).resolves.toBe('cached');
}
await expect(
fs.promises.readFile(
path.join(
homeDirectory,
'.maestro-runner',
'cache',
'wda-builds',
`sim-ios${runtimeVersion}-iphone`,
'DerivedData',
'Build',
'Products',
'WebDriverAgentRunner.xctestrun'
),
'utf8'
fs.promises.access(
path.join(homeDirectory, '.maestro-runner', 'cache', 'wda-builds', 'sim-ios17.5-iphone')
)
).resolves.toBe('cached');
).rejects.toThrow();
} finally {
await fs.promises.rm(homeDirectory, { force: true, recursive: true });
}
await expect(
fs.promises.access(
path.join(homeDirectory, '.maestro-runner', 'cache', 'wda-builds', 'sim-ios17.5-iphone')
)
).rejects.toThrow();
} finally {
await fs.promises.rm(homeDirectory, { force: true, recursive: true });
}
});
);
it('does not download the WDA cache when the installed WDA version is unknown', async () => {
mockedSpawn.mockImplementation((async (command: string) => ({
stdout:
command === 'xcodebuild' ? 'Xcode 26.5\nBuild version 17F90\n' : 'maestro-runner 1.2.3\n',
command === 'xcodebuild' ? 'Xcode 26.5\nBuild version 17F90\n' : 'maestro-runner 1.1.27\n',
})) as any);
const installMaestro = createInstallMaestroBuildFunction();
const globalCtx = createGlobalContextMock({
@@ -593,7 +606,7 @@ describe('createInstallMaestroBuildFunction', () => {
mockedSpawn.mockImplementation((async (command: string) => {
switch (command) {
case 'maestro-runner':
return { stdout: 'maestro-runner 1.2.3\n' };
return { stdout: 'maestro-runner 1.1.27\n' };
case 'xcodebuild':
return { stdout: 'Xcode 26.5\nBuild version 17F90\n' };
case 'xcrun':
@@ -633,7 +646,7 @@ describe('createInstallMaestroBuildFunction', () => {
});
await expect(step.executeAsync()).resolves.toBeUndefined();
expect(step.getOutputValueByName('maestro_version')).toBe('1.2.3');
expect(step.getOutputValueByName('maestro_version')).toBe('1.1.27');
expect(mockedDownloadFile.mock.calls.map(([url]) => url)).toEqual([
'https://cache.example.com/storage.googleapis.com/turtle-v2/maestro-runner-wda-cache/xcode-26.5-wda-11.1.3.tar.gz',
'https://storage.googleapis.com/turtle-v2/maestro-runner-wda-cache/xcode-26.5-wda-11.1.3.tar.gz',
@@ -199,10 +199,15 @@ export function createInstallMaestroBuildFunction(): BuildFunction {
}
if (backend === 'maestro-runner' && global.runtimePlatform === BuildRuntimePlatform.DARWIN) {
await installMaestroRunnerWdaCache({
logger,
env,
});
// Runner 1.1.28 switched the default iOS driver to the bundled DeviceLab agent.
// Use the detected version after installation, including when `latest` was requested.
const installedRunnerVersion = semver.coerce(maestroVersionResult.value);
if (!installedRunnerVersion || semver.lt(installedRunnerVersion, '1.1.28')) {
await installMaestroRunnerWdaCache({
logger,
env,
});
}
}
logger.info(`${backend} ${maestroVersionResult.value} is ready.`);
@@ -0,0 +1,42 @@
import {
BuildFunction,
BuildStepInput,
BuildStepInputValueTypeName,
BuildStepOutput,
} from '@expo/steps';
import path from 'node:path';
import { z } from 'zod';
import { readAndroidArtifactInfoAsync } from '../utils/android/appArtifact';
export function createReadAndroidAppInfoBuildFunction(): BuildFunction {
return new BuildFunction({
namespace: 'eas',
id: 'read_android_app_info',
name: 'Read Android app info',
__metricsId: 'eas/read_android_app_info',
inputProviders: [
BuildStepInput.createProvider({
id: 'artifact_path',
required: true,
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
}),
],
outputProviders: [
BuildStepOutput.createProvider({ id: 'artifact_type', required: true }),
BuildStepOutput.createProvider({ id: 'package_name', required: true }),
],
fn: async (ctx, { inputs, outputs, signal }) => {
const artifactPath = path.resolve(
ctx.workingDirectory,
z.string().min(1).parse(inputs.artifact_path.value)
);
ctx.logger.info(`Reading Android artifact: ${artifactPath}.`);
const artifact = await readAndroidArtifactInfoAsync(artifactPath, signal);
ctx.logger.info(`Android artifact type: ${artifact.artifactType}.`);
ctx.logger.info(`Android package name: ${artifact.packageName}.`);
outputs.artifact_type.set(artifact.artifactType);
outputs.package_name.set(artifact.packageName);
},
});
}
@@ -0,0 +1,134 @@
import { SystemError } from '@expo/eas-build-job';
import { asyncResult } from '@expo/results';
import fetch, { Response } from 'node-fetch';
import { z } from 'zod';
const PostApi = {
'/token': {
request: z.object({
grant_type: z.literal('urn:ietf:params:oauth:grant-type:jwt-bearer'),
assertion: z.string().min(1),
}),
response: z.object({
access_token: z.string().min(1),
expires_in: z.number().finite().gt(60),
token_type: z.string().refine(value => value.toLowerCase() === 'bearer'),
}),
},
};
const OAuthErrorZ = z.enum([
'invalid_request',
'invalid_client',
'invalid_grant',
'unauthorized_client',
'unsupported_grant_type',
'invalid_scope',
'server_error',
'temporarily_unavailable',
]);
export class GooglePlayAuthRequestError extends Error {
constructor(
public readonly status: number,
public readonly errorCode?: z.output<typeof OAuthErrorZ>
) {
super(`Google Play OAuth request failed (HTTP ${status})${errorCode ? `: ${errorCode}` : ''}.`);
}
}
export class GooglePlayAuthClient {
private readonly baseUrl = 'https://oauth2.googleapis.com';
async postAsync<TPath extends keyof typeof PostApi>(
path: TPath,
body: z.input<(typeof PostApi)[TPath]['request']>,
signal?: AbortSignal
): Promise<z.output<(typeof PostApi)[TPath]['response']>> {
const schema = PostApi[path];
return await this.requestAsync({
method: 'POST',
path,
body,
requestSchema: schema.request,
responseSchema: schema.response,
signal,
});
}
private async requestAsync({
method,
path,
body,
requestSchema,
responseSchema,
signal,
}: {
method: 'POST';
path: string;
body: unknown;
requestSchema: z.ZodType<any>;
responseSchema: z.ZodType<any>;
signal?: AbortSignal;
}): Promise<any> {
const parsedBody = await asyncResult((async () => requestSchema.parse(body))());
if (!parsedBody.ok) {
throw new Error(
`Malformed request to Google Play OAuth: ${z.prettifyError(
parsedBody.enforceError() as z.ZodError
)}`
);
}
signal?.throwIfAborted();
let response: Response;
try {
response = await fetch(new URL(path, this.baseUrl).toString(), {
method,
redirect: 'manual',
signal,
body: new URLSearchParams(parsedBody.value),
});
} catch (cause) {
signal?.throwIfAborted();
throw new SystemError('Google Play OAuth request failed before a response was received.', {
cause,
});
}
let text: string;
try {
text = await response.text();
} catch (cause) {
signal?.throwIfAborted();
throw new SystemError(
`Could not read the Google Play OAuth response (HTTP ${response.status}).`,
{
cause,
}
);
}
const parsedJson = await asyncResult((async () => JSON.parse(text))());
if (!response.ok) {
const errorCode = OAuthErrorZ.safeParse(parsedJson.ok ? parsedJson.value?.error : undefined);
throw new GooglePlayAuthRequestError(
response.status,
errorCode.success ? errorCode.data : undefined
);
}
if (!parsedJson.ok) {
throw new SystemError(
`Malformed JSON response from Google Play OAuth (HTTP ${response.status}).`
);
}
const parsedResponse = await asyncResult(
(async () => responseSchema.parse(parsedJson.value))()
);
if (!parsedResponse.ok) {
throw new SystemError(
`Malformed response from Google Play OAuth (HTTP ${response.status}): ${z.prettifyError(
parsedResponse.enforceError() as z.ZodError
)}`
);
}
return parsedResponse.value;
}
}
@@ -0,0 +1,38 @@
import * as jose from 'jose';
import { KeyObject } from 'node:crypto';
import { GooglePlayAuthClient } from './GooglePlayAuthClient';
export type GoogleServiceAccount = {
client_email: string;
private_key: KeyObject;
private_key_id?: string;
};
export namespace GooglePlayAuthUtils {
async function createAssertionAsync(serviceAccount: GoogleServiceAccount): Promise<string> {
return await new jose.SignJWT({
scope: 'https://www.googleapis.com/auth/androidpublisher',
})
.setProtectedHeader({ alg: 'RS256', typ: 'JWT', kid: serviceAccount.private_key_id })
.setIssuer(serviceAccount.client_email)
.setAudience('https://oauth2.googleapis.com/token')
.setIssuedAt()
.setExpirationTime('1h')
.sign(serviceAccount.private_key);
}
export async function createTokenAsync(
serviceAccount: GoogleServiceAccount,
signal?: AbortSignal
): Promise<{ value: string; expiresAt: number }> {
const startedAt = Date.now();
const assertion = await createAssertionAsync(serviceAccount);
const response = await new GooglePlayAuthClient().postAsync(
'/token',
{ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion },
signal
);
return { value: response.access_token, expiresAt: startedAt + response.expires_in * 1000 };
}
}
@@ -0,0 +1,285 @@
import { SystemError } from '@expo/eas-build-job';
import fetch, { Response } from 'node-fetch';
import { z } from 'zod';
import { GooglePlayAuthUtils, GoogleServiceAccount } from './GooglePlayAuthUtils';
export class GooglePlayApiError extends Error {
constructor(
readonly status: number,
readonly apiMessage: string,
readonly reasons: string[]
) {
super(`Google Play request failed (HTTP ${status})${apiMessage ? `: ${apiMessage}` : '.'}`);
}
}
const ReleaseStatusZ = z.enum(['draft', 'inProgress', 'halted', 'completed']);
const ReleaseNoteZ = z.object({
language: z.string(),
text: z.string(),
});
const ReleaseZ = z.object({
name: z.string().optional(),
versionCodes: z.array(z.string()),
status: ReleaseStatusZ,
userFraction: z.number().gt(0).lt(1).optional(),
releaseNotes: z.array(ReleaseNoteZ).optional(),
});
const GetApi = {
'/androidpublisher/v3/applications/:packageName/edits/:editId': {
path: z.object({ packageName: z.string().min(1), editId: z.string().min(1) }),
request: z.object({}),
query: z.object({}),
response: z.object({ id: z.string().min(1), expiryTimeSeconds: z.string().optional() }),
},
'/androidpublisher/v3/applications/:packageName/edits/:editId/tracks/:track': {
path: z.object({
packageName: z.string().min(1),
editId: z.string().min(1),
track: z.string().min(1),
}),
request: z.object({}),
query: z.object({}),
response: z.object({
track: z.string().min(1),
releases: z.array(ReleaseZ).optional(),
}),
},
};
const PostApi = {
'/androidpublisher/v3/applications/:packageName/edits': {
path: z.object({ packageName: z.string().min(1) }),
request: z.object({}),
query: z.object({}),
response: z.object({ id: z.string().min(1), expiryTimeSeconds: z.string().optional() }),
},
'/androidpublisher/v3/applications/:packageName/edits/:editId:commit': {
path: z.object({ packageName: z.string().min(1), editId: z.string().min(1) }),
request: z.object({}),
query: z.object({ changesNotSentForReview: z.boolean().optional() }),
response: z.object({ id: z.string().min(1), expiryTimeSeconds: z.string().optional() }),
},
'/androidpublisher/v3/applications/:packageName/edits/:editId:validate': {
path: z.object({ packageName: z.string().min(1), editId: z.string().min(1) }),
request: z.object({}),
query: z.object({}),
response: z.object({ id: z.string().min(1), expiryTimeSeconds: z.string().optional() }),
},
};
const PutApi = {
'/androidpublisher/v3/applications/:packageName/edits/:editId/tracks/:track': {
path: z.object({
packageName: z.string().min(1),
editId: z.string().min(1),
track: z.string().min(1),
}),
request: z.object({
track: z.string().min(1),
releases: z.array(ReleaseZ).optional(),
}),
query: z.object({}),
response: z.object({
track: z.string().min(1),
releases: z.array(ReleaseZ).optional(),
}),
},
};
const DeleteApi = {
'/androidpublisher/v3/applications/:packageName/edits/:editId': {
path: z.object({ packageName: z.string().min(1), editId: z.string().min(1) }),
},
};
export class GooglePlayClient {
private readonly baseUrl = 'https://androidpublisher.googleapis.com';
private cachedToken?: Promise<{ value: string; expiresAt: number }>;
constructor(private readonly serviceAccount: GoogleServiceAccount) {}
private async getTokenAsync(signal?: AbortSignal): Promise<string> {
signal?.throwIfAborted();
while (this.cachedToken) {
const pending = this.cachedToken;
const cached = await pending;
signal?.throwIfAborted();
if (Date.now() < cached.expiresAt - 60_000) {
return cached.value;
}
if (this.cachedToken === pending) {
break;
}
}
const pending = GooglePlayAuthUtils.createTokenAsync(this.serviceAccount, signal);
this.cachedToken = pending;
try {
return (await pending).value;
} catch (error) {
if (this.cachedToken === pending) {
this.cachedToken = undefined;
}
throw error;
}
}
async getAsync<TPath extends keyof typeof GetApi>(
path: TPath,
params: z.input<(typeof GetApi)[TPath]['path']>,
signal?: AbortSignal
): Promise<z.output<(typeof GetApi)[TPath]['response']>> {
return await this.sendJsonRequestAsync('GET', path, GetApi[path], {}, params, {}, signal);
}
async postAsync<TPath extends keyof typeof PostApi>(
path: TPath,
body: z.input<(typeof PostApi)[TPath]['request']>,
params: z.input<(typeof PostApi)[TPath]['path']>,
options: { query?: z.input<(typeof PostApi)[TPath]['query']>; signal?: AbortSignal } = {}
): Promise<z.output<(typeof PostApi)[TPath]['response']>> {
return await this.sendJsonRequestAsync(
'POST',
path,
PostApi[path],
body,
params,
options.query ?? {},
options.signal
);
}
async putAsync<TPath extends keyof typeof PutApi>(
path: TPath,
body: z.input<(typeof PutApi)[TPath]['request']>,
params: z.input<(typeof PutApi)[TPath]['path']>,
signal?: AbortSignal
): Promise<z.output<(typeof PutApi)[TPath]['response']>> {
return await this.sendJsonRequestAsync('PUT', path, PutApi[path], body, params, {}, signal);
}
async deleteAsync<TPath extends keyof typeof DeleteApi>(
path: TPath,
params: z.input<(typeof DeleteApi)[TPath]['path']>,
signal?: AbortSignal
): Promise<void> {
let url: string = path;
for (const [key, value] of Object.entries(DeleteApi[path].path.parse(params))) {
url = url.replace(`:${key}`, encodeURIComponent(value));
}
await this.requestAsync('DELETE', url, undefined, signal);
}
private async sendJsonRequestAsync(
method: 'GET' | 'POST' | 'PUT' | 'DELETE',
path: string,
schema: {
path: z.ZodType<Record<string, string>>;
request: z.ZodType;
query: z.ZodType;
response: z.ZodType;
},
body: unknown,
params: unknown,
query: unknown,
signal?: AbortSignal
): Promise<any> {
const parsedBody = schema.request.parse(body);
for (const [key, value] of Object.entries(schema.path.parse(params))) {
path = path.replace(`:${key}`, encodeURIComponent(value));
}
const search = new URLSearchParams();
for (const [key, value] of Object.entries(
schema.query.parse(query) as Record<string, unknown>
)) {
if (value !== undefined) {
search.set(key, String(value));
}
}
const response = await this.requestAsync(
method,
search.size ? `${path}?${search}` : path,
method === 'GET' ? undefined : JSON.stringify(parsedBody),
signal
);
let data: unknown;
try {
data = await response.json();
} catch {
signal?.throwIfAborted();
throw new SystemError(
`Could not read the Google Play JSON response (HTTP ${response.status}).`
);
}
const parsed = schema.response.safeParse(data);
if (!parsed.success) {
throw new SystemError(
`Malformed response from Google Play (HTTP ${response.status}): ${z.prettifyError(parsed.error)}`
);
}
return parsed.data;
}
private async requestAsync(
method: 'GET' | 'POST' | 'PUT' | 'DELETE',
path: string,
body?: string,
signal?: AbortSignal
): Promise<Response> {
const url = new URL(path, this.baseUrl);
const token = await this.getTokenAsync(signal);
let response: Response;
signal?.throwIfAborted();
try {
response = await fetch(url.toString(), {
method,
body,
signal,
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
redirect: 'manual',
});
} catch {
signal?.throwIfAborted();
throw new SystemError('Google Play request failed before a response was received.');
}
if (!response.ok) {
let data: unknown;
try {
data = await response.json();
} catch {
signal?.throwIfAborted();
}
const parsed = z
.object({
error: z.object({
message: z.string().optional(),
errors: z.array(z.object({ reason: z.string().optional() })).optional(),
}),
})
.safeParse(data);
throw new GooglePlayApiError(
response.status,
parsed.success ? (parsed.data.error.message ?? '') : '',
parsed.success
? (parsed.data.error.errors?.flatMap(error => (error.reason ? [error.reason] : [])) ?? [])
: []
);
}
return response;
}
}
@@ -0,0 +1,111 @@
import { SystemError } from '@expo/eas-build-job';
import nock from 'nock';
import { inspect } from 'node:util';
import { GooglePlayAuthClient, GooglePlayAuthRequestError } from '../GooglePlayAuthClient';
jest.unmock('node-fetch');
const request = {
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer' as const,
assertion: 'caller-signed-assertion',
};
let client: GooglePlayAuthClient;
beforeEach(() => {
nock.disableNetConnect();
client = new GooglePlayAuthClient();
});
afterEach(() => {
const pending = nock.pendingMocks();
nock.cleanAll();
nock.enableNetConnect();
expect(pending).toEqual([]);
});
it('posts the caller request and returns a validated response on each call', async () => {
nock('https://oauth2.googleapis.com')
.post('/token', request)
.reply(200, { access_token: 'first-token', expires_in: 3600, token_type: 'Bearer' })
.post('/token', request)
.reply(200, { access_token: 'second-token', expires_in: 1800, token_type: 'Bearer' });
await expect(client.postAsync('/token', request)).resolves.toEqual({
access_token: 'first-token',
expires_in: 3600,
token_type: 'Bearer',
});
await expect(client.postAsync('/token', request)).resolves.toEqual({
access_token: 'second-token',
expires_in: 1800,
token_type: 'Bearer',
});
});
it.each([
{ access_token: '', expires_in: 3600, token_type: 'Bearer' },
{ access_token: 'example-token', expires_in: 60, token_type: 'Bearer' },
{ access_token: 'example-token', expires_in: '3600', token_type: 'Bearer' },
{ access_token: 'example-token', expires_in: 3600, token_type: 1 },
{ access_token: 'example-token', expires_in: 3600, token_type: 'Basic' },
])(
'includes validation details without token data for invalid OAuth responses (%j)',
async body => {
nock('https://oauth2.googleapis.com').post('/token').reply(200, body);
const result = client.postAsync('/token', request);
await expect(result).rejects.toThrow('Malformed response from Google Play OAuth (HTTP 200):');
try {
await result;
} catch (error) {
expect(inspect(error, { depth: null })).not.toContain('example-token');
expect((error as Error).message).toMatch(/access_token|expires_in|token_type/);
}
}
);
it.each([
[{ error: 'invalid_grant', error_description: 'example-token' }, 'invalid_grant'],
[{ error: 'example-token' }, undefined],
['<html>example-token</html>', undefined],
])(
'keeps HTTP status and known OAuth codes without retaining response data (%j)',
async (body, errorCode) => {
nock('https://oauth2.googleapis.com').post('/token').reply(400, body);
let error: unknown;
try {
await client.postAsync('/token', request);
} catch (caught) {
error = caught;
}
expect(error).toBeInstanceOf(GooglePlayAuthRequestError);
expect(error).toMatchObject({ status: 400, errorCode });
expect((error as Error).message).toContain('HTTP 400');
if (errorCode) {
expect((error as Error).message).toContain(errorCode);
}
expect(inspect(error, { depth: null })).not.toContain('example-token');
}
);
it.each(['network failure', 'malformed JSON'])('returns a system error for %s', async failure => {
const endpoint = nock('https://oauth2.googleapis.com').post('/token');
if (failure === 'network failure') {
endpoint.replyWithError('connection failed');
} else {
endpoint.reply(200, 'example-token is not JSON');
}
const result = client.postAsync('/token', request);
await expect(result).rejects.toBeInstanceOf(SystemError);
if (failure === 'network failure') {
await expect(result).rejects.toMatchObject({
cause: { message: expect.stringContaining('connection failed') },
});
} else {
await expect(result).rejects.toThrow(
'Malformed JSON response from Google Play OAuth (HTTP 200).'
);
try {
await result;
} catch (error) {
expect(inspect(error, { depth: null })).not.toContain('example-token');
}
}
});
@@ -0,0 +1,158 @@
import nock from 'nock';
import { generateKeyPairSync } from 'node:crypto';
import { SystemError } from '@expo/eas-build-job';
import { ZodError } from 'zod';
import { GooglePlayClient } from '../GooglePlayClient';
const packageName = 'dev.expo.submitfixture';
const editPath = `/androidpublisher/v3/applications/${packageName}/edits/edit`;
const api = (): nock.Scope =>
nock('https://androidpublisher.googleapis.com', {
reqheaders: { authorization: 'Bearer test-access-token' },
});
jest.unmock('node-fetch');
const serviceAccount = {
client_email: '[email protected]',
private_key: generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey,
};
let client: GooglePlayClient;
beforeEach(() => {
nock.disableNetConnect();
client = new GooglePlayClient(serviceAccount);
nock('https://oauth2.googleapis.com')
.post('/token')
.optionally()
.reply(200, { access_token: 'test-access-token', expires_in: 3600, token_type: 'Bearer' });
});
afterEach(() => {
const pending = nock.pendingMocks();
nock.cleanAll();
nock.enableNetConnect();
jest.restoreAllMocks();
expect(pending).toEqual([]);
});
it('creates an edit and validates the response', async () => {
api().post(`/androidpublisher/v3/applications/${packageName}/edits`, {}).reply(200, {
id: 'edit',
expiryTimeSeconds: '1234567890',
});
await expect(
client.postAsync(
'/androidpublisher/v3/applications/:packageName/edits',
{},
{
packageName,
}
)
).resolves.toEqual({ id: 'edit', expiryTimeSeconds: '1234567890' });
});
it('encodes track path parameters and validates track responses', async () => {
api().get(`${editPath}/tracks/wear%3Aproduction`).reply(200, { track: 'wear:production' });
await expect(
client.getAsync('/androidpublisher/v3/applications/:packageName/edits/:editId/tracks/:track', {
packageName,
editId: 'edit',
track: 'wear:production',
})
).resolves.toEqual({ track: 'wear:production' });
});
it('rejects invalid rollout requests before sending them', async () => {
await expect(
client.putAsync(
'/androidpublisher/v3/applications/:packageName/edits/:editId/tracks/:track',
{
track: 'production',
releases: [{ versionCodes: ['123'], status: 'inProgress', userFraction: 1 }],
},
{ packageName, editId: 'edit', track: 'production' }
)
).rejects.toBeInstanceOf(ZodError);
});
it('does not retry an ambiguous edit commit', async () => {
api()
.post(`${editPath}:commit`, {})
.query({ changesNotSentForReview: false })
.replyWithError('Lost response');
await expect(
client.postAsync(
'/androidpublisher/v3/applications/:packageName/edits/:editId:commit',
{},
{ packageName, editId: 'edit' },
{ query: { changesNotSentForReview: false } }
)
).rejects.toBeInstanceOf(SystemError);
});
it('deletes an edit with an empty response', async () => {
api().delete(editPath).reply(204);
await expect(
client.deleteAsync('/androidpublisher/v3/applications/:packageName/edits/:editId', {
packageName,
editId: 'edit',
})
).resolves.toBeUndefined();
});
it('rejects malformed success responses without exposing their contents', async () => {
api()
.get(editPath)
.reply(200, { id: 'edit', expiryTimeSeconds: { secret: 'PRIVATE' } });
await expect(
client.getAsync('/androidpublisher/v3/applications/:packageName/edits/:editId', {
packageName,
editId: 'edit',
})
).rejects.toThrow('Malformed response from Google Play (HTTP 200)');
});
it('retains structured API errors', async () => {
api()
.get(editPath)
.reply(403, { error: { message: 'Denied', errors: [{ reason: 'forbidden' }] } });
await expect(
client.getAsync('/androidpublisher/v3/applications/:packageName/edits/:editId', {
packageName,
editId: 'edit',
})
).rejects.toMatchObject({ status: 403, apiMessage: 'Denied', reasons: ['forbidden'] });
});
it.each(['body', 'query'])('accepts extra fields in an empty %s object', async field => {
api()
.post(`/androidpublisher/v3/applications/${packageName}/edits`, {})
.reply(200, { id: 'edit' });
await expect(
client.postAsync(
'/androidpublisher/v3/applications/:packageName/edits',
(field === 'body' ? { unexpected: true } : {}) as never,
{ packageName },
{ query: (field === 'query' ? { unexpected: true } : {}) as never }
)
).resolves.toEqual({ id: 'edit' });
});
it('shares a token across concurrent requests and refreshes before expiry', async () => {
nock.cleanAll();
const now = Date.now();
const clock = jest.spyOn(Date, 'now').mockReturnValue(now);
nock('https://oauth2.googleapis.com')
.post('/token')
.twice()
.reply(200, { access_token: 'test-access-token', expires_in: 3600, token_type: 'Bearer' });
api().get(editPath).times(4).reply(200, { id: 'edit' });
const get = () =>
client.getAsync('/androidpublisher/v3/applications/:packageName/edits/:editId', {
packageName,
editId: 'edit',
});
await Promise.all([get(), get()]);
clock.mockReturnValue(now + 3550_000);
await Promise.all([get(), get()]);
});
@@ -0,0 +1,92 @@
import { SystemError, UserError } from '@expo/eas-build-job';
import spawn from '@expo/spawn-async';
import StreamZip from 'node-stream-zip';
export type AndroidArtifactType = 'apk' | 'aab';
export async function readAndroidArtifactInfoAsync(
artifactPath: string,
signal?: AbortSignal
): Promise<{ artifactType: AndroidArtifactType; packageName: string }> {
signal?.throwIfAborted();
const artifactType = await detectAndroidArtifactTypeAsync(artifactPath);
switch (artifactType) {
case 'apk': {
const packageName = await readApkPackageNameAsync(artifactPath, signal);
return { artifactType, packageName };
}
case 'aab': {
const packageName = await readAabPackageNameAsync(artifactPath, signal);
return { artifactType, packageName };
}
}
}
async function detectAndroidArtifactTypeAsync(artifactPath: string): Promise<AndroidArtifactType> {
const zip = new StreamZip.async({ file: artifactPath });
try {
const bundleConfig = await zip.entry('BundleConfig.pb');
return bundleConfig ? 'aab' : 'apk';
} catch (error) {
throw new UserError(
'EAS_READ_ANDROID_APP_INFO_INVALID_ARTIFACT',
'Cannot read the Android artifact as a ZIP archive.',
{ cause: error }
);
} finally {
await zip.close().catch(() => {});
}
}
async function readApkPackageNameAsync(
artifactPath: string,
signal?: AbortSignal
): Promise<string> {
signal?.throwIfAborted();
try {
const { stdout } = await spawn('aapt2', ['dump', 'packagename', artifactPath], {
stdio: 'pipe',
signal,
});
return stdout.trim();
} catch (error) {
signal?.throwIfAborted();
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
throw new SystemError('aapt2 is not installed or is not available on the worker PATH.', {
cause: error,
});
}
throw new UserError(
'EAS_READ_ANDROID_APP_INFO_INVALID_MANIFEST',
'Cannot read the APK manifest with aapt2. Check the app binary.',
{ cause: error }
);
}
}
async function readAabPackageNameAsync(
artifactPath: string,
signal?: AbortSignal
): Promise<string> {
signal?.throwIfAborted();
try {
const { stdout } = await spawn(
'bundletool',
['dump', 'manifest', '--bundle', artifactPath, '--xpath', '/manifest/@package'],
{ stdio: 'pipe', signal }
);
return stdout.trim();
} catch (error) {
signal?.throwIfAborted();
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
throw new SystemError('bundletool is not installed or is not available on the worker PATH.', {
cause: error,
});
}
throw new UserError(
'EAS_READ_ANDROID_APP_INFO_INVALID_MANIFEST',
'Cannot read the AAB manifest with bundletool. Check the app binary.',
{ cause: error }
);
}
}
+142 -142
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "eas-cli",
"version": "24.12.0",
"version": "24.12.1",
"description": "EAS command line tool",
"keywords": [
"cli",
@@ -339,8 +339,44 @@ describe(Simulator, () => {
});
}
it('logs "request cancelled", stops the spinner, and exits with 130 only after the flush on Ctrl+C while the session is being created', async () => {
function mockCreateThatAnswersLater(): {
createStarted: Promise<void>;
resolveCreate: (session: CreatedDeviceRunSession) => void;
rejectCreate: (error: Error) => void;
} {
let resolveCreate!: (session: CreatedDeviceRunSession) => void;
let rejectCreate!: (error: Error) => void;
const createStarted = new Promise<void>(notifyCreateStarted => {
mockCreateDeviceRunSessionAsync.mockImplementationOnce(
() =>
new Promise<CreatedDeviceRunSession>((resolve, reject) => {
resolveCreate = resolve;
rejectCreate = reject;
notifyCreateStarted();
})
);
});
return {
createStarted,
resolveCreate: session => {
resolveCreate(session);
},
rejectCreate: error => {
rejectCreate(error);
},
};
}
/** Fake timers with the real sleepAsync, so the Ctrl+C waits run on the fake clock. */
function useFakeTimersWithRealSleep(): void {
jest.useFakeTimers();
const { sleepAsync } = jest.requireActual<typeof promiseUtils>('../../../utils/promise');
jest.spyOn(promiseUtils, 'sleepAsync').mockImplementation(sleepAsync);
}
it('logs "request cancelled", stops the spinner, and exits with 130 only after the flush on Ctrl+C while the session is being created, and stops a session that comes back during the flush only after the flush', async () => {
mockLogEvent.mockClear();
useFakeTimersWithRealSleep();
const processExitSpy = jest.spyOn(process, 'exit').mockImplementation(code => {
throw new Error(`process.exit(${code})`);
});
@@ -355,21 +391,30 @@ describe(Simulator, () => {
})
);
});
const createStarted = mockCreateThatNeverAnswers();
const { createStarted, resolveCreate } = mockCreateThatAnswersLater();
const existingSigintListeners = new Set(process.listeners('SIGINT'));
const { command } = createCommand(['--platform', 'ios', '--non-interactive']);
const commandPromise = command.runAsync();
const exited = expect(commandPromise).rejects.toThrow('process.exit(130)');
await createStarted;
process.listeners('SIGINT').find(listener => !existingSigintListeners.has(listener))?.(
'SIGINT'
);
await flushStarted;
resolveCreate(makeCreatedDeviceRunSession());
await jest.advanceTimersByTimeAsync(500);
const stopCallsDuringFlush = [...mockEnsureDeviceRunSessionStoppedAsync.mock.calls];
const exitCallsDuringFlush = [...processExitSpy.mock.calls];
finishFlush();
await expect(commandPromise).rejects.toThrow('process.exit(130)');
await exited;
expect(stopCallsDuringFlush).toEqual([]);
expect(exitCallsDuringFlush).toEqual([]);
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledWith(
graphqlClient,
'session-123'
);
expect(mockLogEvent).toHaveBeenLastCalledWith(
SimulatorEvent.REQUEST_CANCELLED,
expect.objectContaining({ project_id: 'project-123', reason: 'user_abort' })
@@ -377,14 +422,132 @@ describe(Simulator, () => {
expect(mockOra.mock.results[0]?.value.fail).toHaveBeenCalledWith(
'Simulator session request canceled'
);
expect(mockEnsureDeviceRunSessionStoppedAsync).not.toHaveBeenCalled();
expect(process.listeners('SIGINT')).toEqual([...existingSigintListeners]);
} finally {
processExitSpy.mockRestore();
jest.useRealTimers();
}
});
it('removes its Ctrl+C listener on the first Ctrl+C during the request, so a second Ctrl+C is not swallowed during the flush', async () => {
it('stops a session that the create request returns within 5 seconds of Ctrl+C, prints its ID, and exits with 130 after the stop', async () => {
useFakeTimersWithRealSleep();
const processExitSpy = jest.spyOn(process, 'exit').mockImplementation(code => {
throw new Error(`process.exit(${code})`);
});
try {
let finishStop!: () => void;
mockEnsureDeviceRunSessionStoppedAsync.mockImplementationOnce(
() =>
new Promise(resolve => {
finishStop = () => {
resolve({ id: 'session-123', status: DeviceRunSessionStatus.Stopped });
};
})
);
const { createStarted, resolveCreate } = mockCreateThatAnswersLater();
const existingSigintListeners = [...process.listeners('SIGINT')];
const { command } = createCommand(['--platform', 'ios', '--non-interactive']);
const commandPromise = command.runAsync();
const exited = expect(commandPromise).rejects.toThrow('process.exit(130)');
await createStarted;
process.emit('SIGINT');
await jest.advanceTimersByTimeAsync(4_999);
resolveCreate(makeCreatedDeviceRunSession());
await jest.advanceTimersByTimeAsync(0);
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledWith(
graphqlClient,
'session-123'
);
const exitCallsDuringStop = [...processExitSpy.mock.calls];
finishStop();
await exited;
expect(exitCallsDuringStop).toEqual([]);
expect(mockOra.mock.results[1]?.value.succeed).toHaveBeenCalledWith(
'Simulator session session-123 stopped'
);
expect(Log.warn).not.toHaveBeenCalled();
expect(mockByIdAsync).not.toHaveBeenCalled();
expect(fs.writeFile).not.toHaveBeenCalled();
expect(process.listeners('SIGINT')).toEqual(existingSigintListeners);
} finally {
// Drop the pending stop if this test failed before using it, so later tests do not hang.
mockEnsureDeviceRunSessionStoppedAsync.mockReset();
processExitSpy.mockRestore();
jest.useRealTimers();
}
});
it('warns to check eas simulator:list and exits with 130 when no session comes back within 5 seconds of Ctrl+C', async () => {
useFakeTimersWithRealSleep();
const processExitSpy = jest.spyOn(process, 'exit').mockImplementation(code => {
throw new Error(`process.exit(${code})`);
});
try {
const createStarted = mockCreateThatNeverAnswers();
const { command } = createCommand(['--platform', 'ios', '--non-interactive']);
const commandPromise = command.runAsync();
const exited = expect(commandPromise).rejects.toThrow('process.exit(130)');
await createStarted;
process.emit('SIGINT');
await jest.advanceTimersByTimeAsync(4_999);
const warningsBeforeFiveSeconds = [...jest.mocked(Log.warn).mock.calls];
const exitCallsBeforeFiveSeconds = [...processExitSpy.mock.calls];
await jest.advanceTimersByTimeAsync(1);
await exited;
expect(warningsBeforeFiveSeconds).toEqual([]);
expect(exitCallsBeforeFiveSeconds).toEqual([]);
expect(Log.warn).toHaveBeenCalledWith(
expect.stringContaining('Run `eas simulator:list` to check for a running session')
);
expect(mockEnsureDeviceRunSessionStoppedAsync).not.toHaveBeenCalled();
} finally {
processExitSpy.mockRestore();
jest.useRealTimers();
}
});
it('warns the same way, and logs no "request failed", when the create request fails after Ctrl+C', async () => {
mockLogEvent.mockClear();
useFakeTimersWithRealSleep();
const processExitSpy = jest.spyOn(process, 'exit').mockImplementation(code => {
throw new Error(`process.exit(${code})`);
});
try {
const { createStarted, rejectCreate } = mockCreateThatAnswersLater();
const { command } = createCommand(['--platform', 'ios', '--non-interactive']);
const commandPromise = command.runAsync();
const exited = expect(commandPromise).rejects.toThrow('process.exit(130)');
await createStarted;
process.emit('SIGINT');
rejectCreate(
new CombinedError({
networkError: Object.assign(new Error('socket hang up'), { code: 'ECONNRESET' }),
})
);
await jest.advanceTimersByTimeAsync(0);
// The failed request ends the wait at once, without waiting the full 5 seconds.
expect(processExitSpy).toHaveBeenCalledWith(130);
await exited;
expect(Log.warn).toHaveBeenCalledWith(expect.stringContaining('eas simulator:list'));
expect(mockEnsureDeviceRunSessionStoppedAsync).not.toHaveBeenCalled();
expect(mockLogEvent).toHaveBeenLastCalledWith(
SimulatorEvent.REQUEST_CANCELLED,
expect.objectContaining({ project_id: 'project-123', reason: 'user_abort' })
);
} finally {
processExitSpy.mockRestore();
jest.useRealTimers();
}
});
it('exits with 130 at once on a second Ctrl+C while it waits for the create request', async () => {
useFakeTimersWithRealSleep();
const processExitSpy = jest.spyOn(process, 'exit').mockImplementation(code => {
throw new Error(`process.exit(${code})`);
});
@@ -394,25 +557,35 @@ describe(Simulator, () => {
const { command } = createCommand(['--platform', 'ios', '--non-interactive']);
const commandPromise = command.runAsync();
const exited = expect(commandPromise).rejects.toThrow('process.exit(130)');
await createStarted;
process.emit('SIGINT');
const listenersAfterFirstCtrlC = process.listeners('SIGINT');
await expect(commandPromise).rejects.toThrow('process.exit(130)');
await jest.advanceTimersByTimeAsync(2_000);
expect(Log.log).toHaveBeenCalledWith(
expect.stringContaining('Press Ctrl+C again to exit now')
);
expect(processExitSpy).not.toHaveBeenCalled();
expect(listenersAfterFirstCtrlC).toEqual(existingSigintListeners);
expect(() => process.emit('SIGINT')).toThrow('process.exit(130)');
expect(Log.warn).toHaveBeenCalledWith(expect.stringContaining('eas simulator:list'));
// process.exit is mocked, so let the first Ctrl+C finish to clean up its listener.
await jest.advanceTimersByTimeAsync(3_000);
await exited;
expect(mockEnsureDeviceRunSessionStoppedAsync).not.toHaveBeenCalled();
expect(process.listeners('SIGINT')).toEqual(existingSigintListeners);
} finally {
processExitSpy.mockRestore();
jest.useRealTimers();
}
});
it('exits with 130 after 1 second when the analytics flush hangs after Ctrl+C', async () => {
jest.useFakeTimers();
it('stops waiting for a hung analytics flush 1 second after Ctrl+C', async () => {
useFakeTimersWithRealSleep();
const processExitSpy = jest.spyOn(process, 'exit').mockImplementation(code => {
throw new Error(`process.exit(${code})`);
});
try {
const { sleepAsync } = jest.requireActual<typeof promiseUtils>('../../../utils/promise');
jest.spyOn(promiseUtils, 'sleepAsync').mockImplementation(sleepAsync);
mockFlushAsync.mockImplementationOnce(() => new Promise<void>(() => {}));
const createStarted = mockCreateThatNeverAnswers();
@@ -422,12 +595,17 @@ describe(Simulator, () => {
await createStarted;
process.emit('SIGINT');
await jest.advanceTimersByTimeAsync(999);
const exitCallsBeforeOneSecond = [...processExitSpy.mock.calls];
const waitMessagesBeforeOneSecond = jest
.mocked(Log.log)
.mock.calls.filter(([message]) => String(message).includes('Waiting up to 5 seconds'));
await jest.advanceTimersByTimeAsync(1);
await exited;
expect(exitCallsBeforeOneSecond).toEqual([]);
expect(waitMessagesBeforeOneSecond).toEqual([]);
expect(Log.log).toHaveBeenCalledWith(expect.stringContaining('Waiting up to 5 seconds'));
expect(mockFlushAsync).toHaveBeenCalled();
await jest.advanceTimersByTimeAsync(5_000);
await exited;
} finally {
processExitSpy.mockRestore();
jest.useRealTimers();
@@ -356,7 +356,9 @@ export default class Simulator extends EasCommand {
...agentIdentity,
maxRunTimeMinutes: flags['max-duration-minutes'],
maxIdleTimeMinutes: flags['max-idle-time-minutes'],
})
}),
createdSession =>
stopDeviceRunSessionCreatedAfterCancelAsync(graphqlClient, createdSession.id)
);
deviceRunSessionId = session.id;
nullthrows(session.turtleJobRun?.id, 'Expected simulator session to start');
@@ -762,6 +764,23 @@ async function stopDeviceRunSessionAfterInterruptAsync({
process.exit(130);
}
async function stopDeviceRunSessionCreatedAfterCancelAsync(
graphqlClient: ExpoGraphqlClient,
deviceRunSessionId: string
): Promise<void> {
const spinner = ora(
`Stopping simulator session ${deviceRunSessionId}, which the request created after Ctrl+C`
).start();
const stopped = await ensureDeviceRunSessionStoppedSafelyAsync(graphqlClient, deviceRunSessionId);
if (stopped) {
spinner.succeed(`Simulator session ${deviceRunSessionId} stopped`);
} else {
spinner.fail(
`Could not confirm the simulator session was stopped. Run \`eas simulator:stop --id ${deviceRunSessionId}\` to terminate it and avoid unexpected charges.`
);
}
}
async function resetSimulatorEnvVerboseAsync(
projectDir: string,
deviceRunSessionId: string
@@ -801,31 +820,52 @@ async function ensureDeviceRunSessionStoppedSafelyAsync(
*/
const CANCEL_FLUSH_TIMEOUT_MS = 1_000;
/**
* How long Ctrl+C then waits for the create request. The server can still create the session after
* the client stops waiting, and nothing else stops that session before its maximum duration.
*/
const CANCEL_CREATE_WAIT_MS = 5_000;
const SESSION_MAY_BE_RUNNING_WARNING =
'A simulator session may still be running. Run `eas simulator:list` to check for a running session, and `eas simulator:stop --id <id>` to stop it.';
class SimulatorRequestCancelledError extends Error {}
/**
* Runs the create request and logs the client-side funnel events around it: "request sent" before
* it leaves, "request cancelled" on Ctrl+C before an answer, and "request failed" when no answer
* arrives. Ctrl+C stops the spinner, flushes analytics, and exits with 130, like the session's own
* Ctrl+C handler: going through the command's error handling would print the exit as an error and
* report it to Sentry.
* arrives. "Request cancelled" means the client stopped waiting; the server can still create the
* session. So Ctrl+C stops the spinner, flushes analytics, and waits a bounded time for the
* request: a session that comes back goes to `stopCreatedAsync`, and otherwise the user is told how
* to check for one. Then it exits with 130, like the session's own Ctrl+C handler: going through
* the command's error handling would print the exit as an error and report it to Sentry. A second
* Ctrl+C exits at once.
*/
async function withSimulatorRequestAnalyticsAsync<T>(
analytics: AnalyticsWithOrchestration,
properties: AnalyticsEventProperties,
spinner: Ora,
createAsync: () => Promise<T>
createAsync: () => Promise<T>,
stopCreatedAsync: (created: T) => Promise<void>
): Promise<T> {
let cancelRequested = false;
let onSigint: (() => void) | undefined;
const cancelled = new Promise<never>((_, reject) => {
onSigint = () => {
if (cancelRequested) {
Log.warn(SESSION_MAY_BE_RUNNING_WARNING);
process.exit(130);
}
cancelRequested = true;
reject(new SimulatorRequestCancelledError());
};
});
process.once('SIGINT', onSigint!);
process.on('SIGINT', onSigint!);
analytics.logEvent(SimulatorEvent.REQUEST_SENT, properties);
let createPromise: Promise<T> | undefined;
try {
return await Promise.race([createAsync(), cancelled]);
createPromise = createAsync();
return await Promise.race([createPromise, cancelled]);
} catch (error) {
if (error instanceof SimulatorRequestCancelledError) {
analytics.logEvent(SimulatorEvent.REQUEST_CANCELLED, { ...properties, reason: 'user_abort' });
@@ -836,6 +876,7 @@ async function withSimulatorRequestAnalyticsAsync<T>(
sleepAsync(CANCEL_FLUSH_TIMEOUT_MS, flushTimeout.signal),
]);
flushTimeout.abort();
await stopSessionCreatedAfterCancelAsync(createPromise, stopCreatedAsync);
process.exit(130);
}
const reason = simulatorRequestFailureReason(error);
@@ -848,6 +889,33 @@ async function withSimulatorRequestAnalyticsAsync<T>(
}
}
async function stopSessionCreatedAfterCancelAsync<T>(
createPromise: Promise<T> | undefined,
stopCreatedAsync: (created: T) => Promise<void>
): Promise<void> {
if (!createPromise) {
// Ctrl+C came before the request was sent, so no session can have been created.
return;
}
Log.log(
`Waiting up to ${CANCEL_CREATE_WAIT_MS / 1_000} seconds for the request to finish, so a session it created can be stopped. Press Ctrl+C again to exit now.`
);
const waitTimeout = new AbortController();
const created = await Promise.race([
createPromise.then(
value => ({ value }),
() => undefined
),
sleepAsync(CANCEL_CREATE_WAIT_MS, waitTimeout.signal).then(() => undefined),
]);
waitTimeout.abort();
if (created) {
await stopCreatedAsync(created.value);
} else {
Log.warn(SESSION_MAY_BE_RUNNING_WARNING);
}
}
async function agentIdentityInputAsync(): Promise<{ agentId?: string; agentSessionId?: string }> {
if (await isAnalyticsOptedOutAsync()) {
return {};
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "eas-cli-local-build-plugin",
"version": "24.12.0",
"version": "24.12.1",
"description": "Tool for running EAS compatible builds on a local machine.",
"bugs": "https://github.com/expo/eas-cli/issues",
"license": "BUSL-1.1",
@@ -26,7 +26,7 @@
"clean": "rimraf node_modules dist coverage \"*.tsbuildinfo\""
},
"dependencies": {
"@expo/build-tools": "24.12.0",
"@expo/build-tools": "24.12.1",
"@expo/bunyan": "^4.0.1",
"@expo/eas-build-job": "24.9.0",
"@expo/logger": "24.8.0",
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@expo/worker",
"version": "24.12.0",
"version": "24.12.1",
"private": true,
"scripts": {
"start": "yarn watch",
@@ -19,7 +19,7 @@
},
"dependencies": {
"@babel/core": "7.24.7",
"@expo/build-tools": "24.12.0",
"@expo/build-tools": "24.12.1",
"@expo/config-plugins": "55.0.7",
"@expo/config-types": "55.0.5",
"@expo/eas-build-job": "24.9.0",
Generated
+3 -3
View File
@@ -2303,7 +2303,7 @@ __metadata:
languageName: node
linkType: hard
"@expo/build-tools@npm:24.12.0, @expo/build-tools@workspace:packages/build-tools":
"@expo/build-tools@npm:24.12.1, @expo/build-tools@workspace:packages/build-tools":
version: 0.0.0-use.local
resolution: "@expo/build-tools@workspace:packages/build-tools"
dependencies:
@@ -2984,7 +2984,7 @@ __metadata:
resolution: "@expo/worker@workspace:packages/worker"
dependencies:
"@babel/core": "npm:7.24.7"
"@expo/build-tools": "npm:24.12.0"
"@expo/build-tools": "npm:24.12.1"
"@expo/config-plugins": "npm:55.0.7"
"@expo/config-types": "npm:55.0.5"
"@expo/eas-build-job": "npm:24.9.0"
@@ -10418,7 +10418,7 @@ __metadata:
version: 0.0.0-use.local
resolution: "eas-cli-local-build-plugin@workspace:packages/local-build-plugin"
dependencies:
"@expo/build-tools": "npm:24.12.0"
"@expo/build-tools": "npm:24.12.1"
"@expo/bunyan": "npm:^4.0.1"
"@expo/eas-build-job": "npm:24.9.0"
"@expo/logger": "npm:24.8.0"