Compare commits

...
14 Commits
Author SHA1 Message Date
Expo CI b5ac163b37 v24.12.0 2026-10-07 21:15:21 +00:00
Douglas LowderandClaude Opus 5 92c8944cda [eas-cli] Include sourceMapUrl and assetMapUrl in eas update:view --json (#4534)
For update:view, add both asset map and source map URLs to the returned results when --json is used. This allows CLI users to retrieve source maps needed for symbolicating JS crashes.

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-10-07 21:06:12 +00:00
Douglas LowderandClaude Opus 5.5 96581b8094 [ci] Move ffmpeg-dependent tests to a separate workflow (#4565)
For better performance of the main test workflow, move ffmpeg-dependent tests to a separate workflow, with a restricted set of source files in the workflow trigger, and ensure that this workflow is not required for PRs.

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-07 14:00:32 -07:00
Gabe Debes e229f5378f [build-tools] Show eas update:embedded:upload output in build logs (#4557) 2026-10-07 13:38:05 -07:00
Gabe Debes 19657cc7ff [build-tools] Fix unnotarized mitmproxy cask install on iOS network capture sessions (#4556) 2026-10-07 11:04:55 -07:00
Tomasz Mazur be7acb7ab5 [eas-cli] Fix workflow:ssh lookup for job run ids (#4529) 2026-10-07 17:42:49 +02:00
Gabe DebesandClaude 3c302a055d [build-tools] Upload embedded bundle from custom builds (#4494)
* [build-tools] Upload embedded bundle from eas/build custom builds

Co-Authored-By: Claude  <[email protected]>

* [build-tools] Add ignore_error to eas/upload_embedded_bundle and share archive path resolvers

Co-Authored-By: Claude <[email protected]>
2026-10-06 15:06:48 -07:00
Samuel Newman 449bd4981e Select containing iOS app when archive includes an App Clip (#4541)
For build:download, exclude nested app bundles (like app clips) from the installable candidates. Return the sole outer app without prompting, and keep the selection prompt when there are genuinely separate apps.
2026-10-06 09:58:17 -07:00
Szymon Dziedzic 4fd36987ba [build-tools] Encode macOS session previews with cwebp (#4549)
* [build-tools] Encode macOS session previews with cwebp

Homebrew's FFmpeg is built without libwebp, so every macOS preview failed
with "Encoder not found" (exit code 8). Resize the screenshot with sips and
encode it with cwebp from Homebrew's webp package instead. Android keeps
using FFmpeg.

* [build-tools] Add changelog entry for macOS session preview encoding

* [build-tools] Format the changelog entry
2026-10-06 18:14:16 +02:00
Szymon Dziedzic 01c1ffcaf4 [build-tools] Fix the session preview device reference on main (#4548)
#4398 was based on #4499, which renamed device to readyDevice in
startDeviceSessionHostAsync. #4540 reverted #4499 before #4398 merged, so
main referred to a readyDevice name that no longer exists and the
build-tools typecheck failed. Use device instead.
2026-10-06 14:10:28 +02:00
Szymon Dziedzic b10cc829bd [build-tools] Refresh simulator session preview artifacts (#4398)
Capture a WebP thumbnail of the session device every minute while the
session host runs, and upload it to one reusable preview artifact. Upload
request errors no longer include the signed upload URL in logs.
2026-10-06 13:54:42 +02:00
SJ Kim 3d8ed4c81f [eas-cli] Log client request events for simulator sessions (#4483)
* [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] Don't count an HTTP error answer as a failed simulator session request (ENG-27138)

* [eas-cli] Keep the simulator request analytics wrapper with its only caller (ENG-27138)
2026-10-05 23:10:34 -04:00
Expo CI a344c0e1e8 bump STAGING and PRODUCTION to 24.11.0 in cli-versions.json 2026-10-05 22:05:17 +00:00
Expo CI f80f548e2f update CHANGELOG.md for v24.11.0 2026-10-05 22:03:02 +00:00
52 changed files with 3235 additions and 658 deletions

No files matched your search

@@ -0,0 +1,43 @@
name: Test recording recovery
on:
push:
branches: [main]
paths: &recording-paths
- packages/build-tools/src/steps/utils/deviceRunSessionScreenRecordings.ts
- packages/build-tools/src/steps/utils/deviceRunSessionArtifacts.ts
- packages/build-tools/src/steps/utils/__tests__/*.test.ffmpeg.ts
- packages/build-tools/jest/ffmpeg-config.ts
- .github/workflows/test-recording-recovery.yml
pull_request:
types: [opened, synchronize]
paths: *recording-paths
permissions:
contents: read
concurrency:
group: test-recording-recovery-${{ github.ref }}
cancel-in-progress: true
jobs:
test:
runs-on: ubuntu-latest
name: Test recording recovery with ffmpeg
steps:
- uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4
with:
persist-credentials: false
- name: Setup tools
uses: ./.github/actions/setup-mise
- name: Install ffmpeg
# The recording recovery test cuts and decodes real MP4 files with ffmpeg and ffprobe.
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends ffmpeg
- name: Install dependencies
run: yarn install --immutable
- name: Build build-tools dependencies
# tsc emits the dist files that the test imports from workspace packages such as @expo/logger.
run: yarn run -T lerna run typecheck --scope @expo/build-tools --include-dependencies
- name: Run recording recovery test
working-directory: packages/build-tools
run: yarn jest-ffmpeg
-3
View File
@@ -26,9 +26,6 @@ jobs:
uses: ./.github/actions/setup-mise
env:
MISE_NODE_VERSION: ${{ matrix.node }}
- name: Install ffmpeg
# build-tools recording-recovery tests cut and decode real MP4 files with ffmpeg and ffprobe.
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends ffmpeg
- name: Install dependencies
run: yarn install --immutable
env:
+23 -3
View File
@@ -8,17 +8,37 @@ This is the log of notable changes to EAS CLI and related packages.
### 🎉 New features
- [build-tools] Record iOS Simulator sessions through serve-sim. ([#4474](https://github.com/expo/eas-cli/pull/4474) by [@gwdp](https://github.com/gwdp))
- [eas-cli] Add browser device login with resumable commands for chat agents. ([#4502](https://github.com/expo/eas-cli/pull/4502) by [@eiiot](https://github.com/eiiot))
- [build-tools] Upload the display rotation agent-device reports for a screenshot as device run session artifact metadata. ([#4508](https://github.com/expo/eas-cli/pull/4508) by [@szdziedzic](https://github.com/szdziedzic))
- [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))
- [eas-cli] Include `assetMapUrl` and `sourceMapUrl` in the `eas update:view --json` output. Each value is a signed download URL, or null when the update was published without that file. ([#4534](https://github.com/expo/eas-cli/pull/4534) by [@douglowder](https://github.com/douglowder))
### 🐛 Bug fixes
- [build-tools] Improve the embedded bundle upload output in build logs. ([#4557](https://github.com/expo/eas-cli/pull/4557) by [@gwdp](https://github.com/gwdp))
- [build-tools] Allow the unnotarized mitmproxy cask to run in iOS network capture sessions. ([#4556](https://github.com/expo/eas-cli/pull/4556) by [@gwdp](https://github.com/gwdp))
- [build-tools] Encode macOS simulator session previews with cwebp, because Homebrew's FFmpeg cannot encode WebP. ([#4549](https://github.com/expo/eas-cli/pull/4549) by [@szdziedzic](https://github.com/szdziedzic))
### 🧹 Chores
## [24.11.0](https://github.com/expo/eas-cli/releases/tag/v24.11.0) - 2026-10-05
### 🎉 New features
- [build-tools] Record iOS Simulator sessions through serve-sim. ([#4474](https://github.com/expo/eas-cli/pull/4474) by [@gwdp](https://github.com/gwdp))
- [eas-cli] Add browser device login with resumable commands for chat agents. ([#4502](https://github.com/expo/eas-cli/pull/4502) by [@eiiot](https://github.com/eiiot))
- [build-tools] Upload the display rotation agent-device reports for a screenshot as device run session artifact metadata. ([#4508](https://github.com/expo/eas-cli/pull/4508) by [@szdziedzic](https://github.com/szdziedzic))
- [build-tools] Refresh a WebP thumbnail of the simulator session screen every minute as a reusable session preview artifact. ([#4398](https://github.com/expo/eas-cli/pull/4398) by [@szdziedzic](https://github.com/szdziedzic))
### 🐛 Bug fixes
- [eas-cli] Select the containing iOS app when its archive also includes a nested App Clip. ([#4541](https://github.com/expo/eas-cli/pull/4541) by [@mozzius](https://github.com/mozzius))
- [build-tools] Allow expo.test subdomains to open local and staging simulator previews. ([#4480](https://github.com/expo/eas-cli/pull/4480) by [@hirbod](https://github.com/hirbod))
- [build-tools] Retry App Store Connect connection failures and safely recover interrupted status reads and upload commits. ([#4520](https://github.com/expo/eas-cli/pull/4520) by [@sjchmiela](https://github.com/sjchmiela))
### 🧹 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.10.0",
"PRODUCTION": "24.10.0"
"STAGING": "24.11.0",
"PRODUCTION": "24.11.0"
}
+1 -1
View File
@@ -1,5 +1,5 @@
{
"npmClient": "yarn",
"version": "24.11.0",
"version": "24.12.0",
"$schema": "node_modules/lerna/schemas/lerna-schema.json"
}
@@ -0,0 +1,13 @@
import type { Config } from '@jest/types';
import baseConfig from '../../../jest/jest.shared.config';
const config: Config.InitialOptions = {
...baseConfig,
rootDir: '../src',
testMatch: ['**/__tests__/*.test.ffmpeg.ts'],
clearMocks: true,
setupFilesAfterEnv: ['<rootDir>/../jest/setup-tests.ts'],
};
export default config;
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@expo/build-tools",
"version": "24.11.0",
"version": "24.12.0",
"bugs": "https://github.com/expo/eas-cli/issues",
"license": "BUSL-1.1",
"author": "Expo <[email protected]>",
@@ -30,6 +30,7 @@
"prepack": "rimraf dist \"*.tsbuildinfo\" && yarn gql && tsc -p tsconfig.build.json",
"jest-unit": "jest --config jest/unit-config.ts",
"jest-integration": "jest --config jest/integration-config.ts",
"jest-ffmpeg": "jest --config jest/ffmpeg-config.ts",
"jest-unit-watch": "jest --config jest/unit-config.ts --watch",
"jest-integration-watch": "jest --config jest/integration-config.ts --watch",
"clean": "rimraf node_modules dist coverage \"*.tsbuildinfo\"",
@@ -0,0 +1,5 @@
import { Android } from '@expo/eas-build-job';
export function resolveArtifactPath(job: Android.Job): string {
return job.applicationArchivePath ?? 'android/app/build/outputs/**/*.{apk,aab}';
}
@@ -61,7 +61,7 @@ jest.mock('../../utils/expoUpdates', () => ({
}));
jest.mock('../../utils/expoUpdatesEmbedded', () => ({
...jest.requireActual('../../utils/expoUpdatesEmbedded'),
uploadEmbeddedBundleAsync: jest.fn(),
uploadEmbeddedBundleAsync: jest.fn(async () => ({ status: 'uploaded' })),
}));
jest.mock('../../utils/hooks', () => ({
Hook: {
@@ -344,7 +344,29 @@ describe(androidBuilder, () => {
await androidBuilder(ctx);
expect(uploadEmbeddedBundleAsync).toHaveBeenCalledWith(ctx);
expect(uploadEmbeddedBundleAsync).toHaveBeenCalledWith(
expect.objectContaining({ job: ctx.job, env: ctx.env, projectDir: '/workingdir/build' })
);
});
it.each([
['uploaded', BuildPhaseResult.SUCCESS],
['skipped', BuildPhaseResult.SKIPPED],
['failed', BuildPhaseResult.WARNING],
] as const)('marks the phase from the %s result', async (uploadResult, phaseResult) => {
jest.mocked(uploadEmbeddedBundleAsync).mockResolvedValueOnce({ status: uploadResult });
const ctx = createContext({ sdkVersion: '58.0.0' });
await androidBuilder(ctx);
expect(datadogDistributionMock).toHaveBeenCalledWith(
'eas.build.phase_duration',
expect.any(Number),
expect.objectContaining({
build_phase: BuildPhase.UPLOAD_EMBEDDED_BUNDLE.toLowerCase(),
result: phaseResult,
})
);
});
it('skips by default on SDK 57 and earlier', async () => {
@@ -371,7 +393,9 @@ describe(androidBuilder, () => {
await androidBuilder(ctx);
expect(uploadEmbeddedBundleAsync).toHaveBeenCalledWith(ctx);
expect(uploadEmbeddedBundleAsync).toHaveBeenCalledWith(
expect.objectContaining({ job: ctx.job })
);
});
it('skips on SDK 58 and later when EAS_UPDATE_UPLOAD_EMBEDDED_BUNDLE is 0', async () => {
@@ -393,7 +417,9 @@ describe(androidBuilder, () => {
await androidBuilder(ctx);
expect(uploadEmbeddedBundleAsync).toHaveBeenCalledWith(ctx);
expect(uploadEmbeddedBundleAsync).toHaveBeenCalledWith(
expect.objectContaining({ job: ctx.job })
);
});
});
});
+14 -2
View File
@@ -11,6 +11,7 @@ import {
runGradleCommand,
} from '../android/gradle';
import { formatGradleProfileReport, parseGradleProfile } from '../android/gradleProfile';
import { resolveArtifactPath } from '../android/resolve';
import { Sentry } from '../sentry';
import { eagerBundleAsync, shouldUseEagerBundle } from '../common/eagerBundle';
import { prebuildAsync } from '../common/prebuild';
@@ -220,7 +221,7 @@ async function buildInnerAsync(
await ctx.runBuildPhase(BuildPhase.UPLOAD_APPLICATION_ARCHIVE, async () => {
await uploadApplicationArchive(ctx, {
patternOrPath: ctx.job.applicationArchivePath ?? 'android/app/build/outputs/**/*.{apk,aab}',
patternOrPath: resolveArtifactPath(ctx.job),
rootDir: ctx.getReactNativeProjectDirectory(),
logger: ctx.logger,
});
@@ -228,7 +229,18 @@ async function buildInnerAsync(
if (shouldUploadEmbeddedBundle(ctx)) {
await ctx.runBuildPhase(BuildPhase.UPLOAD_EMBEDDED_BUNDLE, async () => {
await uploadEmbeddedBundleAsync(ctx);
const { status } = await uploadEmbeddedBundleAsync({
job: ctx.job,
env: ctx.env,
logger: ctx.logger,
projectDir: ctx.getReactNativeProjectDirectory(),
appConfig: await ctx.appConfig,
});
if (status === 'skipped') {
ctx.markBuildPhaseSkipped();
} else if (status === 'failed') {
ctx.markBuildPhaseHasWarnings();
}
});
}
+13 -2
View File
@@ -237,7 +237,7 @@ async function buildInnerAsync(
await ctx.runBuildPhase(BuildPhase.UPLOAD_APPLICATION_ARCHIVE, async () => {
await uploadApplicationArchive(ctx, {
patternOrPath: resolveArtifactPath(ctx),
patternOrPath: resolveArtifactPath(ctx.job),
rootDir: ctx.getReactNativeProjectDirectory(),
logger: ctx.logger,
});
@@ -245,7 +245,18 @@ async function buildInnerAsync(
if (shouldUploadEmbeddedBundle(ctx)) {
await ctx.runBuildPhase(BuildPhase.UPLOAD_EMBEDDED_BUNDLE, async () => {
await uploadEmbeddedBundleAsync(ctx);
const { status } = await uploadEmbeddedBundleAsync({
job: ctx.job,
env: ctx.env,
logger: ctx.logger,
projectDir: ctx.getReactNativeProjectDirectory(),
appConfig: await ctx.appConfig,
});
if (status === 'skipped') {
ctx.markBuildPhaseSkipped();
} else if (status === 'failed') {
ctx.markBuildPhaseHasWarnings();
}
});
}
+4 -4
View File
@@ -15,10 +15,10 @@ export function resolveScheme(ctx: BuildContext<Ios.Job>): string {
return schemes[0];
}
export function resolveArtifactPath(ctx: BuildContext<Ios.Job>): string {
if (ctx.job.applicationArchivePath) {
return ctx.job.applicationArchivePath;
} else if (ctx.job.simulator) {
export function resolveArtifactPath(job: Ios.Job): string {
if (job.applicationArchivePath) {
return job.applicationArchivePath;
} else if (job.simulator) {
return 'ios/build/Build/Products/*simulator/*.app';
} else {
return 'ios/build/*.ipa';
@@ -61,6 +61,7 @@ import { createStartSandboxBuildFunction } from './functions/startSandbox';
import { createCollectServeSimMetricsBuildFunction } from './functions/collectServeSimMetrics';
import { createUploadArtifactBuildFunction } from './functions/uploadArtifact';
import { createUploadDeviceRunSessionScreenRecordingsBuildFunction } from './functions/uploadDeviceRunSessionScreenRecordings';
import { createUploadEmbeddedBundleBuildFunction } from './functions/uploadEmbeddedBundle';
import { createUploadToAscBuildFunction } from './functions/uploadToAsc';
import { createUpdateTestFlightMetadataBuildFunction } from './functions/updateTestFlightMetadata';
import { createSetUpNpmrcBuildFunction } from './functions/useNpmToken';
@@ -145,6 +146,7 @@ export function getEasFunctions(ctx: CustomBuildContext): BuildFunction[] {
functions.push(
...[
createFindAndUploadBuildArtifactsBuildFunction(ctx),
createUploadEmbeddedBundleBuildFunction(ctx),
createResolveBuildConfigBuildFunction(ctx),
createGetCredentialsForBuildTriggeredByGithubIntegration(ctx),
]
@@ -219,4 +219,71 @@ describe(createEasBuildBuildFunctionGroup, () => {
'Build function group is not supported in generic jobs.'
);
});
describe('embedded bundle upload', () => {
function getStepNames(
options: Parameters<typeof createMockBuildToolsContext>[0],
{ sdkVersion, env = {} }: { sdkVersion?: string; env?: Record<string, string> }
): string[] {
const functionGroup = createEasBuildBuildFunctionGroup(createMockBuildToolsContext(options));
const globalCtx = createGlobalContextMock({
logger: createMockLogger(),
staticContextContent: { metadata: sdkVersion ? { sdkVersion } : null },
});
globalCtx.updateEnv(env);
return functionGroup
.createBuildStepsFromFunctionGroupCall(globalCtx)
.map(step => step.displayName);
}
it.each([
['Android', { platform: Platform.ANDROID }],
['Android with credentials', { platform: Platform.ANDROID, buildCredentials: { test: {} } }],
['iOS with credentials', { platform: Platform.IOS, buildCredentials: { test: {} } }],
])('uploads the embedded bundle after the build artifacts on SDK 58 (%s)', (_, options) => {
const stepNames = getStepNames(options, { sdkVersion: '58.0.0' });
expect(stepNames.indexOf('Upload embedded bundle')).toBe(
stepNames.indexOf('Find and upload build artifacts') + 1
);
});
it.each([
['Android', { platform: Platform.ANDROID }],
['Android with credentials', { platform: Platform.ANDROID, buildCredentials: { test: {} } }],
['iOS with credentials', { platform: Platform.IOS, buildCredentials: { test: {} } }],
])('passes ignore_error to the embedded bundle step (%s)', (_, options) => {
const functionGroup = createEasBuildBuildFunctionGroup(createMockBuildToolsContext(options));
const globalCtx = createGlobalContextMock({
logger: createMockLogger(),
staticContextContent: { metadata: { sdkVersion: '58.0.0' } },
});
const uploadStep = functionGroup
.createBuildStepsFromFunctionGroupCall(globalCtx)
.find(step => step.displayName === 'Upload embedded bundle');
expect(uploadStep).toBeDefined();
expect(uploadStep!.inputs?.find(input => input.id === 'ignore_error')?.rawValue).toBe(true);
});
it('does not upload the embedded bundle on SDK 57 without the opt-in', () => {
expect(getStepNames({}, { sdkVersion: '57.0.0' })).not.toContain('Upload embedded bundle');
});
it('uploads the embedded bundle on SDK 57 with the opt-in', () => {
expect(
getStepNames(
{},
{ sdkVersion: '57.0.0', env: { EAS_UPDATE_EXPERIMENTAL_UPLOAD_EMBEDDED_BUNDLE: '1' } }
)
).toContain('Upload embedded bundle');
});
it('does not upload the embedded bundle for iOS simulator builds', () => {
expect(
getStepNames({ platform: Platform.IOS, simulator: true }, { sdkVersion: '58.0.0' })
).not.toContain('Upload embedded bundle');
});
});
});
@@ -10,6 +10,7 @@ import path from 'path';
import { shouldUseEagerBundle } from '../../common/eagerBundle';
import { CustomBuildContext } from '../../customBuildContext';
import { shouldUploadEmbeddedBundle } from '../../utils/expoUpdatesEmbedded';
import { calculateEASUpdateRuntimeVersionFunction } from '../functions/calculateEASUpdateRuntimeVersion';
import { createCheckoutBuildFunction } from '../functions/checkout';
import { configureAndroidVersionFunction } from '../functions/configureAndroidVersion';
@@ -32,6 +33,7 @@ import {
import { runFastlaneFunction } from '../functions/runFastlane';
import { runGradleFunction } from '../functions/runGradle';
import { createSaveBuildCacheFunction } from '../functions/saveBuildCache';
import { createUploadEmbeddedBundleBuildFunction } from '../functions/uploadEmbeddedBundle';
import { createSetUpNpmrcBuildFunction } from '../functions/useNpmToken';
interface HelperFunctionsInput {
@@ -303,6 +305,19 @@ function createStepsForIosBuildWithCredentials({
createFindAndUploadBuildArtifactsBuildFunction(
buildToolsContext
).createBuildStepFromFunctionCall(globalCtx, { workingDirectory }),
...(shouldUploadEmbeddedBundle({
env: globalCtx.env,
metadata: globalCtx.staticContext.metadata,
})
? [
createUploadEmbeddedBundleBuildFunction(
buildToolsContext
).createBuildStepFromFunctionCall(globalCtx, {
workingDirectory,
callInputs: { ignore_error: true },
}),
]
: []),
saveCache,
createCacheStatsBuildFunction().createBuildStepFromFunctionCall(globalCtx, {
workingDirectory,
@@ -390,6 +405,19 @@ function createStepsForAndroidBuildWithoutCredentials({
createFindAndUploadBuildArtifactsBuildFunction(
buildToolsContext
).createBuildStepFromFunctionCall(globalCtx, { workingDirectory }),
...(shouldUploadEmbeddedBundle({
env: globalCtx.env,
metadata: globalCtx.staticContext.metadata,
})
? [
createUploadEmbeddedBundleBuildFunction(
buildToolsContext
).createBuildStepFromFunctionCall(globalCtx, {
workingDirectory,
callInputs: { ignore_error: true },
}),
]
: []),
saveCache,
createCacheStatsBuildFunction().createBuildStepFromFunctionCall(globalCtx, {
workingDirectory,
@@ -483,6 +511,19 @@ function createStepsForAndroidBuildWithCredentials({
createFindAndUploadBuildArtifactsBuildFunction(
buildToolsContext
).createBuildStepFromFunctionCall(globalCtx, { workingDirectory }),
...(shouldUploadEmbeddedBundle({
env: globalCtx.env,
metadata: globalCtx.staticContext.metadata,
})
? [
createUploadEmbeddedBundleBuildFunction(
buildToolsContext
).createBuildStepFromFunctionCall(globalCtx, {
workingDirectory,
callInputs: { ignore_error: true },
}),
]
: []),
saveCache,
createCacheStatsBuildFunction().createBuildStepFromFunctionCall(globalCtx, {
workingDirectory,
@@ -1,5 +1,6 @@
import { BuildRuntimePlatform, BuildStep } from '@expo/steps';
import spawn from '@expo/turtle-spawn';
import { fs, vol } from 'memfs';
import { createGlobalContextMock } from '../../../__tests__/utils/context';
import { createInstallMitmproxyBuildFunction } from '../installMitmproxy';
@@ -11,6 +12,58 @@ jest.mock('@expo/turtle-spawn', () => ({
const mockedSpawn = jest.mocked(spawn);
// An x86 Homebrew prefix, to check that the app is found from PATH and not from process.arch.
const APP = '/usr/local/Caskroom/mitmproxy/12.2.3/mitmproxy.app';
const LINK = '/usr/local/bin/mitmdump';
function installCask(): void {
vol.fromJSON({ [`${APP}/Contents/MacOS/mitmdump`]: '', '/usr/local/bin': null });
fs.symlinkSync(`${APP}/Contents/MacOS/mitmdump`, LINK);
}
/**
* `which` finds mitmdump once the cask is installed, `brew` installs it, `xattr -p` reports
* quarantine while `stuck` is set, and each `mitmdump --version` takes the next result.
*/
function mockCommands({
installed = false,
stuck = false,
runs = [],
}: {
installed?: boolean;
stuck?: boolean;
runs?: boolean[];
}): void {
if (installed) {
installCask();
}
mockedSpawn.mockImplementation((async (command: string, args: string[]) => {
if (command === 'which' && !installed) {
throw new Error('not found');
}
if (command === 'which') {
return { stdout: `${LINK}\n` };
}
if (command === 'brew' && !installed) {
installed = true;
installCask();
}
if (command === 'xattr' && args[0] === '-p' && !stuck) {
throw new Error('No such xattr: com.apple.quarantine');
}
if (command === 'mitmdump' && !runs.shift()) {
throw new Error('not found');
}
return { stdout: '' };
}) as never);
}
function spawnedCommands(): string[] {
return mockedSpawn.mock.calls.map(([command, args]) =>
command === 'xattr' ? `xattr ${args?.[0]}` : command
);
}
describe('createInstallMitmproxyBuildFunction', () => {
beforeEach(() => {
jest.clearAllMocks();
@@ -24,28 +77,51 @@ describe('createInstallMitmproxyBuildFunction', () => {
});
}
it('does not install when mitmdump is already on PATH', async () => {
mockedSpawn.mockResolvedValueOnce({} as never);
it('takes the app behind mitmdump on PATH out of quarantine before running it', async () => {
mockCommands({ installed: true, runs: [true] });
await createStep({ EAS_BUILD_RUNNER: 'eas-build' }).executeAsync();
expect(mockedSpawn).toHaveBeenCalledWith('mitmdump', ['--version'], expect.anything());
expect(mockedSpawn).toHaveBeenCalledTimes(1);
expect(mockedSpawn).toHaveBeenCalledWith(
'xattr',
['-dr', 'com.apple.quarantine', APP],
expect.anything()
);
expect(spawnedCommands()).toEqual(['which', 'xattr -dr', 'xattr -p', 'mitmdump']);
});
it('warns instead of installing outside EAS Build VMs', async () => {
mockedSpawn.mockRejectedValueOnce(new Error('not found'));
it('kills a mitmdump --version that does not return', async () => {
mockCommands({ installed: true, runs: [true] });
await createStep({ EAS_BUILD_RUNNER: 'eas-build' }).executeAsync();
expect(mockedSpawn).toHaveBeenCalledWith(
'mitmdump',
['--version'],
expect.objectContaining({ stdio: 'ignore', timeout: 60_000, killSignal: 'SIGKILL' })
);
});
it('does not run a mitmdump that stays quarantined', async () => {
mockCommands({ installed: true, stuck: true });
await expect(
createStep({ EAS_BUILD_RUNNER: 'eas-build' }).executeAsync()
).resolves.toBeUndefined();
expect(spawnedCommands()).not.toContain('mitmdump');
});
it('does not change quarantine outside EAS Build VMs', async () => {
mockCommands({ installed: true, stuck: true, runs: [true] });
await createStep({}).executeAsync();
expect(mockedSpawn).toHaveBeenCalledTimes(1);
expect(spawnedCommands()).toEqual(['mitmdump']);
});
it('installs the cask with Homebrew and leaves auto-update off', async () => {
mockedSpawn
.mockRejectedValueOnce(new Error('not found'))
.mockResolvedValueOnce({} as never)
.mockResolvedValueOnce({} as never);
it('installs the cask with Homebrew and takes it out of quarantine', async () => {
mockCommands({ runs: [false, true] });
await createStep({ EAS_BUILD_RUNNER: 'eas-build' }).executeAsync();
@@ -54,13 +130,19 @@ describe('createInstallMitmproxyBuildFunction', () => {
['install', '--cask', 'mitmproxy'],
expect.objectContaining({ env: expect.objectContaining({ HOMEBREW_NO_AUTO_UPDATE: '1' }) })
);
expect(spawnedCommands()).toEqual([
'which',
'mitmdump',
'brew',
'which',
'xattr -dr',
'xattr -p',
'mitmdump',
]);
});
it('does not fail the job when mitmdump is still not runnable', async () => {
mockedSpawn
.mockRejectedValueOnce(new Error('not found'))
.mockResolvedValueOnce({} as never)
.mockRejectedValueOnce(new Error('not found'));
mockCommands({ runs: [false, false] });
await expect(
createStep({ EAS_BUILD_RUNNER: 'eas-build' }).executeAsync()
@@ -0,0 +1,129 @@
import { ProjectConfig } from '@expo/config';
import { BuildJob } from '@expo/eas-build-job';
import { createGlobalContextMock } from '../../../__tests__/utils/context';
import { createTestAndroidJob } from '../../../__tests__/utils/job';
import { createMockLogger } from '../../../__tests__/utils/logger';
import { BuildContext } from '../../../context';
import { CustomBuildContext } from '../../../customBuildContext';
import { readAppConfig } from '../../../utils/appConfig';
import { uploadEmbeddedBundleAsync } from '../../../utils/expoUpdatesEmbedded';
import { createUploadEmbeddedBundleBuildFunction } from '../uploadEmbeddedBundle';
jest.mock('../../../utils/appConfig');
jest.mock('../../../utils/expoUpdatesEmbedded');
function mockAppConfig(updatesUrl: string | undefined): void {
jest.mocked(readAppConfig).mockResolvedValue({
exp: { name: 'my-app', slug: 'my-app', updates: updatesUrl ? { url: updatesUrl } : undefined },
} as ProjectConfig);
}
function createCustomContext(job: BuildJob): CustomBuildContext<BuildJob> {
return new CustomBuildContext(
new BuildContext(job, {
env: { __API_SERVER_URL: 'http://api.expo.test' },
logBuffer: { getLogs: () => [], getPhaseLogs: () => [] },
logger: createMockLogger(),
uploadArtifact: jest.fn(),
workingdir: '',
})
);
}
describe(createUploadEmbeddedBundleBuildFunction, () => {
const job = createTestAndroidJob({});
const customContext = createCustomContext(job);
beforeEach(() => {
jest.resetAllMocks();
});
it('uploads the embedded bundle from the working directory', async () => {
mockAppConfig('https://u.expo.dev/project-id');
jest.mocked(uploadEmbeddedBundleAsync).mockResolvedValue({ status: 'uploaded' });
const globalContext = createGlobalContextMock({});
globalContext.updateEnv({ EAS_BUILD_ID: 'build-123' });
const buildStep =
createUploadEmbeddedBundleBuildFunction(customContext).createBuildStepFromFunctionCall(
globalContext
);
await buildStep.executeAsync();
expect(uploadEmbeddedBundleAsync).toHaveBeenCalledWith(
expect.objectContaining({
job,
env: expect.objectContaining({ EAS_BUILD_ID: 'build-123' }),
projectDir: globalContext.defaultWorkingDirectory,
appConfig: expect.objectContaining({ updates: { url: 'https://u.expo.dev/project-id' } }),
})
);
});
it('logs when the embedded bundle upload is skipped', async () => {
mockAppConfig('https://u.expo.dev/project-id');
jest.mocked(uploadEmbeddedBundleAsync).mockResolvedValue({ status: 'skipped' });
const buildStep = createUploadEmbeddedBundleBuildFunction(
customContext
).createBuildStepFromFunctionCall(createGlobalContextMock({}));
await buildStep.executeAsync();
expect(buildStep.ctx.logger.info).toHaveBeenCalledWith('Skipping embedded bundle upload.');
});
it('fails the step when the upload fails', async () => {
mockAppConfig('https://u.expo.dev/project-id');
jest.mocked(uploadEmbeddedBundleAsync).mockResolvedValue({ status: 'failed' });
const buildStep = createUploadEmbeddedBundleBuildFunction(
customContext
).createBuildStepFromFunctionCall(createGlobalContextMock({}));
await expect(buildStep.executeAsync()).rejects.toThrow('Failed to upload embedded bundle.');
});
it('does not fail the step when the upload fails and ignore_error is set', async () => {
mockAppConfig('https://u.expo.dev/project-id');
jest.mocked(uploadEmbeddedBundleAsync).mockResolvedValue({ status: 'failed' });
const buildStep = createUploadEmbeddedBundleBuildFunction(
customContext
).createBuildStepFromFunctionCall(createGlobalContextMock({}), {
callInputs: { ignore_error: true },
});
await buildStep.executeAsync();
expect(buildStep.ctx.logger.warn).toHaveBeenCalledWith(
expect.objectContaining({ err: expect.any(Error) }),
'Failed to upload embedded bundle. Ignoring error.'
);
});
it('fails the step when the app config cannot be read', async () => {
jest.mocked(readAppConfig).mockRejectedValue(new Error('Invalid app config'));
const buildStep = createUploadEmbeddedBundleBuildFunction(
customContext
).createBuildStepFromFunctionCall(createGlobalContextMock({}));
await expect(buildStep.executeAsync()).rejects.toThrow('Invalid app config');
expect(uploadEmbeddedBundleAsync).not.toHaveBeenCalled();
});
it('does not fail the step when the app config cannot be read and ignore_error is set', async () => {
jest.mocked(readAppConfig).mockRejectedValue(new Error('Invalid app config'));
const buildStep = createUploadEmbeddedBundleBuildFunction(
customContext
).createBuildStepFromFunctionCall(createGlobalContextMock({}), {
callInputs: { ignore_error: true },
});
await buildStep.executeAsync();
expect(buildStep.ctx.logger.warn).toHaveBeenCalledWith(
expect.objectContaining({ err: expect.any(Error) }),
'Failed to upload embedded bundle. Ignoring error.'
);
expect(uploadEmbeddedBundleAsync).not.toHaveBeenCalled();
});
});
@@ -2,6 +2,7 @@ import { bunyan } from '@expo/logger';
import { asyncResult } from '@expo/results';
import { BuildFunction, BuildRuntimePlatform, BuildStepEnv } from '@expo/steps';
import spawn from '@expo/turtle-spawn';
import fs from 'node:fs';
import { Sentry } from '../../sentry';
@@ -13,7 +14,10 @@ export function createInstallMitmproxyBuildFunction(): BuildFunction {
__metricsId: 'eas/install_mitmproxy',
supportedRuntimePlatforms: [BuildRuntimePlatform.DARWIN],
fn: async ({ logger }, { env }) => {
if (await isMitmproxyAvailableAsync(env)) {
// Some images ship the cask, and its quarantined first launch can hang.
const canLaunch =
env.EAS_BUILD_RUNNER !== 'eas-build' || (await removeMitmproxyQuarantineAsync(env));
if (canLaunch && (await isMitmproxyAvailableAsync(env))) {
logger.info('mitmproxy is already installed.');
return;
}
@@ -28,9 +32,11 @@ export function createInstallMitmproxyBuildFunction(): BuildFunction {
try {
logger.info('Installing mitmproxy with Homebrew.');
await installMitmproxyWithHomebrewAsync({ env, logger });
if (!(await removeMitmproxyQuarantineAsync(env))) {
throw new Error('Could not launch mitmproxy because it is still quarantined.');
}
if (!(await isMitmproxyAvailableAsync(env))) {
throw new Error('`brew install --cask mitmproxy` succeeded but mitmdump is not on PATH.');
throw new Error('`brew install --cask mitmproxy` succeeded but mitmdump did not run.');
}
logger.info('Installed mitmproxy.');
} catch (err) {
@@ -48,7 +54,18 @@ export function createInstallMitmproxyBuildFunction(): BuildFunction {
}
async function isMitmproxyAvailableAsync(env: BuildStepEnv): Promise<boolean> {
return (await asyncResult(spawn('mitmdump', ['--version'], { env }))).ok;
// Kills a first launch that Gatekeeper still holds, if the quarantine check missed it. Without
// pipes, a child process that outlives mitmdump cannot hold the call open past the timeout.
return (
await asyncResult(
spawn('mitmdump', ['--version'], {
env,
stdio: 'ignore',
timeout: 60_000,
killSignal: 'SIGKILL',
})
)
).ok;
}
async function installMitmproxyWithHomebrewAsync({
@@ -63,3 +80,25 @@ async function installMitmproxyWithHomebrewAsync({
logger,
});
}
/**
* Gatekeeper has rejected the mitmproxy 12.2.3 cask as unnotarized since 2026-10-06, and a
* quarantined first launch then never returns. Takes the app behind the `mitmdump` on PATH out of
* quarantine, and returns false when it stays quarantined, so it is not launched.
*/
async function removeMitmproxyQuarantineAsync(env: BuildStepEnv): Promise<boolean> {
const which = await asyncResult(spawn('which', ['mitmdump'], { env, stdio: 'pipe' }));
const mitmdump = which.ok
? await fs.promises.realpath(which.value.stdout.trim()).catch(() => null)
: null;
if (!mitmdump) {
return true;
}
const appEnd = mitmdump.lastIndexOf('.app/');
const app = appEnd === -1 ? mitmdump : mitmdump.slice(0, appEnd + '.app'.length);
await asyncResult(spawn('xattr', ['-dr', 'com.apple.quarantine', app], { env, stdio: 'pipe' }));
const quarantined = await asyncResult(
spawn('xattr', ['-p', 'com.apple.quarantine', mitmdump], { env, stdio: 'pipe' })
);
return !quarantined.ok;
}
@@ -0,0 +1,57 @@
import { BuildJob, UserError } from '@expo/eas-build-job';
import { BuildFunction, BuildStepInput, BuildStepInputValueTypeName } from '@expo/steps';
import { CustomBuildContext } from '../../customBuildContext';
import { readAppConfig } from '../../utils/appConfig';
import { uploadEmbeddedBundleAsync } from '../../utils/expoUpdatesEmbedded';
export function createUploadEmbeddedBundleBuildFunction(
ctx: CustomBuildContext<BuildJob>
): BuildFunction {
return new BuildFunction({
namespace: 'eas',
id: 'upload_embedded_bundle',
name: 'Upload embedded bundle',
__metricsId: 'eas/upload_embedded_bundle',
inputProviders: [
BuildStepInput.createProvider({
id: 'ignore_error',
required: false,
allowedValueTypeName: BuildStepInputValueTypeName.BOOLEAN,
}),
],
fn: async (stepCtx, { env, inputs }) => {
try {
const appConfig = (
await readAppConfig({
projectDir: stepCtx.workingDirectory,
env,
logger: stepCtx.logger,
sdkVersion: stepCtx.global.staticContext.metadata?.sdkVersion,
})
).exp;
const { status } = await uploadEmbeddedBundleAsync({
job: ctx.job,
env,
logger: stepCtx.logger,
projectDir: stepCtx.workingDirectory,
appConfig,
});
if (status === 'skipped') {
stepCtx.logger.info('Skipping embedded bundle upload.');
} else if (status === 'failed') {
throw new UserError(
'EAS_UPLOAD_EMBEDDED_BUNDLE_FAILED',
'Failed to upload embedded bundle. See the warning above for details.'
);
}
} catch (err) {
if (inputs.ignore_error.value) {
stepCtx.logger.warn({ err }, 'Failed to upload embedded bundle. Ignoring error.');
return;
}
throw err;
}
},
});
}
@@ -0,0 +1,400 @@
import { type bunyan } from '@expo/logger';
import { BuildRuntimePlatform } from '@expo/steps';
import spawn from '@expo/turtle-spawn';
import { Client, fetchExchange } from '@urql/core';
import { readFile, readdir, writeFile } from 'node:fs/promises';
import { Readable } from 'node:stream';
import os from 'node:os';
import fetch from 'node-fetch';
import { type CustomBuildContext } from '../../../customBuildContext';
import {
captureDeviceRunSessionPreviewAsync,
ensureMacosPreviewEncoderInstalledAsync,
startDeviceRunSessionPreview,
} from '../deviceRunSessionPreview';
jest.mock('node-fetch');
jest.mock('@expo/turtle-spawn');
const { Response } = jest.requireActual('node-fetch') as typeof import('node-fetch');
describe(startDeviceRunSessionPreview, () => {
const image = Buffer.from('webp-image');
let captureAsync: jest.Mock<Promise<Buffer>, [AbortSignal]>;
let mutation: jest.Mock;
let logger: bunyan;
let ctx: CustomBuildContext;
let preview: ReturnType<typeof startDeviceRunSessionPreview> | undefined;
beforeEach(() => {
jest.useFakeTimers();
captureAsync = jest.fn().mockResolvedValue(image);
mutation = jest.fn().mockReturnValue({
toPromise: async () => ({
data: {
deviceRunSession: {
createPreviewUploadSession: {
uploadSession: {
url: 'https://uploads.expo.test/preview',
headers: { 'content-type': 'image/webp' },
},
},
},
},
}),
});
ctx = { graphqlClient: { mutation } } as unknown as CustomBuildContext;
logger = { warn: jest.fn() } as unknown as bunyan;
jest
.mocked(fetch)
.mockReset()
.mockResolvedValue(new Response('', { status: 200 }));
});
afterEach(async () => {
await preview?.stopAsync();
preview = undefined;
jest.useRealTimers();
});
const start = () => {
preview = startDeviceRunSessionPreview({
ctx,
deviceRunSessionId: 'session-id',
captureAsync,
logger,
});
return preview;
};
it('uploads immediately and reuses the URL every 60 seconds', async () => {
start();
await jest.advanceTimersByTimeAsync(0);
expect(fetch).toHaveBeenCalledWith(
'https://uploads.expo.test/preview',
expect.objectContaining({
method: 'PUT',
body: image,
headers: { 'content-type': 'image/webp' },
})
);
await jest.advanceTimersByTimeAsync(59_999);
expect(captureAsync).toHaveBeenCalledTimes(1);
await jest.advanceTimersByTimeAsync(1);
expect(captureAsync).toHaveBeenCalledTimes(2);
expect(mutation).toHaveBeenCalledTimes(1);
await preview!.stopAsync();
await jest.advanceTimersByTimeAsync(120_000);
expect(captureAsync).toHaveBeenCalledTimes(2);
});
it('retries capture errors without creating an empty artifact', async () => {
captureAsync.mockRejectedValueOnce(new Error('device not ready'));
start();
await jest.advanceTimersByTimeAsync(0);
expect(mutation).not.toHaveBeenCalled();
expect(logger.warn).toHaveBeenCalled();
await jest.advanceTimersByTimeAsync(60_000);
expect(fetch).toHaveBeenCalledTimes(1);
});
it('retries a failed upload with the same URL', async () => {
jest.mocked(fetch).mockResolvedValueOnce(new Response('', { status: 403 }));
start();
await jest.advanceTimersByTimeAsync(60_000);
expect(mutation).toHaveBeenCalledTimes(1);
expect(fetch).toHaveBeenCalledTimes(2);
});
it('does not log the signed upload URL when the upload request fails', async () => {
const { FetchError } = jest.requireActual('node-fetch') as typeof import('node-fetch');
jest
.mocked(fetch)
.mockRejectedValueOnce(
new FetchError('network timeout at: https://uploads.expo.test/preview', 'request-timeout')
);
start();
await jest.advanceTimersByTimeAsync(0);
expect(logger.warn).toHaveBeenCalledTimes(1);
const [fields] = jest.mocked(logger.warn).mock.calls[0] as unknown as [{ err: Error }];
expect(fields.err.message).toBe(
'Session preview upload request failed (name: FetchError, type: request-timeout).'
);
expect(JSON.stringify(jest.mocked(logger.warn).mock.calls)).not.toContain('uploads.expo.test');
});
it('reuses the upload URL for the full session', async () => {
start();
await jest.advanceTimersByTimeAsync(119 * 60_000);
expect(mutation).toHaveBeenCalledTimes(1);
});
it('does not overlap captures and aborts pending work when stopped', async () => {
captureAsync.mockImplementation(
signal =>
new Promise((_, reject) => {
signal.addEventListener('abort', () => reject(new Error('aborted')), { once: true });
})
);
const handle = start();
await jest.advanceTimersByTimeAsync(60_000);
expect(captureAsync).toHaveBeenCalledTimes(1);
await handle.stopAsync();
expect(captureAsync.mock.calls[0][0].aborted).toBe(true);
expect(fetch).not.toHaveBeenCalled();
});
it('does not upload a capture that finishes after shutdown', async () => {
let finish!: (image: Buffer) => void;
captureAsync.mockImplementation(
() =>
new Promise(resolve => {
finish = resolve;
})
);
const handle = start();
const stopping = handle.stopAsync();
finish(image);
await stopping;
expect(mutation).not.toHaveBeenCalled();
});
});
describe('session preview with the real GraphQL client', () => {
const uploadSession = {
url: 'https://uploads.expo.test/preview',
headers: { 'content-type': 'image/webp' },
};
let graphqlFetch: jest.SpyInstance;
let preview: ReturnType<typeof startDeviceRunSessionPreview> | undefined;
let logger: bunyan;
beforeEach(() => {
jest.useFakeTimers();
graphqlFetch = jest.spyOn(globalThis, 'fetch').mockResolvedValue(
new globalThis.Response(
JSON.stringify({
data: { deviceRunSession: { createPreviewUploadSession: { uploadSession } } },
}),
{ headers: { 'content-type': 'application/json' } }
)
);
logger = { warn: jest.fn() } as unknown as bunyan;
jest
.mocked(fetch)
.mockReset()
.mockResolvedValue(new Response('', { status: 200 }));
});
afterEach(async () => {
await preview?.stopAsync();
preview = undefined;
jest.restoreAllMocks();
jest.useRealTimers();
});
const start = () => {
const graphqlClient = new Client({
url: 'https://api.expo.test/graphql',
exchanges: [fetchExchange],
fetchOptions: { headers: { Authorization: 'Bearer worker-token' } },
});
preview = startDeviceRunSessionPreview({
ctx: { graphqlClient } as CustomBuildContext,
deviceRunSessionId: 'session-id',
captureAsync: async () => Buffer.from('webp-image'),
logger,
});
return preview;
};
it('preserves the worker authentication when creating the upload session', async () => {
start();
await jest.advanceTimersByTimeAsync(0);
const [, options] = graphqlFetch.mock.calls[0];
expect(new Headers(options.headers).get('authorization')).toBe('Bearer worker-token');
expect(fetch).toHaveBeenCalledTimes(1);
});
it.each(['shutdown', 'timeout'])('aborts a stalled GraphQL request on %s', async reason => {
const timeout = new AbortController();
jest.spyOn(AbortSignal, 'timeout').mockReturnValue(timeout.signal);
let requestSignal: AbortSignal | undefined;
let rejectRequest!: (error: Error) => void;
graphqlFetch.mockImplementation(
(_url, options) =>
new Promise((_, reject) => {
rejectRequest = reject;
requestSignal = options.signal;
requestSignal!.addEventListener('abort', () => reject(requestSignal!.reason), {
once: true,
});
})
);
const handle = start();
await jest.advanceTimersByTimeAsync(0);
let stopped = false;
let stopping: Promise<void> | undefined;
if (reason === 'shutdown') {
stopping = handle.stopAsync().then(() => {
stopped = true;
});
} else {
timeout.abort(new Error('preview attempt timed out'));
}
await jest.advanceTimersByTimeAsync(0);
const aborted = requestSignal!.aborted;
const stoppedAfterAbort = stopped;
// Always release the fake transport so a regression cannot hang test cleanup.
rejectRequest(new Error('test cleanup'));
await jest.advanceTimersByTimeAsync(0);
expect(aborted).toBe(true);
expect(fetch).not.toHaveBeenCalled();
if (stopping) {
expect(stoppedAfterAbort).toBe(true);
await stopping;
} else {
expect(logger.warn).toHaveBeenCalled();
graphqlFetch.mockResolvedValue(
new globalThis.Response(
JSON.stringify({
data: { deviceRunSession: { createPreviewUploadSession: { uploadSession } } },
}),
{ headers: { 'content-type': 'application/json' } }
)
);
jest.spyOn(AbortSignal, 'timeout').mockReturnValue(new AbortController().signal);
await jest.advanceTimersByTimeAsync(60_000);
expect(fetch).toHaveBeenCalledTimes(1);
}
});
});
describe(captureDeviceRunSessionPreviewAsync, () => {
const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0xff, 0x00]);
const webp = Buffer.from('encoded-webp');
const resized = Buffer.from('resized-png');
it.each([
[BuildRuntimePlatform.DARWIN, 'selected-device'],
[BuildRuntimePlatform.LINUX, 'selected-device'],
[BuildRuntimePlatform.LINUX, 'no-device-id'],
] as const)(
'captures the selected device on %s and removes temporary files',
async (runtimePlatform, device) => {
jest.mocked(spawn).mockImplementation((command, args) => {
if (command === 'adb' && args[0] === 'devices') {
return Promise.resolve({
stdout: 'List of devices attached\nselected-device\tdevice\noffline-device\toffline\n',
}) as ReturnType<typeof spawn>;
}
if (command === 'adb') {
expect(args).toEqual(['-s', 'selected-device', 'exec-out', 'screencap', '-p']);
return Object.assign(Promise.resolve({ stdout: '', stderr: '' }), {
child: { stdout: Readable.from([png]) },
}) as ReturnType<typeof spawn>;
}
return (async () => {
if (command === 'xcrun') {
expect(args.slice(0, 4)).toEqual(['simctl', 'io', 'selected-device', 'screenshot']);
await writeFile(args[4], Uint8Array.from(png));
} else if (command === 'sips') {
expect(args.slice(0, 2)).toEqual(['-Z', '320']);
expect(await readFile(args[2])).toEqual(png);
await writeFile(args[args.indexOf('--out') + 1], Uint8Array.from(resized));
} else if (command === 'cwebp') {
expect(await readFile(args[args.indexOf('-o') - 1])).toEqual(resized);
await writeFile(args[args.indexOf('-o') + 1], Uint8Array.from(webp));
} else {
// Homebrew's FFmpeg cannot encode WebP, so macOS must not use it.
expect(runtimePlatform).toBe(BuildRuntimePlatform.LINUX);
expect(command).toBe('ffmpeg');
expect(await readFile(args[args.indexOf('-i') + 1])).toEqual(png);
expect(args).toContain('libwebp');
await writeFile(args[args.length - 1], Uint8Array.from(webp));
}
return { stdout: '', stderr: '' };
})() as ReturnType<typeof spawn>;
});
expect(
await captureDeviceRunSessionPreviewAsync({
runtimePlatform,
device,
env: {},
signal: new AbortController().signal,
})
).toEqual(webp);
expect(
(await readdir(os.tmpdir())).filter(name => name.startsWith('session-preview-'))
).toEqual([]);
}
);
it('skips ambiguous Android devices instead of capturing the wrong screen', async () => {
jest
.mocked(spawn)
.mockResolvedValue({ stdout: 'device-one\tdevice\ndevice-two\tdevice\n' } as Awaited<
ReturnType<typeof spawn>
>);
await expect(
captureDeviceRunSessionPreviewAsync({
runtimePlatform: BuildRuntimePlatform.LINUX,
device: 'no-device-id',
env: {},
signal: new AbortController().signal,
})
).rejects.toThrow('Expected exactly one connected Android device');
});
it('cleans up temporary files when capture fails', async () => {
jest.mocked(spawn).mockRejectedValue(new Error('capture failed'));
await expect(
captureDeviceRunSessionPreviewAsync({
runtimePlatform: BuildRuntimePlatform.DARWIN,
device: 'device',
env: {},
signal: new AbortController().signal,
})
).rejects.toThrow('capture failed');
expect(
(await readdir(os.tmpdir())).filter(name => name.startsWith('session-preview-'))
).toEqual([]);
});
});
describe(ensureMacosPreviewEncoderInstalledAsync, () => {
const logger = { info: jest.fn() } as unknown as bunyan;
it.each([true, false])(
'installs webp only when cwebp is missing (present: %s)',
async present => {
jest.mocked(spawn).mockReset();
jest
.mocked(spawn)
.mockImplementation(
command =>
(command === 'cwebp' && !present
? Promise.reject(new Error('command not found: cwebp'))
: Promise.resolve({ stdout: '', stderr: '' })) as ReturnType<typeof spawn>
);
await ensureMacosPreviewEncoderInstalledAsync({ env: { HOME: '/Users/expo' }, logger });
const brewCalls = jest.mocked(spawn).mock.calls.filter(([command]) => command === 'brew');
if (present) {
expect(brewCalls).toEqual([]);
} else {
expect(brewCalls).toEqual([
[
'brew',
['install', 'webp'],
{ env: { HOME: '/Users/expo', HOMEBREW_NO_AUTO_UPDATE: '1' }, logger },
],
]);
}
}
);
it('rejects when webp cannot be installed', async () => {
jest.mocked(spawn).mockReset();
jest.mocked(spawn).mockRejectedValue(new Error('brew failed'));
await expect(ensureMacosPreviewEncoderInstalledAsync({ env: {}, logger })).rejects.toThrow(
'brew failed'
);
});
});
@@ -0,0 +1,200 @@
import type { bunyan } from '@expo/logger';
import type { BuildStepEnv } from '@expo/steps';
import { Client, fetchExchange } from '@urql/core';
import { execFileSync } from 'node:child_process';
import { copyFile, mkdir, mkdtemp, rm, stat, writeFile } from 'node:fs/promises';
import { type IncomingMessage, type ServerResponse, createServer } from 'node:http';
import { tmpdir } from 'node:os';
import path from 'node:path';
import type { CustomBuildContext } from '../../../customBuildContext';
import {
findUnlistedDeviceScreenRecordingsAsync,
uploadDeviceRunSessionScreenRecordingsAsync,
} from '../deviceRunSessionScreenRecordings';
// Runs with `yarn jest-ffmpeg`, which needs ffmpeg and ffprobe on PATH.
jest.unmock('node-fetch');
jest.unmock('node:fs');
jest.unmock('node:fs/promises');
let handle: (request: IncomingMessage, response: ServerResponse) => void;
let server: ReturnType<typeof createServer>;
let ctx: CustomBuildContext;
let url: string;
let directory: string;
let creationBodies: string[];
beforeEach(async () => {
creationBodies = [];
directory = await mkdtemp(path.join(tmpdir(), 'recording-recovery-'));
server = createServer((request, response) => {
if (request.url === '/graphql') {
request.setEncoding('utf8');
let body = '';
request.on('data', chunk => (body += chunk));
request.on('end', () => {
creationBodies.push(body);
response.setHeader('Content-Type', 'application/json');
response.end(
JSON.stringify({
data: {
deviceRunSession: {
createArtifactUploadSession: {
uploadSession: { url: `${url}/artifact`, headers: {} },
},
},
},
})
);
});
} else {
handle(request, response);
}
});
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (!address || typeof address === 'string') {
throw new Error('Missing test server address');
}
url = `http://127.0.0.1:${address.port}`;
ctx = {
graphqlClient: new Client({
url: `${url}/graphql`,
exchanges: [fetchExchange],
fetchOptions: { headers: { Authorization: 'Bearer test-auth' } },
}),
} as CustomBuildContext;
});
afterEach(async () => {
server.closeAllConnections();
await new Promise<void>(resolve => server.close(() => resolve()));
await rm(directory, { recursive: true, force: true });
});
it('recovers unlisted recordings from a killed host and flags the unfinished ones as partial', async () => {
const logger = { info: jest.fn(), warn: jest.fn() } as unknown as bunyan;
const env = process.env as BuildStepEnv;
const cut = path.join(directory, 'cut');
const empty = path.join(directory, 'empty');
const failed = path.join(directory, 'failed');
const done = path.join(directory, 'done');
await mkdir(cut);
await mkdir(empty);
await mkdir(failed);
await mkdir(done);
const manifest = {
udid: 'emulator-5554',
deviceName: 'Pixel',
runtimeDisplayName: 'Android 16',
status: 'recording',
recording: 'recording.mp4.partial',
firstFrameWallClock: { iso8601: '2026-07-10T10:00:00.000Z' },
width: 128,
height: 96,
};
execFileSync('ffmpeg', [
'-v',
'error',
'-f',
'lavfi',
'-i',
'color=c=red:s=128x96:r=1',
'-t',
'3',
'-c:v',
'libx264',
'-g',
'1',
'-pix_fmt',
'yuv420p',
'-movflags',
'frag_keyframe+empty_moov',
'-f',
'mp4',
path.join(cut, 'recording.mp4.partial'),
]);
await writeFile(path.join(cut, 'session.json'), JSON.stringify(manifest));
await writeFile(path.join(empty, 'recording.mp4.partial'), new Uint8Array(28));
await writeFile(path.join(empty, 'session.json'), JSON.stringify(manifest));
await copyFile(
path.join(cut, 'recording.mp4.partial'),
path.join(failed, 'recording.mp4.partial')
);
await writeFile(
path.join(failed, 'session.json'),
JSON.stringify({
...manifest,
status: 'failed',
error: 'Recording finalization exceeded 30000 ms.',
})
);
await copyFile(path.join(cut, 'recording.mp4.partial'), path.join(done, 'recording.mp4'));
await writeFile(
path.join(done, 'session.json'),
JSON.stringify({ ...manifest, status: 'complete', recording: 'recording.mp4' })
);
const recordings = await findUnlistedDeviceScreenRecordingsAsync({
root: directory,
env,
logger,
});
expect(recordings).toEqual([
{
udid: 'emulator-5554',
deviceName: 'Pixel',
runtimeDisplayName: 'Android 16',
directory: cut,
},
{
udid: 'emulator-5554',
deviceName: 'Pixel',
runtimeDisplayName: 'Android 16',
directory: done,
},
{
udid: 'emulator-5554',
deviceName: 'Pixel',
runtimeDisplayName: 'Android 16',
directory: failed,
},
]);
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('empty/recording.mp4.partial'));
let putBytes = 0;
handle = (request, response) => {
request.on('data', chunk => (putBytes += chunk.length));
request.on('end', () => {
response.statusCode = 200;
response.end();
});
};
await expect(
uploadDeviceRunSessionScreenRecordingsAsync(ctx, {
logger,
deviceRunSessionId: 'drs-id',
recordings,
})
).resolves.toBe(true);
expect(putBytes).toBe(3 * (await stat(path.join(cut, 'recording.mp4.partial'))).size);
const inputs = creationBodies
.map(body => JSON.parse(body).variables.input)
.sort((a, b) => a.filename.localeCompare(b.filename));
expect(inputs.map(input => input.filename)).toEqual(['cut.mp4', 'done.mp4', 'failed.mp4']);
expect(inputs.map(input => input.name.includes(', partial)'))).toEqual([true, false, true]);
expect(inputs[1].metadata).not.toHaveProperty('partial');
expect(inputs[0].metadata).toMatchObject({
partial: true,
partialReason: 'The Device Hub stopped before it could finalize the recording.',
width: 128,
height: 96,
});
expect(inputs[2].metadata).toMatchObject({
partial: true,
partialReason: 'Recording finalization exceeded 30000 ms.',
});
});
@@ -1,9 +1,8 @@
import type { bunyan } from '@expo/logger';
import type { BuildStepEnv } from '@expo/steps';
import { Client, fetchExchange } from '@urql/core';
import { execFileSync } from 'node:child_process';
import { createReadStream } from 'node:fs';
import { copyFile, mkdir, mkdtemp, rm, stat, writeFile } from 'node:fs/promises';
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import { type IncomingMessage, type ServerResponse, createServer } from 'node:http';
import type { Socket } from 'node:net';
import { tmpdir } from 'node:os';
@@ -13,10 +12,7 @@ import { setTimeout as delay } from 'node:timers/promises';
import type { CustomBuildContext } from '../../../customBuildContext';
import { uploadDeviceRunSessionArtifactAsync } from '../deviceRunSessionArtifacts';
import {
findUnlistedDeviceScreenRecordingsAsync,
uploadDeviceRunSessionScreenRecordingsAsync,
} from '../deviceRunSessionScreenRecordings';
import { findUnlistedDeviceScreenRecordingsAsync } from '../deviceRunSessionScreenRecordings';
jest.unmock('node-fetch');
jest.unmock('node:fs');
@@ -47,13 +43,11 @@ let creates: number;
let authorization: string | undefined;
let stallCreation: boolean;
let creationStarted: ReturnType<typeof deferred<IncomingMessage>>;
let creationBodies: string[];
beforeEach(async () => {
creates = 0;
authorization = undefined;
stallCreation = false;
creationBodies = [];
creationStarted = deferred();
directory = await mkdtemp(path.join(tmpdir(), 'recording-upload-http-'));
server = createServer((request, response) => {
@@ -61,10 +55,7 @@ beforeEach(async () => {
creates++;
authorization = request.headers.authorization;
creationStarted.resolve(request);
request.setEncoding('utf8');
let body = '';
request.on('data', chunk => (body += chunk));
request.on('end', () => creationBodies.push(body));
request.resume();
request.on('end', () => {
if (stallCreation) {
return;
@@ -336,128 +327,3 @@ it('says ffprobe is missing instead of calling an unlisted recording undecodable
'ffprobe is not available; cannot recover the unlisted recording session/recording.mp4.partial.'
);
});
it('recovers unlisted recordings from a killed host and flags the unfinished ones as partial', async () => {
const logger = { info: jest.fn(), warn: jest.fn() } as unknown as bunyan;
const env = process.env as BuildStepEnv;
const cut = path.join(directory, 'cut');
const empty = path.join(directory, 'empty');
const failed = path.join(directory, 'failed');
const done = path.join(directory, 'done');
await mkdir(cut);
await mkdir(empty);
await mkdir(failed);
await mkdir(done);
const manifest = {
udid: 'emulator-5554',
deviceName: 'Pixel',
runtimeDisplayName: 'Android 16',
status: 'recording',
recording: 'recording.mp4.partial',
firstFrameWallClock: { iso8601: '2026-07-10T10:00:00.000Z' },
width: 128,
height: 96,
};
execFileSync('ffmpeg', [
'-v',
'error',
'-f',
'lavfi',
'-i',
'color=c=red:s=128x96:r=1',
'-t',
'3',
'-c:v',
'libx264',
'-g',
'1',
'-pix_fmt',
'yuv420p',
'-movflags',
'frag_keyframe+empty_moov',
'-f',
'mp4',
path.join(cut, 'recording.mp4.partial'),
]);
await writeFile(path.join(cut, 'session.json'), JSON.stringify(manifest));
await writeFile(path.join(empty, 'recording.mp4.partial'), new Uint8Array(28));
await writeFile(path.join(empty, 'session.json'), JSON.stringify(manifest));
await copyFile(
path.join(cut, 'recording.mp4.partial'),
path.join(failed, 'recording.mp4.partial')
);
await writeFile(
path.join(failed, 'session.json'),
JSON.stringify({
...manifest,
status: 'failed',
error: 'Recording finalization exceeded 30000 ms.',
})
);
await copyFile(path.join(cut, 'recording.mp4.partial'), path.join(done, 'recording.mp4'));
await writeFile(
path.join(done, 'session.json'),
JSON.stringify({ ...manifest, status: 'complete', recording: 'recording.mp4' })
);
const recordings = await findUnlistedDeviceScreenRecordingsAsync({
root: directory,
env,
logger,
});
expect(recordings).toEqual([
{
udid: 'emulator-5554',
deviceName: 'Pixel',
runtimeDisplayName: 'Android 16',
directory: cut,
},
{
udid: 'emulator-5554',
deviceName: 'Pixel',
runtimeDisplayName: 'Android 16',
directory: done,
},
{
udid: 'emulator-5554',
deviceName: 'Pixel',
runtimeDisplayName: 'Android 16',
directory: failed,
},
]);
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('empty/recording.mp4.partial'));
let putBytes = 0;
handle = (request, response) => {
request.on('data', chunk => (putBytes += chunk.length));
request.on('end', () => {
response.statusCode = 200;
response.end();
});
};
await expect(
uploadDeviceRunSessionScreenRecordingsAsync(ctx, {
logger,
deviceRunSessionId: 'drs-id',
recordings,
})
).resolves.toBe(true);
expect(putBytes).toBe(3 * (await stat(path.join(cut, 'recording.mp4.partial'))).size);
const inputs = creationBodies
.map(body => JSON.parse(body).variables.input)
.sort((a, b) => a.filename.localeCompare(b.filename));
expect(inputs.map(input => input.filename)).toEqual(['cut.mp4', 'done.mp4', 'failed.mp4']);
expect(inputs.map(input => input.name.includes(', partial)'))).toEqual([true, false, true]);
expect(inputs[1].metadata).not.toHaveProperty('partial');
expect(inputs[0].metadata).toMatchObject({
partial: true,
partialReason: 'The Device Hub stopped before it could finalize the recording.',
width: 128,
height: 96,
});
expect(inputs[2].metadata).toMatchObject({
partial: true,
partialReason: 'Recording finalization exceeded 30000 ms.',
});
});
@@ -12,8 +12,12 @@ import {
findUnlistedDeviceScreenRecordingsAsync,
uploadDeviceRunSessionScreenRecordingsAsync,
} from '../deviceRunSessionScreenRecordings';
import {
ensureMacosPreviewEncoderInstalledAsync,
startDeviceRunSessionPreview,
} from '../deviceRunSessionPreview';
import { startDeviceSessionHostAsync } from '../deviceSessionHost';
import { spawnDetached } from '../remoteDeviceRunSession';
import { ensureFfmpegInstalledOnceAsync, spawnDetached } from '../remoteDeviceRunSession';
jest.mock('@ngrok/ngrok');
jest.mock('../deviceRunSessionArtifacts');
@@ -30,6 +34,11 @@ jest.mock('../remoteDeviceRunSession', () => ({
fetchWebPreviewTurnArgsAsync: jest.fn().mockResolvedValue([]),
spawnDetached: jest.fn(),
}));
jest.mock('../deviceRunSessionPreview', () => ({
...jest.requireActual('../deviceRunSessionPreview'),
ensureMacosPreviewEncoderInstalledAsync: jest.fn(),
startDeviceRunSessionPreview: jest.fn(),
}));
jest.mock('../deviceRunSessionScreenRecordings', () => ({
...jest.requireActual('../deviceRunSessionScreenRecordings'),
findUnlistedDeviceScreenRecordingsAsync: jest.fn(),
@@ -64,8 +73,14 @@ async function startHostAsync() {
});
}
const stopSessionPreview = jest.fn();
beforeEach(() => {
jest.clearAllMocks();
stopSessionPreview.mockResolvedValue(undefined);
jest.mocked(startDeviceRunSessionPreview).mockReturnValue({ stopAsync: stopSessionPreview });
jest.mocked(ensureFfmpegInstalledOnceAsync).mockResolvedValue(undefined);
jest.mocked(ensureMacosPreviewEncoderInstalledAsync).mockResolvedValue(undefined);
stopServer.mockResolvedValue(undefined);
closeTunnel.mockResolvedValue(undefined);
jest.mocked(uploadDeviceRunSessionScreenRecordingsAsync).mockReset().mockResolvedValue(false);
@@ -502,3 +517,60 @@ it.each([BuildRuntimePlatform.LINUX, BuildRuntimePlatform.DARWIN])(
await expect(access(directory)).rejects.toMatchObject({ code: 'ENOENT' });
}
);
it.each([BuildRuntimePlatform.LINUX, BuildRuntimePlatform.DARWIN])(
'refreshes the session preview of the ready device until the %s host finishes',
async runtimePlatform => {
const host = await startDeviceSessionHostAsync(ctx, {
runtimePlatform,
env,
logger,
timeoutMs: 10_000,
});
await new Promise(resolve => setImmediate(resolve));
expect(startDeviceRunSessionPreview).toHaveBeenCalledTimes(1);
expect(startDeviceRunSessionPreview).toHaveBeenCalledWith(
expect.objectContaining({ deviceRunSessionId: 'drs-id', captureAsync: expect.any(Function) })
);
await host.finishAsync();
expect(stopSessionPreview).toHaveBeenCalledTimes(1);
expect(stopSessionPreview.mock.invocationCallOrder[0]).toBeLessThan(
stopServer.mock.invocationCallOrder[0]
);
}
);
it('does not delay macOS readiness on encoder setup or start the preview after finish', async () => {
const install = deferred<void>();
jest.mocked(ensureMacosPreviewEncoderInstalledAsync).mockReturnValueOnce(install.promise);
const host = await startDeviceSessionHostAsync(ctx, {
runtimePlatform: BuildRuntimePlatform.DARWIN,
env,
logger,
timeoutMs: 10_000,
});
await host.finishAsync();
install.resolve();
await new Promise(resolve => setImmediate(resolve));
expect(startDeviceRunSessionPreview).not.toHaveBeenCalled();
expect(stopServer).toHaveBeenCalledTimes(1);
});
it('keeps the session running when encoder setup for the preview fails', async () => {
jest
.mocked(ensureMacosPreviewEncoderInstalledAsync)
.mockRejectedValueOnce(new Error('brew failed'));
const host = await startDeviceSessionHostAsync(ctx, {
runtimePlatform: BuildRuntimePlatform.DARWIN,
env,
logger,
timeoutMs: 10_000,
});
await new Promise(resolve => setImmediate(resolve));
expect(startDeviceRunSessionPreview).not.toHaveBeenCalled();
expect(logger.warn).toHaveBeenCalledWith(
{ err: expect.objectContaining({ message: 'brew failed' }) },
'Could not start refreshing the session preview.'
);
await host.finishAsync();
});
@@ -0,0 +1,264 @@
import { type bunyan } from '@expo/logger';
import { asyncResult } from '@expo/results';
import { BuildRuntimePlatform, type BuildStepEnv } from '@expo/steps';
import spawn from '@expo/turtle-spawn';
import { graphql } from 'gql.tada';
import fetch from 'node-fetch';
import { createWriteStream } from 'node:fs';
import { pipeline } from 'node:stream/promises';
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { type CustomBuildContext } from '../../customBuildContext';
const PREVIEW_INTERVAL_MS = 60_000;
const PREVIEW_MAX_DIMENSION = 320;
const PREVIEW_QUALITY = 70;
const MAX_PREVIEW_SIZE_BYTES = 5 * 1024 * 1024;
const CREATE_PREVIEW_UPLOAD_SESSION_MUTATION = graphql(`
mutation CreateDeviceRunSessionPreviewUploadSession($deviceRunSessionId: ID!) {
deviceRunSession {
createPreviewUploadSession(deviceRunSessionId: $deviceRunSessionId) {
uploadSession {
url
headers
}
}
}
}
`);
/**
* node-fetch includes the request URL in its error messages, and this URL is a signed upload URL
* that is valid for the whole session. Replace such errors with one that names only the failure.
*/
async function putPreviewAsync(
uploadSession: { url: string; headers: Record<string, string> },
{ image, signal }: { image: Buffer; signal: AbortSignal }
): Promise<Awaited<ReturnType<typeof fetch>>> {
try {
return await fetch(uploadSession.url, {
method: 'PUT',
headers: uploadSession.headers,
body: image,
signal,
timeout: 30_000,
});
} catch (err) {
const { name, type, code } = err as { name?: unknown; type?: unknown; code?: unknown };
const details = Object.entries({ name, type, code })
.filter(([, value]) => typeof value === 'string' && value.length > 0)
.map(([key, value]) => `${key}: ${value}`)
.join(', ');
throw new Error(`Session preview upload request failed (${details || 'unknown error'}).`);
}
}
export function startDeviceRunSessionPreview({
ctx,
deviceRunSessionId,
captureAsync,
logger,
}: {
ctx: CustomBuildContext;
deviceRunSessionId: string;
captureAsync: (signal: AbortSignal) => Promise<Buffer>;
logger: bunyan;
}): { stopAsync: () => Promise<void> } {
const controller = new AbortController();
let timer: NodeJS.Timeout | undefined;
let uploadSession: { url: string; headers: Record<string, string> } | undefined;
let pending: Promise<void>;
const uploadAsync = async (): Promise<void> => {
const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(60_000)]);
try {
const image = await captureAsync(signal);
if (controller.signal.aborted) {
return;
}
if (image.length === 0 || image.length > MAX_PREVIEW_SIZE_BYTES) {
throw new Error('Session preview is empty or exceeds the 5 MiB upload limit.');
}
if (!uploadSession) {
const result = await ctx.graphqlClient
.mutation(
CREATE_PREVIEW_UPLOAD_SESSION_MUTATION,
{ deviceRunSessionId },
{
// Keep the client's auth headers and combine cancellation after URQL sets its signal.
fetch: (url, options) =>
globalThis.fetch(url, {
...options,
signal: AbortSignal.any([signal, ...(options?.signal ? [options.signal] : [])]),
}),
}
)
.toPromise();
if (result.error) {
throw result.error;
}
const session = result.data?.deviceRunSession.createPreviewUploadSession.uploadSession;
if (!session) {
throw new Error('No session preview upload URL was returned.');
}
uploadSession = {
url: session.url,
headers: session.headers as Record<string, string>,
};
}
if (controller.signal.aborted) {
return;
}
const response = await putPreviewAsync(uploadSession, { image, signal });
if (!response.ok) {
throw new Error(`Session preview upload failed: ${response.status} ${response.statusText}`);
}
} catch (err) {
if (!controller.signal.aborted) {
logger.warn({ err }, 'Could not refresh the session preview; retrying in 60 seconds.');
}
}
};
const tick = (): void => {
pending = uploadAsync().finally(() => {
if (!controller.signal.aborted) {
timer = setTimeout(tick, PREVIEW_INTERVAL_MS);
timer.unref();
}
});
};
tick();
return {
stopAsync: async () => {
controller.abort();
clearTimeout(timer);
await pending;
},
};
}
/**
* Homebrew's FFmpeg is built without libwebp, so macOS encodes previews with `cwebp` from
* Homebrew's webp package instead. Throws when it cannot be installed.
*/
export async function ensureMacosPreviewEncoderInstalledAsync({
env,
logger,
}: {
env: BuildStepEnv;
logger: bunyan;
}): Promise<void> {
if ((await asyncResult(spawn('cwebp', ['-version'], { env, stdio: 'pipe' }))).ok) {
return;
}
logger.info('Installing webp with Homebrew for the session preview.');
await spawn('brew', ['install', 'webp'], {
env: { ...env, HOMEBREW_NO_AUTO_UPDATE: '1' },
logger,
});
}
export async function captureDeviceRunSessionPreviewAsync({
runtimePlatform,
device,
env,
signal,
}: {
runtimePlatform: BuildRuntimePlatform;
device: string;
env: BuildStepEnv;
signal: AbortSignal;
}): Promise<Buffer> {
const directory = await mkdtemp(path.join(os.tmpdir(), 'session-preview-'));
try {
const options = { env, signal, timeout: 30_000, stdio: 'pipe' as const };
const preview = path.join(directory, 'preview.webp');
if (runtimePlatform === BuildRuntimePlatform.DARWIN) {
await captureIosPreviewAsync({ device, directory, preview, options });
} else {
await captureAndroidPreviewAsync({ device, directory, preview, options });
}
return await readFile(preview);
} finally {
await rm(directory, { recursive: true, force: true });
}
}
type CaptureOptions = {
env: BuildStepEnv;
signal: AbortSignal;
timeout: number;
stdio: 'pipe';
};
async function captureIosPreviewAsync({
device,
directory,
preview,
options,
}: {
device: string;
directory: string;
preview: string;
options: CaptureOptions;
}): Promise<void> {
const screenshot = path.join(directory, 'screen.png');
const resized = path.join(directory, 'resized.png');
await spawn('xcrun', ['simctl', 'io', device, 'screenshot', screenshot], options);
await spawn('sips', ['-Z', String(PREVIEW_MAX_DIMENSION), screenshot, '--out', resized], options);
await spawn('cwebp', ['-quiet', '-q', String(PREVIEW_QUALITY), resized, '-o', preview], options);
}
async function captureAndroidPreviewAsync({
device,
directory,
preview,
options,
}: {
device: string;
directory: string;
preview: string;
options: CaptureOptions;
}): Promise<void> {
const screenshot = path.join(directory, 'screen.png');
let serial = device;
// expo-device-hub's readiness endpoint currently reports a placeholder instead of a serial.
if (serial === 'no-device-id') {
const result = await spawn('adb', ['devices'], options);
const devices = result.stdout
.split('\n')
.map(line => line.trim().split(/\s+/))
.filter(([, status]) => status === 'device');
if (devices.length !== 1) {
throw new Error('Expected exactly one connected Android device for the session preview.');
}
serial = devices[0][0];
}
const capture = spawn('adb', ['-s', serial, 'exec-out', 'screencap', '-p'], options);
// Preserve binary PNG output instead of spawn-async's UTF-8 stdout conversion.
await Promise.all([
capture,
pipeline(capture.child.stdout!, createWriteStream(screenshot), { signal: options.signal }),
]);
await spawn(
'ffmpeg',
[
'-nostdin',
'-y',
'-i',
screenshot,
'-vf',
`scale=${PREVIEW_MAX_DIMENSION}:${PREVIEW_MAX_DIMENSION}:force_original_aspect_ratio=decrease`,
'-frames:v',
'1',
'-c:v',
'libwebp',
'-quality',
String(PREVIEW_QUALITY),
preview,
],
options
);
}
@@ -21,6 +21,11 @@ import {
parseDeviceScreenRecordings,
uploadDeviceRunSessionScreenRecordingsAsync,
} from './deviceRunSessionScreenRecordings';
import {
captureDeviceRunSessionPreviewAsync,
ensureMacosPreviewEncoderInstalledAsync,
startDeviceRunSessionPreview,
} from './deviceRunSessionPreview';
import { startDeviceRunSessionScreenshotsAsync } from './deviceRunSessionScreenshots';
import {
type DetachedProcessHandle,
@@ -379,6 +384,7 @@ export async function startDeviceSessionHostAsync(
let previewTask: Promise<DeviceWebPreview> | null = null;
let finishTask: Promise<void> | null = null;
let hostReady = false;
let sessionPreview: ReturnType<typeof startDeviceRunSessionPreview> | null = null;
const host: DeviceSessionHost = {
openPreviewAsync({ baseDomain }) {
@@ -436,6 +442,7 @@ export async function startDeviceSessionHostAsync(
finishAsync() {
return (finishTask ??= finishDeviceSessionHostAsync(ctx, {
previewTask,
stopSessionPreviewAsync: async () => await sessionPreview?.stopAsync(),
previewServer,
screenshots,
serverName,
@@ -467,6 +474,29 @@ export async function startDeviceSessionHostAsync(
}
IosSimulatorRecordingUtils.useServeSimPackage(packageSpec);
}
// Android installed FFmpeg before launching the host. The optional thumbnail must not delay
// readiness on macOS, so it starts after its encoder is installed there.
void (async () => {
if (!isAndroid) {
await ensureMacosPreviewEncoderInstalledAsync({ env, logger });
}
if (!finishTask) {
sessionPreview = startDeviceRunSessionPreview({
ctx,
deviceRunSessionId: getDeviceRunSessionIdOrThrow(env),
logger,
captureAsync: signal =>
captureDeviceRunSessionPreviewAsync({
runtimePlatform,
device,
env,
signal,
}),
});
}
})().catch(err => {
logger.warn({ err }, 'Could not start refreshing the session preview.');
});
return host;
} catch (error) {
await host.finishAsync();
@@ -478,6 +508,7 @@ async function finishDeviceSessionHostAsync(
ctx: CustomBuildContext,
{
previewTask,
stopSessionPreviewAsync,
previewServer,
screenshots,
serverName,
@@ -486,6 +517,7 @@ async function finishDeviceSessionHostAsync(
logger,
}: {
previewTask: Promise<DeviceWebPreview> | null;
stopSessionPreviewAsync: () => Promise<void>;
previewServer: DetachedProcessHandle;
screenshots: { finishAsync(hostStopped: boolean): Promise<void> };
serverName: string;
@@ -494,6 +526,8 @@ async function finishDeviceSessionHostAsync(
logger: bunyan;
}
): Promise<void> {
// Stop capturing before the host stops, so the last thumbnail shows the session, not shutdown.
await stopSessionPreviewAsync();
// Native ngrok operations have no scoped cancellation. Retire a late listener too.
const retirePreview = withDeviceRunSessionTimeoutAsync(
{ name: 'Preview tunnel retirement', timeoutMs: 5_000 },
@@ -1,12 +1,13 @@
import { Platform } from '@expo/eas-build-job';
import { PipeMode } from '@expo/logger';
import { BuildContext } from '../../context';
import * as expoUpdates from '../expoUpdates';
import * as expoUpdates from '../../steps/utils/expoUpdates';
import { uploadEmbeddedBundleAsync } from '../expoUpdatesEmbedded';
import * as easCli from '../easCli';
import * as artifacts from '../artifacts';
import { createMockLogger } from '../../__tests__/utils/logger';
jest.mock('../expoUpdates');
jest.mock('../../steps/utils/expoUpdates');
jest.mock('../easCli');
jest.mock('../artifacts');
@@ -29,13 +30,13 @@ function zipEntryMap(entries: Record<string, true>): Record<string, { name: stri
return Object.fromEntries(Object.keys(entries).map(name => [name, { name }]));
}
function makeCtx(overrides: {
function makeArgs(overrides: {
platform: Platform;
simulator?: boolean;
developmentClient?: boolean;
channel?: string;
env?: Record<string, string>;
}): BuildContext<any> {
}): Parameters<typeof uploadEmbeddedBundleAsync>[0] {
const job =
overrides.platform === Platform.IOS
? {
@@ -53,22 +54,19 @@ function makeCtx(overrides: {
return {
job,
env: overrides.env ?? {},
appConfig: Promise.resolve({
appConfig: {
name: 'my-app',
slug: 'my-app',
updates: { url: 'https://u.expo.dev/project-id' },
}),
logger: {
info: jest.fn(),
warn: jest.fn(),
},
markBuildPhaseSkipped: jest.fn(),
markBuildPhaseHasWarnings: jest.fn(),
getReactNativeProjectDirectory: () => '/project',
} as any;
logger: createMockLogger(),
projectDir: '/project',
} as Parameters<typeof uploadEmbeddedBundleAsync>[0];
}
describe('uploadEmbeddedBundleAsync', () => {
beforeEach(() => {
jest.mocked(expoUpdates.isEASUpdateConfigured).mockResolvedValue(true);
jest.mocked(expoUpdates.isEASUpdateConfigured).mockReturnValue(true);
jest.mocked(easCli.runEasCliCommand).mockResolvedValue({} as any);
jest.mocked(artifacts.findArtifacts).mockResolvedValue([]);
mockZipEntries.mockResolvedValue({});
@@ -82,33 +80,36 @@ describe('uploadEmbeddedBundleAsync', () => {
});
it('skips when EAS Update is not configured', async () => {
jest.mocked(expoUpdates.isEASUpdateConfigured).mockResolvedValue(false);
const ctx = makeCtx({ platform: Platform.ANDROID, channel: 'production' });
jest.mocked(expoUpdates.isEASUpdateConfigured).mockReturnValue(false);
const args = makeArgs({ platform: Platform.ANDROID, channel: 'production' });
await uploadEmbeddedBundleAsync(ctx);
const { status } = await uploadEmbeddedBundleAsync(args);
expect(ctx.markBuildPhaseSkipped).toHaveBeenCalled();
expect(status).toBe('skipped');
expect(artifacts.findArtifacts).not.toHaveBeenCalled();
});
it('warns when no channel is configured and does not look for the archive', async () => {
const ctx = makeCtx({ platform: Platform.ANDROID });
const args = makeArgs({ platform: Platform.ANDROID });
await uploadEmbeddedBundleAsync(ctx);
const { status } = await uploadEmbeddedBundleAsync(args);
expect(ctx.logger.warn).toHaveBeenCalledWith(
expect(args.logger.warn).toHaveBeenCalledWith(
'Skipping embedded bundle upload: no channel configured for this build profile.'
);
expect(ctx.markBuildPhaseHasWarnings).toHaveBeenCalled();
expect(status).toBe('failed');
expect(artifacts.findArtifacts).not.toHaveBeenCalled();
});
it('throws for an unsupported platform', async () => {
const ctx = makeCtx({ platform: Platform.ANDROID, channel: 'production' });
(ctx.job as { platform: string }).platform = 'web';
it('warns for an unsupported platform', async () => {
const args = makeArgs({ platform: Platform.ANDROID, channel: 'production' });
(args.job as { platform: string }).platform = 'web';
await expect(uploadEmbeddedBundleAsync(ctx)).rejects.toThrow(
'Uploading embedded updates is not supported for the web platform.'
const { status } = await uploadEmbeddedBundleAsync(args);
expect(status).toBe('failed');
expect(args.logger.warn).toHaveBeenCalledWith(
'Skipping embedded bundle upload: the web platform is not supported.'
);
expect(artifacts.findArtifacts).not.toHaveBeenCalled();
});
@@ -121,14 +122,18 @@ describe('uploadEmbeddedBundleAsync', () => {
'assets/app.manifest': true,
})
);
const ctx = makeCtx({
const args = makeArgs({
platform: Platform.ANDROID,
channel: 'production',
env: { EAS_BUILD_ID: 'build-123' },
});
await uploadEmbeddedBundleAsync(ctx);
const { status } = await uploadEmbeddedBundleAsync(args);
expect(status).toBe('uploaded');
expect(artifacts.findArtifacts).toHaveBeenCalledWith(
expect.objectContaining({ patternOrPath: 'android/app/build/outputs/**/*.{apk,aab}' })
);
expect(mockZipExtract).toHaveBeenCalledWith(
'assets/index.android.bundle',
expect.stringContaining('index.android.bundle')
@@ -144,10 +149,24 @@ describe('uploadEmbeddedBundleAsync', () => {
'--build-id',
'build-123',
]),
options: expect.objectContaining({ mode: PipeMode.COMBINED_AS_STDOUT }),
})
);
});
it('uses applicationArchivePath to find the archive', async () => {
const args = makeArgs({ platform: Platform.ANDROID, channel: 'production' });
await uploadEmbeddedBundleAsync({
...args,
job: { ...args.job, applicationArchivePath: 'custom/app.aab' },
});
expect(artifacts.findArtifacts).toHaveBeenCalledWith(
expect.objectContaining({ patternOrPath: 'custom/app.aab' })
);
});
it('uploads from Android AAB archives', async () => {
jest.mocked(artifacts.findArtifacts).mockResolvedValue(['/tmp/app-release.aab']);
mockZipEntries.mockResolvedValue(
@@ -156,10 +175,11 @@ describe('uploadEmbeddedBundleAsync', () => {
'base/assets/app.manifest': true,
})
);
const ctx = makeCtx({ platform: Platform.ANDROID, channel: 'production' });
const args = makeArgs({ platform: Platform.ANDROID, channel: 'production' });
await uploadEmbeddedBundleAsync(ctx);
const { status } = await uploadEmbeddedBundleAsync(args);
expect(status).toBe('uploaded');
expect(mockZipExtract).toHaveBeenCalledWith(
'base/assets/index.android.bundle',
expect.stringContaining('index.android.bundle')
@@ -175,10 +195,14 @@ describe('uploadEmbeddedBundleAsync', () => {
'Payload/App.app/EXUpdates.bundle/app.manifest': true,
})
);
const ctx = makeCtx({ platform: Platform.IOS, channel: 'production' });
const args = makeArgs({ platform: Platform.IOS, channel: 'production' });
await uploadEmbeddedBundleAsync(ctx);
const { status } = await uploadEmbeddedBundleAsync(args);
expect(status).toBe('uploaded');
expect(artifacts.findArtifacts).toHaveBeenCalledWith(
expect.objectContaining({ patternOrPath: 'ios/build/*.ipa' })
);
expect(easCli.runEasCliCommand).toHaveBeenCalledWith(
expect.objectContaining({
args: expect.arrayContaining(['--platform', Platform.IOS]),
@@ -187,25 +211,24 @@ describe('uploadEmbeddedBundleAsync', () => {
});
it('skips simulator builds', async () => {
const ctx = makeCtx({ platform: Platform.IOS, simulator: true, channel: 'preview' });
const args = makeArgs({ platform: Platform.IOS, simulator: true, channel: 'preview' });
await uploadEmbeddedBundleAsync(ctx);
const { status } = await uploadEmbeddedBundleAsync(args);
expect(ctx.markBuildPhaseSkipped).toHaveBeenCalled();
expect(status).toBe('skipped');
expect(artifacts.findArtifacts).not.toHaveBeenCalled();
});
it('skips development client builds', async () => {
const ctx = makeCtx({
const args = makeArgs({
platform: Platform.ANDROID,
developmentClient: true,
channel: 'development',
});
await uploadEmbeddedBundleAsync(ctx);
const { status } = await uploadEmbeddedBundleAsync(args);
expect(ctx.markBuildPhaseSkipped).toHaveBeenCalled();
expect(ctx.markBuildPhaseHasWarnings).not.toHaveBeenCalled();
expect(status).toBe('skipped');
expect(artifacts.findArtifacts).not.toHaveBeenCalled();
});
@@ -216,11 +239,12 @@ describe('uploadEmbeddedBundleAsync', () => {
'assets/app.manifest': true,
})
);
const ctx = makeCtx({ platform: Platform.ANDROID, channel: 'production' });
const args = makeArgs({ platform: Platform.ANDROID, channel: 'production' });
await uploadEmbeddedBundleAsync(ctx);
const { status } = await uploadEmbeddedBundleAsync(args);
expect(ctx.logger.warn).toHaveBeenCalledWith(
expect(status).toBe('failed');
expect(args.logger.warn).toHaveBeenCalledWith(
'Skipping embedded bundle upload: bundle or manifest not found in archive.'
);
expect(easCli.runEasCliCommand).not.toHaveBeenCalled();
@@ -228,27 +252,27 @@ describe('uploadEmbeddedBundleAsync', () => {
it('warns when build archive is not found', async () => {
jest.mocked(artifacts.findArtifacts).mockResolvedValue([]);
const ctx = makeCtx({ platform: Platform.ANDROID, channel: 'production' });
const args = makeArgs({ platform: Platform.ANDROID, channel: 'production' });
await uploadEmbeddedBundleAsync(ctx);
const { status } = await uploadEmbeddedBundleAsync(args);
expect(ctx.logger.warn).toHaveBeenCalledWith(
expect(args.logger.warn).toHaveBeenCalledWith(
'Skipping embedded bundle upload: build archive not found.'
);
expect(ctx.markBuildPhaseHasWarnings).toHaveBeenCalled();
expect(status).toBe('failed');
expect(easCli.runEasCliCommand).not.toHaveBeenCalled();
});
it('treats findArtifacts errors as no archive found', async () => {
jest.mocked(artifacts.findArtifacts).mockRejectedValue(new Error('glob failed'));
const ctx = makeCtx({ platform: Platform.ANDROID, channel: 'production' });
const args = makeArgs({ platform: Platform.ANDROID, channel: 'production' });
await uploadEmbeddedBundleAsync(ctx);
const { status } = await uploadEmbeddedBundleAsync(args);
expect(ctx.logger.warn).toHaveBeenCalledWith(
expect(args.logger.warn).toHaveBeenCalledWith(
'Skipping embedded bundle upload: build archive not found.'
);
expect(ctx.markBuildPhaseHasWarnings).toHaveBeenCalled();
expect(status).toBe('failed');
expect(easCli.runEasCliCommand).not.toHaveBeenCalled();
});
@@ -261,15 +285,15 @@ describe('uploadEmbeddedBundleAsync', () => {
})
);
jest.mocked(easCli.runEasCliCommand).mockRejectedValue(new Error('upload failed'));
const ctx = makeCtx({ platform: Platform.ANDROID, channel: 'production' });
const args = makeArgs({ platform: Platform.ANDROID, channel: 'production' });
await uploadEmbeddedBundleAsync(ctx);
const { status } = await uploadEmbeddedBundleAsync(args);
expect(ctx.logger.warn).toHaveBeenCalledWith(
expect(args.logger.warn).toHaveBeenCalledWith(
expect.objectContaining({ err: expect.any(Error) }),
'Failed to upload embedded bundle.'
);
expect(ctx.markBuildPhaseHasWarnings).toHaveBeenCalled();
expect(status).toBe('failed');
});
it('swallows zip.close() failures so they do not mask the upload result', async () => {
@@ -281,9 +305,9 @@ describe('uploadEmbeddedBundleAsync', () => {
})
);
mockZipClose.mockRejectedValue(new Error('close failed'));
const ctx = makeCtx({ platform: Platform.ANDROID, channel: 'production' });
const args = makeArgs({ platform: Platform.ANDROID, channel: 'production' });
await expect(uploadEmbeddedBundleAsync(ctx)).resolves.toBeUndefined();
await expect(uploadEmbeddedBundleAsync(args)).resolves.toEqual({ status: 'uploaded' });
expect(easCli.runEasCliCommand).toHaveBeenCalled();
expect(mockZipClose).toHaveBeenCalled();
});
@@ -1,5 +1,6 @@
import { Android, BuildJob, Ios, Platform } from '@expo/eas-build-job';
import { PipeMode } from '@expo/logger';
import { ExpoConfig } from '@expo/config';
import { Android, BuildJob, Env, Ios, Metadata, Platform } from '@expo/eas-build-job';
import { PipeMode, bunyan } from '@expo/logger';
import { asyncResult } from '@expo/results';
import fs from 'fs-extra';
import os from 'os';
@@ -9,9 +10,9 @@ import semver from 'semver';
import { findArtifacts } from './artifacts';
import { runEasCliCommand } from './easCli';
import { resolveArtifactPath } from '../ios/resolve';
import { BuildContext } from '../context';
import { isEASUpdateConfigured } from './expoUpdates';
import { resolveArtifactPath as resolveAndroidArtifactPath } from '../android/resolve';
import { resolveArtifactPath as resolveIosArtifactPath } from '../ios/resolve';
import { isEASUpdateConfigured } from '../steps/utils/expoUpdates';
function parseBooleanEnvVar(value: string | undefined): boolean | undefined {
if (!value) {
@@ -27,55 +28,64 @@ function parseBooleanEnvVar(value: string | undefined): boolean | undefined {
* On SDK 57 and below the feature is still experimental and off by default. Projects opt in by
* setting EAS_UPDATE_EXPERIMENTAL_UPLOAD_EMBEDDED_BUNDLE to "1".
*/
export function shouldUploadEmbeddedBundle(ctx: BuildContext<BuildJob>): boolean {
export function shouldUploadEmbeddedBundle({
env,
metadata,
}: {
env: Env;
metadata?: Metadata | null;
}): boolean {
const explicitFlag =
parseBooleanEnvVar(ctx.env.EAS_UPDATE_UPLOAD_EMBEDDED_BUNDLE) ??
parseBooleanEnvVar(ctx.env.EAS_UPDATE_EXPERIMENTAL_UPLOAD_EMBEDDED_BUNDLE);
parseBooleanEnvVar(env.EAS_UPDATE_UPLOAD_EMBEDDED_BUNDLE) ??
parseBooleanEnvVar(env.EAS_UPDATE_EXPERIMENTAL_UPLOAD_EMBEDDED_BUNDLE);
if (explicitFlag !== undefined) {
return explicitFlag;
}
const sdkVersion = ctx.metadata?.sdkVersion;
const sdkVersion = metadata?.sdkVersion;
return !!sdkVersion && semver.satisfies(sdkVersion, '>=58');
}
export async function uploadEmbeddedBundleAsync(ctx: BuildContext<BuildJob>): Promise<void> {
if (!(await isEASUpdateConfigured(ctx))) {
ctx.markBuildPhaseSkipped();
return;
export async function uploadEmbeddedBundleAsync({
job,
env,
logger,
projectDir,
appConfig,
}: {
job: BuildJob;
env: Env;
logger: bunyan;
projectDir: string;
appConfig: ExpoConfig;
}): Promise<{ status: 'uploaded' | 'skipped' | 'failed' }> {
if (!isEASUpdateConfigured(appConfig, logger)) {
return { status: 'skipped' };
}
if (ctx.job.developmentClient) {
ctx.markBuildPhaseSkipped();
return;
if (job.developmentClient) {
return { status: 'skipped' };
}
const { platform } = ctx.job;
if (platform === Platform.IOS && (ctx.job as Ios.Job).simulator) {
ctx.markBuildPhaseSkipped();
return;
const { platform } = job;
if (platform === Platform.IOS && (job as Ios.Job).simulator) {
return { status: 'skipped' };
}
const channel = ctx.job.updates?.channel;
const channel = job.updates?.channel;
if (!channel) {
ctx.logger.warn(
'Skipping embedded bundle upload: no channel configured for this build profile.'
);
ctx.markBuildPhaseHasWarnings();
return;
logger.warn('Skipping embedded bundle upload: no channel configured for this build profile.');
return { status: 'failed' };
}
const projectDir = ctx.getReactNativeProjectDirectory();
let archivePattern: string;
if (platform === Platform.IOS) {
archivePattern = resolveArtifactPath(ctx as BuildContext<Ios.Job>);
archivePattern = resolveIosArtifactPath(job as Ios.Job);
} else if (platform === Platform.ANDROID) {
archivePattern =
(ctx as BuildContext<Android.Job>).job.applicationArchivePath ??
'android/app/build/outputs/**/*.{apk,aab}';
archivePattern = resolveAndroidArtifactPath(job as Android.Job);
} else {
throw new Error(`Uploading embedded updates is not supported for the ${platform} platform.`);
logger.warn(`Skipping embedded bundle upload: the ${platform} platform is not supported.`);
return { status: 'failed' };
}
const [archivePath] = await findArtifacts({
@@ -85,9 +95,8 @@ export async function uploadEmbeddedBundleAsync(ctx: BuildContext<BuildJob>): Pr
}).catch(() => [] as string[]);
if (!archivePath) {
ctx.logger.warn('Skipping embedded bundle upload: build archive not found.');
ctx.markBuildPhaseHasWarnings();
return;
logger.warn('Skipping embedded bundle upload: build archive not found.');
return { status: 'failed' };
}
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'eas-embedded-bundle-'));
@@ -109,9 +118,8 @@ export async function uploadEmbeddedBundleAsync(ctx: BuildContext<BuildJob>): Pr
);
if (!bundleEntry || !manifestEntry) {
ctx.logger.warn('Skipping embedded bundle upload: bundle or manifest not found in archive.');
ctx.markBuildPhaseHasWarnings();
return;
logger.warn('Skipping embedded bundle upload: bundle or manifest not found in archive.');
return { status: 'failed' };
}
await zip.extract(bundleEntry.name, bundlePath);
@@ -129,21 +137,22 @@ export async function uploadEmbeddedBundleAsync(ctx: BuildContext<BuildJob>): Pr
channel,
'--non-interactive',
];
if (ctx.env.EAS_BUILD_ID) {
args.push('--build-id', ctx.env.EAS_BUILD_ID);
if (env.EAS_BUILD_ID) {
args.push('--build-id', env.EAS_BUILD_ID);
}
await runEasCliCommand({
args,
options: {
cwd: projectDir,
env: ctx.env,
logger: ctx.logger,
mode: PipeMode.STDERR_ONLY_AS_STDOUT,
env,
logger,
mode: PipeMode.COMBINED_AS_STDOUT,
},
});
return { status: 'uploaded' };
} catch (err: any) {
ctx.logger.warn({ err }, 'Failed to upload embedded bundle.');
ctx.markBuildPhaseHasWarnings();
logger.warn({ err }, 'Failed to upload embedded bundle.');
return { status: 'failed' };
} finally {
await asyncResult(zip.close());
}
+142 -142
View File
File diff suppressed because it is too large. Load diff
+477 -133
View File
@@ -124,6 +124,26 @@
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "scopes",
"description": "Scopes this token is restricted to. Null for a full token that authenticates as the owner\nwith all of their permissions.",
"args": [],
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "AccessTokenScope",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "updatedAt",
"description": null,
@@ -284,6 +304,155 @@
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "AccessTokenScope",
"description": "One scope narrowing an AccessToken below its owner's full access",
"fields": [
{
"name": "accountID",
"description": "The account this scope applies to. Only present for ACCOUNT scopes.",
"args": [],
"type": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "permissions",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "ENUM",
"name": "Permission",
"ofType": null
}
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "type",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "ENUM",
"name": "AccessTokenScopeType",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "INPUT_OBJECT",
"name": "AccessTokenScopeInput",
"description": null,
"fields": null,
"inputFields": [
{
"name": "accountID",
"description": "The account this scope applies to. Required for ACCOUNT scopes and must be omitted for\nALL_ACCOUNTS scopes.",
"type": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "permissions",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "ENUM",
"name": "Permission",
"ofType": null
}
}
}
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "type",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "ENUM",
"name": "AccessTokenScopeType",
"ofType": null
}
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
}
],
"interfaces": null,
"enumValues": null,
"possibleTypes": null
},
{
"kind": "ENUM",
"name": "AccessTokenScopeType",
"description": null,
"fields": null,
"inputFields": null,
"interfaces": null,
"enumValues": [
{
"name": "ACCOUNT",
"description": "One account, named by accountID, narrowed to the scope's permissions.",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "ALL_ACCOUNTS",
"description": "Every account the token's owner has permissions on at request time, narrowed to the\nscope's permissions.",
"isDeprecated": false,
"deprecationReason": null
}
],
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "AccessibleGitHubAppInstallation",
@@ -1629,6 +1798,83 @@
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "deviceRunSessionsPaginated",
"description": "Simulator sessions for all apps associated with this account, sorted newest first.",
"args": [
{
"name": "after",
"description": null,
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "before",
"description": null,
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "filter",
"description": null,
"type": {
"kind": "INPUT_OBJECT",
"name": "AccountDeviceRunSessionFilterInput",
"ofType": null
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "first",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "last",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "AccountDeviceRunSessionsConnection",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
@@ -3555,6 +3801,131 @@
"enumValues": null,
"possibleTypes": null
},
{
"kind": "INPUT_OBJECT",
"name": "AccountDeviceRunSessionFilterInput",
"description": null,
"fields": null,
"inputFields": [
{
"name": "statuses",
"description": null,
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "ENUM",
"name": "DeviceRunSessionStatus",
"ofType": null
}
}
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
}
],
"interfaces": null,
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "AccountDeviceRunSessionsConnection",
"description": null,
"fields": [
{
"name": "edges",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "AccountDeviceRunSessionsEdge",
"ofType": null
}
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "pageInfo",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "PageInfo",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "AccountDeviceRunSessionsEdge",
"description": null,
"fields": [
{
"name": "cursor",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "node",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "DeviceRunSession",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "AccountGoogleServiceAccountKeysConnection",
@@ -4011,55 +4382,6 @@
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "changeAdditionalAgentCreditsCount",
"description": "Buys or revokes account's additional agent credits, charging the account the appropriate amount if needed.",
"args": [
{
"name": "accountID",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "newAdditionalAgentCreditsCount",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "Account",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "changeAdditionalConcurrenciesCount",
"description": "Buys or revokes account's additional concurrencies, charging the account the appropriate amount if needed.",
@@ -44871,6 +45193,26 @@
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "scopes",
"description": "When given, requests authenticated with the new token are restricted to these scopes instead\nof the actor's full access. Either a single ALL_ACCOUNTS scope or one ACCOUNT scope per\naccount.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "INPUT_OBJECT",
"name": "AccessTokenScopeInput",
"ofType": null
}
}
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
}
],
"interfaces": null,
@@ -47464,6 +47806,18 @@
"description": null,
"fields": null,
"inputFields": [
{
"name": "agentRunId",
"description": null,
"type": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "appId",
"description": null,
@@ -51338,7 +51692,7 @@
},
{
"name": "createEventLogUploadSession",
"description": "Create a standard artifact and a two-hour upload URL for repeatedly\noverwriting its structured event log while the backing job run is running.",
"description": "Create or reuse a standard artifact and a two-hour upload URL for repeatedly\noverwriting its structured event log while the backing job run is running.",
"args": [
{
"name": "deviceRunSessionId",
@@ -51369,6 +51723,39 @@
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "createPreviewUploadSession",
"description": "Create or renew a two-hour upload URL for overwriting the session preview.\nReuses one WebP artifact while the backing job run is active.",
"args": [
{
"name": "deviceRunSessionId",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "CreateDeviceRunSessionArtifactUploadSessionResult",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "deleteDeviceRunSession",
"description": "Permanently delete a finished session and its artifacts. The backing job,\nif present, must also have finished. Returns the deleted session ID.",
@@ -52141,12 +52528,6 @@
"inputFields": null,
"interfaces": null,
"enumValues": [
{
"name": "AGENT",
"description": null,
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "BUILDS",
"description": null,
@@ -52206,12 +52587,6 @@
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "CREDIT_USAGE",
"description": null,
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "LOCAL_BUILDS",
"description": null,
@@ -65417,51 +65792,6 @@
"name": "InvoiceQuery",
"description": null,
"fields": [
{
"name": "previewInvoiceForAdditionalAgentCreditsCountUpdate",
"description": "Previews the invoice for the specified number of additional agent credit units.",
"args": [
{
"name": "accountID",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "additionalAgentCreditsCount",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
}
],
"type": {
"kind": "OBJECT",
"name": "Invoice",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "previewInvoiceForAdditionalConcurrenciesCountUpdate",
"description": "Previews the invoice for the specified number of additional concurrencies.\nThis is the total number of concurrencies the customer wishes to purchase\non top of their base plan, not the relative change in concurrencies\nthe customer wishes to make. For example, specify \"3\" if the customer has\ntwo add-on concurrencies and wishes to purchase one more.",
@@ -82258,14 +82588,14 @@
{
"name": "GCS_BUILD_APPLICATION_ARCHIVE",
"description": null,
"isDeprecated": false,
"deprecationReason": null
"isDeprecated": true,
"deprecationReason": "Submit with the build ID instead."
},
{
"name": "GCS_BUILD_APPLICATION_ARCHIVE_ORCHESTRATOR",
"description": null,
"isDeprecated": false,
"deprecationReason": null
"isDeprecated": true,
"deprecationReason": "Submit with the build ID instead."
},
{
"name": "GCS_SUBMIT_ARCHIVE",
@@ -82714,22 +83044,6 @@
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "includedAgentCreditsInCents",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "isDowngrading",
"description": null,
@@ -85469,6 +85783,18 @@
"isDeprecated": true,
"deprecationReason": "Use 'runtime' field ."
},
{
"name": "sourceMapUrl",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "updatedAt",
"description": null,
@@ -90047,6 +90373,18 @@
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "simulatorMinutes",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
@@ -90071,6 +90409,18 @@
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "simulatorMinutes",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
}
],
"interfaces": null,
@@ -90272,12 +90622,6 @@
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "CREDIT",
"description": null,
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "EVENT",
"description": null,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "eas-cli",
"version": "24.11.0",
"version": "24.12.0",
"description": "EAS command line tool",
"keywords": [
"cli",
@@ -20,7 +20,8 @@ export type AnalyticsEvent =
| BuildEvent
| SubmissionEvent
| MetadataEvent
| BillingEvent;
| BillingEvent
| SimulatorEvent;
export enum CommandEvent {
ACTION = 'action', // generic event type which is used to determine the 'daily active user' stat, include an `action: eas ${subcommand}` property inside of the event properties object
@@ -77,6 +78,12 @@ export enum BuildEvent {
ANDROID_KEYSTORE_CREATE = 'build cli credentials keystore create',
}
export enum SimulatorEvent {
REQUEST_SENT = 'sim session request sent',
REQUEST_CANCELLED = 'sim session request cancelled',
REQUEST_FAILED = 'sim session request failed',
}
export enum MetadataEvent {
APPLE_METADATA_DOWNLOAD = 'metadata cli download apple response',
APPLE_METADATA_UPLOAD = 'metadata cli upload apple response',
@@ -1,8 +1,8 @@
import ContextField, { ContextOptions } from './ContextField';
import { Analytics } from '../../analytics/AnalyticsManager';
import { AnalyticsWithOrchestration } from '../../analytics/AnalyticsManager';
export default class AnalyticsContextField extends ContextField<Analytics> {
async getValueAsync({ analytics }: ContextOptions): Promise<Analytics> {
export default class AnalyticsContextField extends ContextField<AnalyticsWithOrchestration> {
async getValueAsync({ analytics }: ContextOptions): Promise<AnalyticsWithOrchestration> {
return analytics;
}
}
@@ -1,10 +1,10 @@
import { Analytics } from '../../analytics/AnalyticsManager';
import { AnalyticsWithOrchestration } from '../../analytics/AnalyticsManager';
import SessionManager from '../../user/SessionManager';
import { Client } from '../../vcs/vcs';
export interface ContextOptions {
sessionManager: SessionManager;
analytics: Analytics;
analytics: AnalyticsWithOrchestration;
nonInteractive: boolean;
vcsClientOverride?: Client;
/** Short-circuits project ID resolution. */
@@ -1,7 +1,9 @@
import { Config } from '@oclif/core';
import { CombinedError } from '@urql/core';
import * as fs from 'fs-extra';
import { GraphQLError } from 'graphql';
import { isAnalyticsOptedOutAsync } from '../../../analytics/AnalyticsManager';
import { SimulatorEvent, isAnalyticsOptedOutAsync } from '../../../analytics/AnalyticsManager';
import { getAgentTelemetryContext } from '../../../analytics/agent';
import { ExpoGraphqlClient } from '../../../commandUtils/context/contextUtils/createGraphqlClient';
import {
@@ -103,6 +105,8 @@ const mockEnsureDeviceRunSessionStoppedAsync = jest.mocked(
const mockAvailabilityByAppIdAsync = jest.mocked(DeviceRunSessionAvailabilityQuery.byAppIdAsync);
const mockByIdAsync = jest.mocked(DeviceRunSessionQuery.byIdAsync);
const mockLoadSimulatorEnvAsync = jest.mocked(loadSimulatorEnvAsync);
const mockLogEvent = jest.fn();
const mockFlushAsync = jest.fn(async () => {});
const mockResetSimulatorEnvAsync = jest.mocked(resetSimulatorEnvAsync);
const mockResolveExpoGoSdkVersionAsync = jest.mocked(resolveExpoGoSdkVersionAsync);
const mockOra = jest.mocked(ora);
@@ -219,6 +223,7 @@ describe(Simulator, () => {
// @ts-expect-error getContextAsync is protected
const getContextAsync = jest.spyOn(command, 'getContextAsync').mockResolvedValue({
loggedIn: { actor: { isExpoAdmin }, graphqlClient },
analytics: { logEvent: mockLogEvent, flushAsync: mockFlushAsync, setActor: jest.fn() },
projectDir,
projectId: 'project-123',
});
@@ -251,6 +256,203 @@ describe(Simulator, () => {
expect(mockCreateDeviceRunSessionAsync).toHaveBeenCalled();
});
it('logs "request sent" with the funnel properties before creating the session', async () => {
mockLogEvent.mockClear();
mockCreateDeviceRunSessionAsync.mockImplementationOnce(async () => {
expect(mockLogEvent).toHaveBeenCalledWith(SimulatorEvent.REQUEST_SENT, {
project_id: 'project-123',
origin: 'eas-cli',
type: 'agent-device',
platform: 'ios',
has_build_id: false,
has_archive_url: false,
expo_go: false,
non_interactive: true,
});
return makeCreatedDeviceRunSession();
});
const { command } = createCommand([
'--platform',
'ios',
'--non-interactive',
'--out-config-type',
'env',
]);
await command.runAsync();
expect(mockCreateDeviceRunSessionAsync).toHaveBeenCalledTimes(1);
expect(mockLogEvent).toHaveBeenCalledTimes(1);
});
it.each([
['network_error', Object.assign(new Error('socket hang up'), { code: 'ECONNRESET' })],
['timeout', Object.assign(new Error('connect timeout'), { code: 'ETIMEDOUT' })],
])(
'logs "request failed" with reason %s when the create request gets no answer, and rethrows',
async (reason, networkError) => {
mockLogEvent.mockClear();
const error = new CombinedError({ networkError });
mockCreateDeviceRunSessionAsync.mockRejectedValueOnce(error);
const { command } = createCommand(['--platform', 'ios', '--non-interactive']);
await expect(command.runAsync()).rejects.toBe(error);
expect(mockLogEvent).toHaveBeenCalledTimes(2);
expect(mockLogEvent).toHaveBeenLastCalledWith(
SimulatorEvent.REQUEST_FAILED,
expect.objectContaining({ project_id: 'project-123', reason })
);
}
);
it.each([
[
'a GraphQL refusal',
new CombinedError({
graphQLErrors: [new GraphQLError('Simulator sessions are not enabled')],
}),
],
[
'an HTTP error answer',
new CombinedError({
networkError: new Error('Gateway Timeout'),
response: { status: 504, statusText: 'Gateway Timeout' },
}),
],
])('logs only "request sent" when the server answers with %s', async (_, error) => {
mockLogEvent.mockClear();
mockCreateDeviceRunSessionAsync.mockRejectedValueOnce(error);
const { command } = createCommand(['--platform', 'ios', '--non-interactive']);
await expect(command.runAsync()).rejects.toBe(error);
expect(mockLogEvent).toHaveBeenCalledTimes(1);
expect(mockLogEvent).toHaveBeenCalledWith(SimulatorEvent.REQUEST_SENT, expect.anything());
});
function mockCreateThatNeverAnswers(): Promise<void> {
return new Promise<void>(notifyCreateStarted => {
mockCreateDeviceRunSessionAsync.mockImplementationOnce(
() =>
new Promise(() => {
notifyCreateStarted();
})
);
});
}
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 () => {
mockLogEvent.mockClear();
const processExitSpy = jest.spyOn(process, 'exit').mockImplementation(code => {
throw new Error(`process.exit(${code})`);
});
try {
let finishFlush!: () => void;
const flushStarted = new Promise<void>(notifyFlushStarted => {
mockFlushAsync.mockImplementationOnce(
() =>
new Promise<void>(resolve => {
finishFlush = resolve;
notifyFlushStarted();
})
);
});
const createStarted = mockCreateThatNeverAnswers();
const existingSigintListeners = new Set(process.listeners('SIGINT'));
const { command } = createCommand(['--platform', 'ios', '--non-interactive']);
const commandPromise = command.runAsync();
await createStarted;
process.listeners('SIGINT').find(listener => !existingSigintListeners.has(listener))?.(
'SIGINT'
);
await flushStarted;
const exitCallsDuringFlush = [...processExitSpy.mock.calls];
finishFlush();
await expect(commandPromise).rejects.toThrow('process.exit(130)');
expect(exitCallsDuringFlush).toEqual([]);
expect(mockLogEvent).toHaveBeenLastCalledWith(
SimulatorEvent.REQUEST_CANCELLED,
expect.objectContaining({ project_id: 'project-123', reason: 'user_abort' })
);
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();
}
});
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 () => {
const processExitSpy = jest.spyOn(process, 'exit').mockImplementation(code => {
throw new Error(`process.exit(${code})`);
});
try {
const createStarted = mockCreateThatNeverAnswers();
const existingSigintListeners = [...process.listeners('SIGINT')];
const { command } = createCommand(['--platform', 'ios', '--non-interactive']);
const commandPromise = command.runAsync();
await createStarted;
process.emit('SIGINT');
const listenersAfterFirstCtrlC = process.listeners('SIGINT');
await expect(commandPromise).rejects.toThrow('process.exit(130)');
expect(listenersAfterFirstCtrlC).toEqual(existingSigintListeners);
} finally {
processExitSpy.mockRestore();
}
});
it('exits with 130 after 1 second when the analytics flush hangs after Ctrl+C', async () => {
jest.useFakeTimers();
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();
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(999);
const exitCallsBeforeOneSecond = [...processExitSpy.mock.calls];
await jest.advanceTimersByTimeAsync(1);
await exited;
expect(exitCallsBeforeOneSecond).toEqual([]);
expect(mockFlushAsync).toHaveBeenCalled();
} finally {
processExitSpy.mockRestore();
jest.useRealTimers();
}
});
it('removes its Ctrl+C listener once the create request answers or fails', async () => {
const existingSigintListeners = [...process.listeners('SIGINT')];
let listenersWhilePolling: Function[] | undefined;
mockByIdAsync.mockImplementationOnce(async () => {
listenersWhilePolling = [...process.listeners('SIGINT')];
return makeDeviceRunSession();
});
await createCommand(['--platform', 'ios', '--non-interactive']).command.runAsync();
// Only the session's own Ctrl+C handler, registered after the request answered, is left.
expect(listenersWhilePolling).toHaveLength(existingSigintListeners.length + 1);
expect(process.listeners('SIGINT')).toEqual(existingSigintListeners);
mockCreateDeviceRunSessionAsync.mockRejectedValueOnce(new Error('boom'));
await expect(
createCommand(['--platform', 'ios', '--non-interactive']).command.runAsync()
).rejects.toThrow('boom');
expect(process.listeners('SIGINT')).toEqual(existingSigintListeners);
});
it('prints environment variables without saving when outputting env', async () => {
const { command, getContextAsync } = createCommand([
'--platform',
+108 -28
View File
@@ -1,7 +1,12 @@
import { Flags } from '@oclif/core';
import nullthrows from 'nullthrows';
import { isAnalyticsOptedOutAsync } from '../../analytics/AnalyticsManager';
import {
AnalyticsEventProperties,
AnalyticsWithOrchestration,
SimulatorEvent,
isAnalyticsOptedOutAsync,
} from '../../analytics/AnalyticsManager';
import { getAgentTelemetryContext } from '../../analytics/agent';
import { getDeviceRunSessionUrl } from '../../build/utils/url';
import EasCommand from '../../commandUtils/EasCommand';
@@ -23,7 +28,7 @@ import { DeviceRunSessionMutation } from '../../graphql/mutations/DeviceRunSessi
import { DeviceRunSessionAvailabilityQuery } from '../../graphql/queries/DeviceRunSessionAvailabilityQuery';
import { DeviceRunSessionQuery } from '../../graphql/queries/DeviceRunSessionQuery';
import Log, { link } from '../../log';
import { ora } from '../../ora';
import { Ora, ora } from '../../ora';
import { promptAsync } from '../../prompts';
import { parseEgressAllowList, runLocalEgressAsync } from '../../simulator/egress';
import { parseNetworkCaptureFields } from '../../simulator/networkCapture';
@@ -35,6 +40,10 @@ import {
writeSimulatorEnvAsync,
} from '../../simulator/env';
import { resolveExpoGoSdkVersionAsync } from '../../simulator/expoGo';
import {
simulatorRequestFailureReason,
simulatorRequestProperties,
} from '../../simulator/requestAnalytics';
import {
DEVICE_RUN_SESSION_RESOURCE_CLASS_BY_FLAG_VALUE,
DEVICE_RUN_SESSION_RESOURCE_CLASS_FLAG_VALUES,
@@ -186,6 +195,7 @@ export default class Simulator extends EasCommand {
...this.ContextOptions.ProjectId,
...this.ContextOptions.ProjectDir,
...this.ContextOptions.LoggedIn,
...this.ContextOptions.Analytics,
};
async runAsync(): Promise<void> {
@@ -200,6 +210,7 @@ export default class Simulator extends EasCommand {
projectId,
projectDir,
loggedIn: { actor, graphqlClient },
analytics,
} = await this.getContextAsync(Simulator, {
nonInteractive,
});
@@ -302,35 +313,51 @@ export default class Simulator extends EasCommand {
let sessionInterrupt: SessionInterrupt | undefined;
try {
const agentIdentity = await agentIdentityInputAsync();
const session = await DeviceRunSessionMutation.createDeviceRunSessionAsync(graphqlClient, {
appId: projectId,
name,
...(tags?.length ? { tags } : {}),
const requestProperties = simulatorRequestProperties({
projectId,
type: flags.type,
platform,
type: DEVICE_RUN_SESSION_TYPE_BY_FLAG_VALUE[flags.type],
hasBuildId: !!buildId || !!buildFingerprint,
hasArchiveUrl: !!applicationArchiveUrlFromFlag,
expoGo: !!expoGoSdkVersion,
packageVersion: flags['package-version'],
networkCapture: flags['network-capture'],
...(networkCaptureFields.length ? { networkCaptureFields } : {}),
...(deviceIdentifier
? platform === AppPlatform.Ios
? { ios: { deviceIdentifier } }
: { android: { deviceIdentifier } }
: {}),
...(buildId ? { buildId } : {}),
...(buildFingerprint ? { buildFingerprint } : {}),
...(applicationArchiveUrlFromFlag
? { applicationArchiveUrl: applicationArchiveUrlFromFlag }
: {}),
...(expoGoSdkVersion ? { expoGo: true, sdkVersion: expoGoSdkVersion } : {}),
...(launchArgs?.length ? { launchArgs } : {}),
...(openUrl ? { openUrl } : {}),
...(resourceClass ? { resourceClass } : {}),
...(egress ? { egress } : {}),
requestOrigin: DeviceRunSessionRequestOrigin.EasCli,
...agentIdentity,
maxRunTimeMinutes: flags['max-duration-minutes'],
maxIdleTimeMinutes: flags['max-idle-time-minutes'],
nonInteractive,
});
const session = await withSimulatorRequestAnalyticsAsync(
analytics,
requestProperties,
createSpinner,
() =>
DeviceRunSessionMutation.createDeviceRunSessionAsync(graphqlClient, {
appId: projectId,
name,
...(tags?.length ? { tags } : {}),
platform,
type: DEVICE_RUN_SESSION_TYPE_BY_FLAG_VALUE[flags.type],
packageVersion: flags['package-version'],
networkCapture: flags['network-capture'],
...(networkCaptureFields.length ? { networkCaptureFields } : {}),
...(deviceIdentifier
? platform === AppPlatform.Ios
? { ios: { deviceIdentifier } }
: { android: { deviceIdentifier } }
: {}),
...(buildId ? { buildId } : {}),
...(buildFingerprint ? { buildFingerprint } : {}),
...(applicationArchiveUrlFromFlag
? { applicationArchiveUrl: applicationArchiveUrlFromFlag }
: {}),
...(expoGoSdkVersion ? { expoGo: true, sdkVersion: expoGoSdkVersion } : {}),
...(launchArgs?.length ? { launchArgs } : {}),
...(openUrl ? { openUrl } : {}),
...(resourceClass ? { resourceClass } : {}),
...(egress ? { egress } : {}),
requestOrigin: DeviceRunSessionRequestOrigin.EasCli,
...agentIdentity,
maxRunTimeMinutes: flags['max-duration-minutes'],
maxIdleTimeMinutes: flags['max-idle-time-minutes'],
})
);
deviceRunSessionId = session.id;
nullthrows(session.turtleJobRun?.id, 'Expected simulator session to start');
deviceRunSessionUrl = getDeviceRunSessionUrl(
@@ -768,6 +795,59 @@ async function ensureDeviceRunSessionStoppedSafelyAsync(
}
}
/**
* How long Ctrl+C waits for analytics to flush. The analytics client has no request timeout, so
* without a limit a hung network would make Ctrl+C look ignored.
*/
const CANCEL_FLUSH_TIMEOUT_MS = 1_000;
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.
*/
async function withSimulatorRequestAnalyticsAsync<T>(
analytics: AnalyticsWithOrchestration,
properties: AnalyticsEventProperties,
spinner: Ora,
createAsync: () => Promise<T>
): Promise<T> {
let onSigint: (() => void) | undefined;
const cancelled = new Promise<never>((_, reject) => {
onSigint = () => {
reject(new SimulatorRequestCancelledError());
};
});
process.once('SIGINT', onSigint!);
analytics.logEvent(SimulatorEvent.REQUEST_SENT, properties);
try {
return await Promise.race([createAsync(), cancelled]);
} catch (error) {
if (error instanceof SimulatorRequestCancelledError) {
analytics.logEvent(SimulatorEvent.REQUEST_CANCELLED, { ...properties, reason: 'user_abort' });
spinner.fail('Simulator session request canceled');
const flushTimeout = new AbortController();
await Promise.race([
analytics.flushAsync(),
sleepAsync(CANCEL_FLUSH_TIMEOUT_MS, flushTimeout.signal),
]);
flushTimeout.abort();
process.exit(130);
}
const reason = simulatorRequestFailureReason(error);
if (reason) {
analytics.logEvent(SimulatorEvent.REQUEST_FAILED, { ...properties, reason });
}
throw error;
} finally {
process.removeListener('SIGINT', onSigint!);
}
}
async function agentIdentityInputAsync(): Promise<{ agentId?: string; agentSessionId?: string }> {
if (await isAnalyticsOptedOutAsync()) {
return {};
@@ -7,7 +7,7 @@ import { enableJsonOutput, printJsonOnlyOutput } from '../../../utils/json';
import UpdateView from '../view';
jest.mock('../../../graphql/queries/UpdateQuery', () => ({
UpdateQuery: { viewUpdateGroupAsync: jest.fn(), viewByUpdateAsync: jest.fn() },
UpdateQuery: { viewUpdateGroupWithFileUrlsAsync: jest.fn(), viewByUpdateAsync: jest.fn() },
}));
jest.mock('../../../graphql/queries/UpdateInsightsQuery', () => ({
UpdateInsightsQuery: { viewUpdateGroupInsightsAsync: jest.fn() },
@@ -15,7 +15,9 @@ jest.mock('../../../graphql/queries/UpdateInsightsQuery', () => ({
jest.mock('../../../log');
jest.mock('../../../utils/json');
const mockViewUpdateGroupAsync = jest.mocked(UpdateQuery.viewUpdateGroupAsync);
const mockViewUpdateGroupWithFileUrlsAsync = jest.mocked(
UpdateQuery.viewUpdateGroupWithFileUrlsAsync
);
const mockViewByUpdateAsync = jest.mocked(UpdateQuery.viewByUpdateAsync);
const mockViewUpdateGroupInsightsAsync = jest.mocked(
UpdateInsightsQuery.viewUpdateGroupInsightsAsync
@@ -95,7 +97,7 @@ describe(UpdateView, () => {
beforeEach(() => {
jest.clearAllMocks();
mockViewUpdateGroupAsync.mockResolvedValue(updateGroup);
mockViewUpdateGroupWithFileUrlsAsync.mockResolvedValue(updateGroup);
mockViewUpdateGroupInsightsAsync.mockResolvedValue(insightsResponse);
});
@@ -160,13 +162,15 @@ describe(UpdateView, () => {
it('does not look up a single update when the ID resolves as a group', async () => {
const command = createCommand(['group-1']);
await command.runAsync();
expect(mockViewUpdateGroupAsync).toHaveBeenCalledWith(graphqlClient, { groupId: 'group-1' });
expect(mockViewUpdateGroupWithFileUrlsAsync).toHaveBeenCalledWith(graphqlClient, {
groupId: 'group-1',
});
expect(mockViewByUpdateAsync).not.toHaveBeenCalled();
});
it('resolves a platform-specific update ID to its group', async () => {
mockViewUpdateGroupAsync.mockReset();
mockViewUpdateGroupAsync
mockViewUpdateGroupWithFileUrlsAsync.mockReset();
mockViewUpdateGroupWithFileUrlsAsync
.mockRejectedValueOnce(new Error('Could not find any updates with group ID: "u1"'))
.mockResolvedValueOnce(updateGroup);
mockViewByUpdateAsync.mockResolvedValue({ ...updateGroup[0], group: 'group-1' });
@@ -175,7 +179,7 @@ describe(UpdateView, () => {
await command.runAsync();
expect(mockViewByUpdateAsync).toHaveBeenCalledWith(graphqlClient, { updateId: 'u1' });
expect(mockViewUpdateGroupAsync).toHaveBeenLastCalledWith(graphqlClient, {
expect(mockViewUpdateGroupWithFileUrlsAsync).toHaveBeenLastCalledWith(graphqlClient, {
groupId: 'group-1',
});
expect(mockViewUpdateGroupInsightsAsync).toHaveBeenCalledWith(
@@ -185,8 +189,8 @@ describe(UpdateView, () => {
});
it('surfaces the original group lookup error when the ID matches neither a group nor an update', async () => {
mockViewUpdateGroupAsync.mockReset();
mockViewUpdateGroupAsync.mockRejectedValue(
mockViewUpdateGroupWithFileUrlsAsync.mockReset();
mockViewUpdateGroupWithFileUrlsAsync.mockRejectedValue(
new Error('Could not find any updates with group ID: "bogus"')
);
mockViewByUpdateAsync.mockRejectedValue(new Error('update not found'));
+9 -7
View File
@@ -4,7 +4,7 @@ import chalk from 'chalk';
import EasCommand from '../../commandUtils/EasCommand';
import { EasJsonOnlyFlag } from '../../commandUtils/flags';
import { ExpoGraphqlClient } from '../../commandUtils/context/contextUtils/createGraphqlClient';
import { UpdateFragment } from '../../graphql/generated';
import { UpdateFragment, UpdateWithFileUrlsFragment } from '../../graphql/generated';
import { UpdateInsightsQuery } from '../../graphql/queries/UpdateInsightsQuery';
import { UpdateQuery } from '../../graphql/queries/UpdateQuery';
import { resolveInsightsTimeRange } from '../../insights/timeRange';
@@ -18,7 +18,7 @@ import {
import {
formatUpdateGroup,
getUpdateGroupDescriptions,
getUpdateJsonInfosForUpdates,
getUpdateWithFileUrlsJsonInfosForUpdates,
} from '../../update/utils';
import { enableJsonOutput, printJsonOnlyOutput } from '../../utils/json';
@@ -98,11 +98,11 @@ export default class UpdateView extends EasCommand {
if (jsonFlag) {
if (insightsSummary) {
printJsonOnlyOutput({
updates: getUpdateJsonInfosForUpdates(updatesByGroup),
updates: getUpdateWithFileUrlsJsonInfosForUpdates(updatesByGroup),
insights: buildUpdateInsightsJson(insightsSummary),
});
} else {
printJsonOnlyOutput(getUpdateJsonInfosForUpdates(updatesByGroup));
printJsonOnlyOutput(getUpdateWithFileUrlsJsonInfosForUpdates(updatesByGroup));
}
} else {
const [updateGroupDescription] = getUpdateGroupDescriptions([updatesByGroup]);
@@ -127,9 +127,11 @@ export default class UpdateView extends EasCommand {
private static async resolveUpdateGroupAsync(
graphqlClient: ExpoGraphqlClient,
id: string
): Promise<{ groupId: string; updatesByGroup: UpdateFragment[] }> {
): Promise<{ groupId: string; updatesByGroup: UpdateWithFileUrlsFragment[] }> {
try {
const updatesByGroup = await UpdateQuery.viewUpdateGroupAsync(graphqlClient, { groupId: id });
const updatesByGroup = await UpdateQuery.viewUpdateGroupWithFileUrlsAsync(graphqlClient, {
groupId: id,
});
return { groupId: id, updatesByGroup };
} catch (groupError) {
let update: UpdateFragment | undefined;
@@ -141,7 +143,7 @@ export default class UpdateView extends EasCommand {
throw groupError;
}
const updatesByGroup = await UpdateQuery.viewUpdateGroupAsync(graphqlClient, {
const updatesByGroup = await UpdateQuery.viewUpdateGroupWithFileUrlsAsync(graphqlClient, {
groupId: update.group,
});
return { groupId: update.group, updatesByGroup };
+107 -21
View File
@@ -44,6 +44,11 @@ export type AccessToken = {
note?: Maybe<Scalars['String']['output']>;
owner: Actor;
revokedAt?: Maybe<Scalars['DateTime']['output']>;
/**
* Scopes this token is restricted to. Null for a full token that authenticates as the owner
* with all of their permissions.
*/
scopes?: Maybe<Array<AccessTokenScope>>;
updatedAt: Scalars['DateTime']['output'];
visibleTokenPrefix: Scalars['String']['output'];
};
@@ -74,6 +79,35 @@ export type AccessTokenMutation_SetAccessTokenRevokedArgs = {
revoked?: InputMaybe<Scalars['Boolean']['input']>;
};
/** One scope narrowing an AccessToken below its owner's full access */
export type AccessTokenScope = {
__typename?: 'AccessTokenScope';
/** The account this scope applies to. Only present for ACCOUNT scopes. */
accountID?: Maybe<Scalars['ID']['output']>;
permissions: Array<Permission>;
type: AccessTokenScopeType;
};
export type AccessTokenScopeInput = {
/**
* The account this scope applies to. Required for ACCOUNT scopes and must be omitted for
* ALL_ACCOUNTS scopes.
*/
accountID?: InputMaybe<Scalars['ID']['input']>;
permissions: Array<Permission>;
type: AccessTokenScopeType;
};
export enum AccessTokenScopeType {
/** One account, named by accountID, narrowed to the scope's permissions. */
Account = 'ACCOUNT',
/**
* Every account the token's owner has permissions on at request time, narrowed to the
* scope's permissions.
*/
AllAccounts = 'ALL_ACCOUNTS'
}
/** A GitHub App installation visible to a viewer, not necessarily linked yet. */
export type AccessibleGitHubAppInstallation = {
__typename?: 'AccessibleGitHubAppInstallation';
@@ -149,6 +183,8 @@ export type Account = {
/** Convex team connections for this account */
convexTeamConnections: Array<ConvexTeamConnection>;
createdAt: Scalars['DateTime']['output'];
/** Simulator sessions for all apps associated with this account, sorted newest first. */
deviceRunSessionsPaginated: AccountDeviceRunSessionsConnection;
displayName?: Maybe<Scalars['String']['output']>;
/** Echo projects for this account (paginated, most recent first) */
echoProjects: EchoProjectConnection;
@@ -419,6 +455,19 @@ export type Account_ConcurrencyConsumersArgs = {
};
/**
* An account is a container owning projects, credentials, billing and other organization
* data and settings. Actors may own and be members of accounts.
*/
export type Account_DeviceRunSessionsPaginatedArgs = {
after?: InputMaybe<Scalars['String']['input']>;
before?: InputMaybe<Scalars['String']['input']>;
filter?: InputMaybe<AccountDeviceRunSessionFilterInput>;
first?: InputMaybe<Scalars['Int']['input']>;
last?: InputMaybe<Scalars['Int']['input']>;
};
/**
* An account is a container owning projects, credentials, billing and other organization
* data and settings. Actors may own and be members of accounts.
@@ -622,6 +671,22 @@ export type AccountDataInput = {
userSpecifiedAccountUsage?: InputMaybe<UserSpecifiedAccountUsage>;
};
export type AccountDeviceRunSessionFilterInput = {
statuses?: InputMaybe<Array<DeviceRunSessionStatus>>;
};
export type AccountDeviceRunSessionsConnection = {
__typename?: 'AccountDeviceRunSessionsConnection';
edges: Array<AccountDeviceRunSessionsEdge>;
pageInfo: PageInfo;
};
export type AccountDeviceRunSessionsEdge = {
__typename?: 'AccountDeviceRunSessionsEdge';
cursor: Scalars['String']['output'];
node: DeviceRunSession;
};
export type AccountGoogleServiceAccountKeysConnection = {
__typename?: 'AccountGoogleServiceAccountKeysConnection';
edges: Array<AccountGoogleServiceAccountKeysEdge>;
@@ -696,8 +761,6 @@ export type AccountMutation = {
cancelAllSubscriptionsImmediately: Account;
/** Cancel scheduled subscription change */
cancelScheduledSubscriptionChange: Account;
/** Buys or revokes account's additional agent credits, charging the account the appropriate amount if needed. */
changeAdditionalAgentCreditsCount: Account;
/** Buys or revokes account's additional concurrencies, charging the account the appropriate amount if needed. */
changeAdditionalConcurrenciesCount: Account;
/** Upgrades or downgrades the active subscription to the newPlanIdentifier, which must be one of the EAS plans (i.e., Production or Enterprise). */
@@ -740,12 +803,6 @@ export type AccountMutation_CancelScheduledSubscriptionChangeArgs = {
};
export type AccountMutation_ChangeAdditionalAgentCreditsCountArgs = {
accountID: Scalars['ID']['input'];
newAdditionalAgentCreditsCount: Scalars['Int']['input'];
};
export type AccountMutation_ChangeAdditionalConcurrenciesCountArgs = {
accountID: Scalars['ID']['input'];
newAdditionalConcurrenciesCount: Scalars['Int']['input'];
@@ -6295,6 +6352,12 @@ export type CrashesFilters = {
export type CreateAccessTokenInput = {
actorID: Scalars['ID']['input'];
note?: InputMaybe<Scalars['String']['input']>;
/**
* When given, requests authenticated with the new token are restricted to these scopes instead
* of the actor's full access. Either a single ALL_ACCOUNTS scope or one ACCOUNT scope per
* account.
*/
scopes?: InputMaybe<Array<AccessTokenScopeInput>>;
};
export type CreateAccessTokenResponse = {
@@ -6667,6 +6730,7 @@ export type CreatePostHogDeepLinkInput = {
};
export type CreateSandboxInput = {
agentRunId?: InputMaybe<Scalars['ID']['input']>;
appId: Scalars['ID']['input'];
image?: InputMaybe<Scalars['String']['input']>;
operatingSystem: SandboxOperatingSystem;
@@ -7232,10 +7296,15 @@ export type DeviceRunSessionMutation = {
/** Create a device run session */
createDeviceRunSession: DeviceRunSession;
/**
* Create a standard artifact and a two-hour upload URL for repeatedly
* Create or reuse a standard artifact and a two-hour upload URL for repeatedly
* overwriting its structured event log while the backing job run is running.
*/
createEventLogUploadSession: CreateDeviceRunSessionEventLogUploadSessionResult;
/**
* Create or renew a two-hour upload URL for overwriting the session preview.
* Reuses one WebP artifact while the backing job run is active.
*/
createPreviewUploadSession: CreateDeviceRunSessionArtifactUploadSessionResult;
/**
* Permanently delete a finished session and its artifacts. The backing job,
* if present, must also have finished. Returns the deleted session ID.
@@ -7273,6 +7342,11 @@ export type DeviceRunSessionMutation_CreateEventLogUploadSessionArgs = {
};
export type DeviceRunSessionMutation_CreatePreviewUploadSessionArgs = {
deviceRunSessionId: Scalars['ID']['input'];
};
export type DeviceRunSessionMutation_DeleteDeviceRunSessionArgs = {
deviceRunSessionId: Scalars['ID']['input'];
};
@@ -7404,7 +7478,6 @@ export enum EasBuildWaiverType {
}
export enum EasService {
Agent = 'AGENT',
Builds = 'BUILDS',
Jobs = 'JOBS',
Mcp = 'MCP',
@@ -7416,7 +7489,6 @@ export enum EasServiceMetric {
AssetsRequests = 'ASSETS_REQUESTS',
BandwidthUsage = 'BANDWIDTH_USAGE',
Builds = 'BUILDS',
CreditUsage = 'CREDIT_USAGE',
LocalBuilds = 'LOCAL_BUILDS',
ManifestRequests = 'MANIFEST_REQUESTS',
McpRequests = 'MCP_REQUESTS',
@@ -9385,8 +9457,6 @@ export type InvoicePeriod = {
export type InvoiceQuery = {
__typename?: 'InvoiceQuery';
/** Previews the invoice for the specified number of additional agent credit units. */
previewInvoiceForAdditionalAgentCreditsCountUpdate?: Maybe<Invoice>;
/**
* Previews the invoice for the specified number of additional concurrencies.
* This is the total number of concurrencies the customer wishes to purchase
@@ -9400,12 +9470,6 @@ export type InvoiceQuery = {
};
export type InvoiceQuery_PreviewInvoiceForAdditionalAgentCreditsCountUpdateArgs = {
accountID: Scalars['ID']['input'];
additionalAgentCreditsCount: Scalars['Int']['input'];
};
export type InvoiceQuery_PreviewInvoiceForAdditionalConcurrenciesCountUpdateArgs = {
accountID: Scalars['ID']['input'];
additionalConcurrenciesCount: Scalars['Int']['input'];
@@ -11721,7 +11785,9 @@ export type SubmissionArchiveSourceInput = {
};
export enum SubmissionArchiveSourceType {
/** @deprecated Submit with the build ID instead. */
GcsBuildApplicationArchive = 'GCS_BUILD_APPLICATION_ARCHIVE',
/** @deprecated Submit with the build ID instead. */
GcsBuildApplicationArchiveOrchestrator = 'GCS_BUILD_APPLICATION_ARCHIVE_ORCHESTRATOR',
GcsSubmitArchive = 'GCS_SUBMIT_ARCHIVE',
Url = 'URL'
@@ -11804,7 +11870,6 @@ export type SubscriptionDetails = {
endedAt?: Maybe<Scalars['DateTime']['output']>;
futureSubscription?: Maybe<FutureSubscription>;
id: Scalars['ID']['output'];
includedAgentCreditsInCents: Scalars['Int']['output'];
isDowngrading?: Maybe<Scalars['Boolean']['output']>;
meteredBillingStatus: MeteredBillingStatus;
name?: Maybe<Scalars['String']['output']>;
@@ -12185,6 +12250,7 @@ export type Update = ActivityTimelineProjectActivity & {
runtime: Runtime;
/** @deprecated Use 'runtime' field . */
runtimeVersion: Scalars['String']['output'];
sourceMapUrl?: Maybe<Scalars['String']['output']>;
updatedAt: Scalars['DateTime']['output'];
workflowJob?: Maybe<WorkflowJob>;
};
@@ -12849,10 +12915,12 @@ export type UsageBudget = {
export type UsageBudgetLimits = {
__typename?: 'UsageBudgetLimits';
builds?: Maybe<Scalars['Int']['output']>;
simulatorMinutes?: Maybe<Scalars['Int']['output']>;
};
export type UsageBudgetLimitsInput = {
builds?: InputMaybe<Scalars['Int']['input']>;
simulatorMinutes?: InputMaybe<Scalars['Int']['input']>;
};
export type UsageBudgetMutation = {
@@ -12880,7 +12948,6 @@ export type UsageMetricTotal = {
export enum UsageMetricType {
Bandwidth = 'BANDWIDTH',
Build = 'BUILD',
Credit = 'CREDIT',
Event = 'EVENT',
Minute = 'MINUTE',
Request = 'REQUEST',
@@ -17037,6 +17104,18 @@ export type ViewUpdatesByGroupQuery = { __typename?: 'RootQuery', updatesByGroup
| { __typename: 'User', username: string, id: string }
| null, branch: { __typename?: 'UpdateBranch', id: string, name: string }, codeSigningInfo?: { __typename?: 'CodeSigningInfo', keyid: string, sig: string, alg: string } | null, rolloutControlUpdate?: { __typename?: 'Update', id: string, group: string } | null, fingerprint?: { __typename?: 'Fingerprint', id: string, hash: string, debugInfoUrl?: string | null, source?: { __typename?: 'FingerprintSource', type: FingerprintSourceType, bucketKey: string, isDebugFingerprint?: boolean | null } | null } | null }> };
export type ViewUpdatesByGroupWithFileUrlsQueryVariables = Exact<{
groupId: Scalars['ID']['input'];
}>;
export type ViewUpdatesByGroupWithFileUrlsQuery = { __typename?: 'RootQuery', updatesByGroup: Array<{ __typename?: 'Update', id: string, assetMapUrl?: string | null, sourceMapUrl?: string | null, group: string, message?: string | null, createdAt: any, platform: string, manifestFragment: string, isRollBackToEmbedded: boolean, manifestPermalink: string, gitCommitHash?: string | null, isGitWorkingTreeDirty: boolean, environment?: any | null, rolloutPercentage?: number | null, manifestHostOverride?: string | null, assetHostOverride?: string | null, runtime: { __typename?: 'Runtime', id: string, version: string }, actor?:
| { __typename: 'PartnerActor', username: string, id: string }
| { __typename: 'Robot', firstName?: string | null, id: string }
| { __typename: 'SSOUser', username: string, id: string }
| { __typename: 'User', username: string, id: string }
| null, branch: { __typename?: 'UpdateBranch', id: string, name: string }, codeSigningInfo?: { __typename?: 'CodeSigningInfo', keyid: string, sig: string, alg: string } | null, rolloutControlUpdate?: { __typename?: 'Update', id: string, group: string } | null, fingerprint?: { __typename?: 'Fingerprint', id: string, hash: string, debugInfoUrl?: string | null, source?: { __typename?: 'FingerprintSource', type: FingerprintSourceType, bucketKey: string, isDebugFingerprint?: boolean | null } | null } | null }> };
export type ViewUpdateGroupsOnBranchQueryVariables = Exact<{
appId: Scalars['String']['input'];
branchName: Scalars['String']['input'];
@@ -17418,6 +17497,13 @@ export type UpdateFragment = { __typename?: 'Update', id: string, group: string,
| { __typename: 'User', username: string, id: string }
| null, branch: { __typename?: 'UpdateBranch', id: string, name: string }, codeSigningInfo?: { __typename?: 'CodeSigningInfo', keyid: string, sig: string, alg: string } | null, rolloutControlUpdate?: { __typename?: 'Update', id: string, group: string } | null, fingerprint?: { __typename?: 'Fingerprint', id: string, hash: string, debugInfoUrl?: string | null, source?: { __typename?: 'FingerprintSource', type: FingerprintSourceType, bucketKey: string, isDebugFingerprint?: boolean | null } | null } | null };
export type UpdateWithFileUrlsFragment = { __typename?: 'Update', id: string, assetMapUrl?: string | null, sourceMapUrl?: string | null, group: string, message?: string | null, createdAt: any, platform: string, manifestFragment: string, isRollBackToEmbedded: boolean, manifestPermalink: string, gitCommitHash?: string | null, isGitWorkingTreeDirty: boolean, environment?: any | null, rolloutPercentage?: number | null, manifestHostOverride?: string | null, assetHostOverride?: string | null, runtime: { __typename?: 'Runtime', id: string, version: string }, actor?:
| { __typename: 'PartnerActor', username: string, id: string }
| { __typename: 'Robot', firstName?: string | null, id: string }
| { __typename: 'SSOUser', username: string, id: string }
| { __typename: 'User', username: string, id: string }
| null, branch: { __typename?: 'UpdateBranch', id: string, name: string }, codeSigningInfo?: { __typename?: 'CodeSigningInfo', keyid: string, sig: string, alg: string } | null, rolloutControlUpdate?: { __typename?: 'Update', id: string, group: string } | null, fingerprint?: { __typename?: 'Fingerprint', id: string, hash: string, debugInfoUrl?: string | null, source?: { __typename?: 'FingerprintSource', type: FingerprintSourceType, bucketKey: string, isDebugFingerprint?: boolean | null } | null } | null };
export type UpdateBranchFragment = { __typename?: 'UpdateBranch', id: string, name: string, updates: Array<{ __typename?: 'Update', id: string, group: string, message?: string | null, createdAt: any, platform: string, manifestFragment: string, isRollBackToEmbedded: boolean, manifestPermalink: string, gitCommitHash?: string | null, isGitWorkingTreeDirty: boolean, environment?: any | null, rolloutPercentage?: number | null, manifestHostOverride?: string | null, assetHostOverride?: string | null, runtime: { __typename?: 'Runtime', id: string, version: string }, actor?:
| { __typename: 'PartnerActor', username: string, id: string }
| { __typename: 'Robot', firstName?: string | null, id: string }
@@ -7,6 +7,7 @@ import {
UpdateByIdQuery,
UpdateByIdQueryVariables,
UpdateFragment,
UpdateWithFileUrlsFragment,
ViewUpdateGroupsOnAppQuery,
ViewUpdateGroupsOnAppQueryVariables,
ViewUpdateGroupsOnBranchQuery,
@@ -15,8 +16,10 @@ import {
ViewUpdateGroupsPaginatedOnBranchQueryVariables,
ViewUpdatesByGroupQuery,
ViewUpdatesByGroupQueryVariables,
ViewUpdatesByGroupWithFileUrlsQuery,
ViewUpdatesByGroupWithFileUrlsQueryVariables,
} from '../generated';
import { UpdateFragmentNode } from '../types/Update';
import { UpdateFragmentNode, UpdateWithFileUrlsFragmentNode } from '../types/Update';
export const UpdateQuery = {
async viewUpdateGroupAsync(
@@ -49,6 +52,40 @@ export const UpdateQuery = {
return updatesByGroup;
},
/**
* Same as viewUpdateGroupAsync, but also fetches the signed asset map and source map URLs.
* Those are signed per request on the server, so only use this when the URLs are shown.
*/
async viewUpdateGroupWithFileUrlsAsync(
graphqlClient: ExpoGraphqlClient,
{ groupId }: ViewUpdatesByGroupWithFileUrlsQueryVariables
): Promise<UpdateWithFileUrlsFragment[]> {
const { updatesByGroup } = await withErrorHandlingAsync(
graphqlClient
.query<ViewUpdatesByGroupWithFileUrlsQuery, ViewUpdatesByGroupWithFileUrlsQueryVariables>(
gql`
query ViewUpdatesByGroupWithFileUrls($groupId: ID!) {
updatesByGroup(group: $groupId) {
id
...UpdateWithFileUrlsFragment
}
}
${print(UpdateWithFileUrlsFragmentNode)}
`,
{
groupId,
},
{ additionalTypenames: ['Update'] }
)
.toPromise()
);
if (updatesByGroup.length === 0) {
throw new Error(`Could not find any updates with group ID: "${groupId}"`);
}
return updatesByGroup;
},
async viewUpdateGroupsOnBranchAsync(
graphqlClient: ExpoGraphqlClient,
{ limit, offset, appId, branchName, filter }: ViewUpdateGroupsOnBranchQueryVariables
@@ -106,6 +106,8 @@ function isNotFoundError(error: unknown): boolean {
const code = e?.extensions?.errorCode ?? e?.extensions?.code;
return (
code === 'ENTITY_NOT_FOUND' ||
code === 'BUILD_NOT_FOUND' ||
code === 'NOT_FOUND_ERROR' ||
/Entity not found/i.test(e?.message ?? '') ||
/not found/i.test(e?.message ?? '')
);
@@ -3,6 +3,19 @@ import { GraphqlError } from '../../client';
import { BuildStatus, JobRunStatus, WorkflowJobStatus } from '../../generated';
import { WorkflowJobSshQuery } from '../WorkflowJobSshQuery';
const workflowJobNotFoundError = {
message: 'Entity Not Found: Entity not found: WorkflowJobEntity (id = missing)',
extensions: { errorCode: 'NOT_FOUND_ERROR', errorType: 'USER' },
};
const buildNotFoundError = {
message: "Build with id 'missing' does not exist.",
extensions: { errorCode: 'BUILD_NOT_FOUND', errorType: 'USER' },
};
const jobRunNotFoundError = {
message: 'Entity Not Found: Entity not found: TurtleJobRunEntity (id = missing)',
extensions: { errorCode: 'NOT_FOUND_ERROR', errorType: 'USER' },
};
describe(WorkflowJobSshQuery.connectInfoForWorkflowJobAsync.name, () => {
function makeClient(byId: unknown): {
graphqlClient: ExpoGraphqlClient;
@@ -64,9 +77,7 @@ describe(WorkflowJobSshQuery.connectInfoForWorkflowJobAsync.name, () => {
toPromise: async () => ({
data: undefined,
error: new GraphqlError({
graphQLErrors: [
{ message: 'Entity not found', extensions: { errorCode: 'ENTITY_NOT_FOUND' } },
],
graphQLErrors: [workflowJobNotFoundError],
networkError: undefined,
response: undefined,
}),
@@ -82,6 +93,7 @@ describe(WorkflowJobSshQuery.connectInfoForWorkflowJobAsync.name, () => {
for (const graphQLErrors of [
[{ message: 'Workflow job not found', extensions: {} }],
[{ message: 'missing', extensions: { code: 'ENTITY_NOT_FOUND' } }],
[{ message: 'missing', extensions: { errorCode: 'NOT_FOUND_ERROR' } }],
]) {
const query = jest.fn().mockReturnValue({
toPromise: async () => ({
@@ -231,9 +243,7 @@ describe(WorkflowJobSshQuery.connectInfoForBuildAsync.name, () => {
toPromise: async () => ({
data: undefined,
error: new GraphqlError({
graphQLErrors: [
{ message: 'Entity not found', extensions: { errorCode: 'ENTITY_NOT_FOUND' } },
],
graphQLErrors: [buildNotFoundError],
networkError: undefined,
response: undefined,
}),
@@ -260,11 +270,13 @@ describe(WorkflowJobSshQuery.connectInfoForBuildAsync.name, () => {
});
describe(WorkflowJobSshQuery.connectInfoForResourceIdAsync.name, () => {
const notFound = new GraphqlError({
graphQLErrors: [{ message: 'Entity not found', extensions: { errorCode: 'ENTITY_NOT_FOUND' } }],
networkError: undefined,
response: undefined,
});
function notFound(graphQLError: typeof workflowJobNotFoundError): GraphqlError {
return new GraphqlError({
graphQLErrors: [graphQLError],
networkError: undefined,
response: undefined,
});
}
const session = {
id: 'ts-1',
connectionConfig: { host: 'relay.expo.dev', secret: 'TOKENx', reconnecting: false },
@@ -279,16 +291,16 @@ describe(WorkflowJobSshQuery.connectInfoForResourceIdAsync.name, () => {
if ('workflowJobId' in variables) {
return found.workflowJob
? { data: { workflowJobs: { byId: found.workflowJob } } }
: { data: undefined, error: notFound };
: { data: undefined, error: notFound(workflowJobNotFoundError) };
}
if ('buildId' in variables) {
return found.build
? { data: { builds: { byId: found.build } } }
: { data: undefined, error: notFound };
: { data: undefined, error: notFound(buildNotFoundError) };
}
return found.jobRun
? { data: { jobRun: { byId: found.jobRun } } }
: { data: undefined, error: notFound };
: { data: undefined, error: notFound(jobRunNotFoundError) };
},
}));
return { graphqlClient: { query } as unknown as ExpoGraphqlClient, query };
@@ -1,3 +1,4 @@
import { print } from 'graphql';
import gql from 'graphql-tag';
export const UpdateFragmentNode = gql`
@@ -58,3 +59,19 @@ export const UpdateFragmentNode = gql`
assetHostOverride
}
`;
/**
* UpdateFragment plus the stored file URLs.
*
* Each URL is signed on demand by the server, which is not free, so only query this where the
* URLs are actually shown. List queries should use UpdateFragment.
*/
export const UpdateWithFileUrlsFragmentNode = gql`
fragment UpdateWithFileUrlsFragment on Update {
id
...UpdateFragment
assetMapUrl
sourceMapUrl
}
${print(UpdateFragmentNode)}
`;
@@ -0,0 +1,25 @@
import { print } from 'graphql';
import { UpdateFragmentNode, UpdateWithFileUrlsFragmentNode } from '../Update';
const FILE_URL_FIELDS = ['assetMapUrl', 'sourceMapUrl'];
describe('UpdateFragment', () => {
// The server signs each of these URLs per request, so list queries must not ask for them.
it.each(FILE_URL_FIELDS)('does not request %s', field => {
expect(print(UpdateFragmentNode)).not.toContain(field);
});
});
describe('UpdateWithFileUrlsFragment', () => {
it.each(FILE_URL_FIELDS)('requests %s', field => {
expect(print(UpdateWithFileUrlsFragmentNode)).toContain(field);
});
it('builds on UpdateFragment rather than duplicating its fields', () => {
const printed = print(UpdateWithFileUrlsFragmentNode);
expect(printed).toContain('...UpdateFragment');
expect(printed).toContain('fragment UpdateFragment on Update');
});
});
@@ -0,0 +1,99 @@
import { CombinedError } from '@urql/core';
import { GraphQLError } from 'graphql';
import { simulatorRequestFailureReason, simulatorRequestProperties } from '../requestAnalytics';
const properties = simulatorRequestProperties({
projectId: 'project-123',
type: 'serve-sim',
platform: 'IOS',
hasBuildId: false,
hasArchiveUrl: false,
expoGo: false,
nonInteractive: true,
});
function networkError(fields: { code?: string; name?: string; causeCode?: string } = {}): Error {
const error = new Error('fetch failed') as Error & { code?: string; cause?: { code?: string } };
if (fields.name) {
error.name = fields.name;
}
if (fields.code) {
error.code = fields.code;
}
if (fields.causeCode) {
error.cause = { code: fields.causeCode };
}
return error;
}
describe(simulatorRequestProperties, () => {
it('names the funnel reference properties and leaves out an unset package version', () => {
expect(properties).toEqual({
project_id: 'project-123',
origin: 'eas-cli',
type: 'serve-sim',
platform: 'ios',
has_build_id: false,
has_archive_url: false,
expo_go: false,
non_interactive: true,
});
expect(
simulatorRequestProperties({
projectId: 'p',
type: 'argent',
platform: 'ANDROID',
hasBuildId: true,
hasArchiveUrl: true,
expoGo: true,
packageVersion: '0.22.1',
nonInteractive: false,
})
).toMatchObject({ platform: 'android', requested_package_version: '0.22.1' });
});
});
describe(simulatorRequestFailureReason, () => {
it('reports a timeout from the error code, its cause, or the error name', () => {
for (const error of [
networkError({ code: 'ETIMEDOUT' }),
networkError({ causeCode: 'UND_ERR_CONNECT_TIMEOUT' }),
networkError({ name: 'AbortError' }),
networkError({ name: 'TimeoutError' }),
]) {
expect(simulatorRequestFailureReason(new CombinedError({ networkError: error }))).toBe(
'timeout'
);
}
});
it('reports any other missing answer as a network error', () => {
expect(
simulatorRequestFailureReason(
new CombinedError({ networkError: networkError({ code: 'ECONNRESET' }) })
)
).toBe('network_error');
});
it('is null when the server answered, since www reports refusals', () => {
expect(
simulatorRequestFailureReason(
new CombinedError({
graphQLErrors: [new GraphQLError('Simulator sessions are not enabled')],
})
)
).toBeNull();
expect(
simulatorRequestFailureReason(new Error('Returned query result data is null!'))
).toBeNull();
expect(
simulatorRequestFailureReason(
new CombinedError({
networkError: new Error('Gateway Timeout'),
response: { status: 504, statusText: 'Gateway Timeout' },
})
)
).toBeNull();
});
});
@@ -0,0 +1,75 @@
import { CombinedError } from '@urql/core';
import { AnalyticsEventProperties } from '../analytics/AnalyticsManager';
/** Matches www's `request_origin` value for eas-cli, though this CLI does not send it to www yet. */
export const SIMULATOR_REQUEST_ORIGIN = 'eas-cli';
export type SimulatorRequestFailureReason = 'network_error' | 'timeout';
const TIMEOUT_CODES = new Set([
'ETIMEDOUT',
'ESOCKETTIMEDOUT',
'UND_ERR_CONNECT_TIMEOUT',
'UND_ERR_HEADERS_TIMEOUT',
]);
export function simulatorRequestProperties({
projectId,
type,
platform,
hasBuildId,
hasArchiveUrl,
expoGo,
packageVersion,
nonInteractive,
}: {
projectId: string;
type: string;
platform: string;
hasBuildId: boolean;
hasArchiveUrl: boolean;
expoGo: boolean;
packageVersion?: string;
nonInteractive: boolean;
}): AnalyticsEventProperties {
return {
project_id: projectId,
origin: SIMULATOR_REQUEST_ORIGIN,
type,
platform: platform.toLowerCase(),
has_build_id: hasBuildId,
has_archive_url: hasArchiveUrl,
expo_go: expoGo,
...(packageVersion ? { requested_package_version: packageVersion } : {}),
non_interactive: nonInteractive,
};
}
/**
* Why the create request got no answer, or null when the server answered. A server refusal is
* not a client failure: www reports it as an admission denial, so counting it here would count
* the same attempt twice.
*/
export function simulatorRequestFailureReason(
error: unknown
): SimulatorRequestFailureReason | null {
if (!(error instanceof CombinedError) || !error.networkError || error.graphQLErrors.length > 0) {
return null;
}
// urql attaches the HTTP response to non-2xx answers too, such as a 504 from the load balancer.
// An answer arrived, so www may have seen the request already.
if (error.response) {
return null;
}
const networkError = error.networkError as Error & { code?: string; cause?: { code?: string } };
const code = networkError.code ?? networkError.cause?.code;
if (
(code && TIMEOUT_CODES.has(code)) ||
networkError.name === 'AbortError' ||
networkError.name === 'TimeoutError'
) {
return 'timeout';
}
return 'network_error';
}
@@ -1,4 +1,29 @@
import { getPlatformsForGroup, truncateString } from '../utils';
import { UpdateWithFileUrlsFragment } from '../../graphql/generated';
import {
getPlatformsForGroup,
getUpdateWithFileUrlsJsonInfosForUpdates,
truncateString,
} from '../utils';
function makeUpdate(
overrides: Partial<UpdateWithFileUrlsFragment> = {}
): UpdateWithFileUrlsFragment {
return {
id: 'update-1',
group: 'group-1',
message: 'a message',
createdAt: '2026-01-01T00:00:00Z',
platform: 'ios',
manifestFragment: '{}',
isRollBackToEmbedded: false,
manifestPermalink: 'https://expo.dev/manifest',
gitCommitHash: 'abc123',
isGitWorkingTreeDirty: false,
branch: { id: 'branch-1', name: 'main' },
runtime: { id: 'runtime-1', version: '1.0.0' },
...overrides,
} as UpdateWithFileUrlsFragment;
}
describe('update utility functions', () => {
describe(truncateString, () => {
@@ -16,6 +41,41 @@ describe('update utility functions', () => {
});
});
describe(getUpdateWithFileUrlsJsonInfosForUpdates, () => {
it('includes the signed asset map and source map URLs', () => {
const [info] = getUpdateWithFileUrlsJsonInfosForUpdates([
makeUpdate({
assetMapUrl: 'https://storage.example/assetmap.json?signature',
sourceMapUrl: 'https://storage.example/updates/ios.map?signature',
}),
]);
expect(info.assetMapUrl).toBe('https://storage.example/assetmap.json?signature');
expect(info.sourceMapUrl).toBe('https://storage.example/updates/ios.map?signature');
});
it.each([[null], [undefined]])(
'reports both URLs as null when the server returns %p',
value => {
const [info] = getUpdateWithFileUrlsJsonInfosForUpdates([
makeUpdate({ assetMapUrl: value, sourceMapUrl: value }),
]);
expect(info.assetMapUrl).toBeNull();
expect(info.sourceMapUrl).toBeNull();
}
);
it('reports sourceMapUrl as null for an update published without source maps', () => {
const [info] = getUpdateWithFileUrlsJsonInfosForUpdates([
makeUpdate({ assetMapUrl: 'https://storage.example/assetmap.json?signature' }),
]);
expect(info.assetMapUrl).not.toBeNull();
expect(info.sourceMapUrl).toBeNull();
});
});
describe(getPlatformsForGroup.name, () => {
it.each([
{ group: 'abc', updates: [] },
+20
View File
@@ -14,6 +14,7 @@ import {
UpdateBranchFragment,
UpdateFragment,
UpdatePublishMutation,
UpdateWithFileUrlsFragment,
User,
} from '../graphql/generated';
import { AssetQuery } from '../graphql/queries/AssetQuery';
@@ -39,6 +40,9 @@ export type UpdateJsonInfo = { branch: string; runtimeVersion: string } & Pick<
'id' | 'createdAt' | 'group' | 'message' | 'platform' | 'manifestPermalink' | 'gitCommitHash'
>;
export type UpdateWithFileUrlsJsonInfo = UpdateJsonInfo &
Pick<UpdateWithFileUrlsFragment, 'assetMapUrl' | 'sourceMapUrl'>;
export type UpdateGroupDescription = FormatUpdateParameter & {
branch: string;
group: string;
@@ -224,6 +228,22 @@ export function getUpdateJsonInfosForUpdates(updates: UpdateFragment[]): UpdateJ
}));
}
/**
* Same as getUpdateJsonInfosForUpdates, with the stored file URLs. Only `eas update:view` queries
* those, because the server signs each one per request.
*/
export function getUpdateWithFileUrlsJsonInfosForUpdates(
updates: UpdateWithFileUrlsFragment[]
): UpdateWithFileUrlsJsonInfo[] {
return getUpdateJsonInfosForUpdates(updates).map((info, index) => ({
...info,
// Null unless the update was published with an asset map. The URL is signed and expires.
assetMapUrl: updates[index].assetMapUrl ?? null,
// Null unless published with `--upload-source-maps`. The URL is signed and expires.
sourceMapUrl: updates[index].sourceMapUrl ?? null,
}));
}
export function getUpdateGroupDescriptions(
updateGroups: UpdateFragment[][]
): FormattedUpdateGroupDescription[] {
@@ -0,0 +1,86 @@
import os from 'os';
import path from 'path';
import fs from 'fs-extra';
import { create } from 'tar';
import { extractAppFromLocalArchiveAsync } from '../download';
import * as Paths from '../paths';
import { AppPlatform } from '../../graphql/generated';
import { promptAsync } from '../../prompts';
jest.mock('../../prompts');
const mockPromptAsync = jest.mocked(promptAsync);
describe(extractAppFromLocalArchiveAsync, () => {
let tmpDir: string;
beforeEach(async () => {
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'eas-cli-download-test-'));
jest.spyOn(Paths, 'getTmpDirectory').mockReturnValue(tmpDir);
mockPromptAsync.mockReset();
});
afterEach(async () => {
jest.restoreAllMocks();
await fs.remove(tmpDir);
});
async function makeArchiveAsync(appPaths: string[]): Promise<string> {
const contentsDir = path.join(tmpDir, 'contents');
await fs.ensureDir(contentsDir);
for (const appPath of appPaths) {
await fs.ensureDir(path.join(contentsDir, appPath));
}
const archivePath = path.join(tmpDir, 'apps.tar.gz');
await create({ file: archivePath, cwd: contentsDir, gzip: true }, ['.']);
return archivePath;
}
it('selects the containing app without prompting for its nested App Clip', async () => {
const archivePath = await makeArchiveAsync([
'Bluesky.app',
'Bluesky.app/AppClips/BlueskyClip.app',
]);
const appPath = await extractAppFromLocalArchiveAsync(archivePath, AppPlatform.Ios);
expect(path.basename(appPath)).toBe('Bluesky.app');
expect(await fs.pathExists(path.join(appPath, 'AppClips/BlueskyClip.app'))).toBe(true);
expect(mockPromptAsync).not.toHaveBeenCalled();
});
it('prompts for separate apps but excludes nested App Clips from the choices', async () => {
const archivePath = await makeArchiveAsync([
'Bluesky.app',
'Bluesky.app/AppClips/BlueskyClip.app',
'Bluesky.app.backup.app',
]);
mockPromptAsync.mockResolvedValueOnce({ selectedFile: './Bluesky.app.backup.app' });
const appPath = await extractAppFromLocalArchiveAsync(archivePath, AppPlatform.Ios);
expect(path.basename(appPath)).toBe('Bluesky.app.backup.app');
const [question] = mockPromptAsync.mock.calls[0];
if (Array.isArray(question)) {
throw new Error('Expected a single app selection prompt');
}
expect(question.choices).toHaveLength(2);
expect(question.choices).toEqual(
expect.arrayContaining([
expect.objectContaining({ title: expect.stringMatching(/Bluesky\.app$/) }),
expect.objectContaining({ title: expect.stringMatching(/Bluesky\.app\.backup\.app$/) }),
])
);
});
it('throws when the archive contains no apps', async () => {
const archivePath = await makeArchiveAsync([]);
await expect(extractAppFromLocalArchiveAsync(archivePath, AppPlatform.Ios)).rejects.toThrow(
'Did not find any installable apps inside tarball.'
);
expect(mockPromptAsync).not.toHaveBeenCalled();
});
});
+8 -3
View File
@@ -172,8 +172,13 @@ async function getAppPathAsync(outputDir: string, applicationExtension: string):
throw Error('Did not find any installable apps inside tarball.');
}
if (appFilePaths.length === 1) {
return path.join(outputDir, appFilePaths[0]);
// App Clips are nested inside their containing iOS app and cannot be run independently.
const installableAppPaths = appFilePaths.filter(
filePath => !appFilePaths.some(parentPath => filePath.startsWith(`${parentPath}/`))
);
if (installableAppPaths.length === 1) {
return path.join(outputDir, installableAppPaths[0]);
}
Log.newLine();
@@ -184,7 +189,7 @@ async function getAppPathAsync(outputDir: string, applicationExtension: string):
message: 'Select the app to run:',
name: 'selectedFile',
choices: [
...appFilePaths.map(filePath => ({
...installableAppPaths.map(filePath => ({
title: filePath,
value: filePath,
})),
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "eas-cli-local-build-plugin",
"version": "24.11.0",
"version": "24.12.0",
"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.11.0",
"@expo/build-tools": "24.12.0",
"@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.11.0",
"version": "24.12.0",
"private": true,
"scripts": {
"start": "yarn watch",
@@ -19,7 +19,7 @@
},
"dependencies": {
"@babel/core": "7.24.7",
"@expo/build-tools": "24.11.0",
"@expo/build-tools": "24.12.0",
"@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.11.0, @expo/build-tools@workspace:packages/build-tools":
"@expo/build-tools@npm:24.12.0, @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.11.0"
"@expo/build-tools": "npm:24.12.0"
"@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.11.0"
"@expo/build-tools": "npm:24.12.0"
"@expo/bunyan": "npm:^4.0.1"
"@expo/eas-build-job": "npm:24.9.0"
"@expo/logger": "npm:24.8.0"