Compare commits

...
Author SHA1 Message Date
Ash Wu 5fe8c311d7 [build-tools] add the step functions that detect the Xcode project of a native iOS build 2026-11-23 23:05:17 +08:00
Ash Wu 6936b4f4e6 [eas-build-job] add builder to the build metadata 2026-11-23 22:32:24 +08:00
Ash Wu 346cc030d8 [eas-build-job] add the native job schema for Android 2026-11-23 22:32:23 +08:00
Ash Wu 8b683079c6 [eas-build-job] add the native job schema for iOS 2026-11-23 22:32:23 +08:00
Ash Wu 22f1fae8ec [eas-build-job] add the NativeBuilder enum 2026-11-23 22:32:22 +08:00
Ash Wu 7abd3fe05a [build-tools] extract the custom build project preparation into prepareProjectForStepsAsync 2026-11-23 22:32:22 +08:00
Ash Wu bf5ba2b25a [build-tools] run the after_checkout hook in builds without custom steps (#4920) 2026-11-23 15:30:12 +08:00
Expo CI b78cda16a5 bump STAGING and PRODUCTION to 27.11.0 in cli-versions.json 2026-11-19 17:02:36 +00:00
Expo CI 67972c5d6a v27.11.0 2026-11-19 16:17:39 +00:00
Mustafa Abban d88708d842 [eas-build-job] support Observe error occurrence events (#4860) 2026-11-19 10:41:38 -05:00
expo-tuft[bot] 13056cac22 [build-tools] report the installed app identifier in the agent-device remote config (#4831) 2026-11-19 18:02:26 +08:00
David Mokos 1b45814e3c updates agent-cli-detector to 0.1.8 (#4912) 2026-11-19 00:34:22 +01:00
Tomasz Mazur 8d00e33806 [build-tools] Compress dSYMs with zip level 1 in fastlane gym (#4909) 2026-11-18 21:05:24 +01:00
Szymon Świerk f27e7988a1 [eas-build-job] Accept issue_comment as a workflow github.event_name (#4906) 2026-11-17 18:45:59 +01:00
Gabe DebesandClaude Opus 5.5 b4e4229464 [build-tools] Add step functions to record simulator crash artifacts (#4596)
* [build-tools] Collect simulator crash artifacts

* [build-tools] Use shared crash artifact upload deadlines

* [build-tools] Link crash artifact changelog entry

* [build-tools] Bound crash collection retries and uploads

* [build-tools] Keep retrying productive crash streams

* [build-tools] preserve crash shutdown mock in merged host tests

* Save individual native IPS crash artifacts

* [build-tools] Keep missing crash reports outside artifact limits

* [build-tools] Verify missing crash reports across reconnects

* [build-tools] Reserve crash collection before asynchronous setup

* [build-tools] Release failed crash recorder initialization

* [build-tools] Address crash artifact review findings

Skip a crash occurrence whose detail fails or exceeds 8 MiB instead of
reconnecting, and check each device's crash list once more on stop so
occurrences the stream had not delivered are kept. Key occurrences by
capture time and report path, merge the seen and skipped sets, create the
directory before the session is registered, and log dropped errors.
Artifacts are now kind simulator-crash with per-device numbered ids,
names, and filenames.

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

* [build-tools] Retry transient crash detail failures

Try a failed crash detail up to three times before skipping it; skip a
missing, mismatched, malformed, or oversized detail at once.

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

* [build-tools] Address second crash artifact review

Keep each device's serve-sim address current for the final pass, warn
when its deadline stops a device, report poller and upload failures to
Sentry, name failed uploads by report, and fall back to the process name
when the app name is empty.

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

* [build-tools] Skip crash details that a retry cannot fix

Treat invalid JSON and permanent 4xx responses as unusable, so they are
not retried three times before later reports are collected.

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

* [build-tools] Upload crash reports with the shared file upload helper

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-16 16:09:00 -07:00
Gabe DebesandClaude Opus 5.5 a04489e678 [build-tools] Add step functions to record simulator HAR artifacts (#4495)
* [build-tools] record network capture with serve-sim capture har steps

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* [build-tools] Rename the network capture recording step

Edited-by: Codex

* [build-tools] Remove the capture recorder command override

Edited-by: Codex

* [build-tools] Bound failed network capture followers

* [build-tools] Limit HAR artifact uploads to 500 MiB

* [build-tools] Address HAR capture review findings

Rename the record step to eas/start_serve_sim_network_capture and the
upload helper to a one-file serveSimNetworkCaptureArtifacts; the collect
step numbers parts. Count HARs by their entry log so empty recordings
are neither uploaded nor use recording slots, give followers that record
nothing a slower restart and a separate start cap, drop the spawn
failure throttle and unreachable guards, and allow 60 s for the final
HAR rebuild with followers stopped together.

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

* [build-tools] Bound HAR recording slots and uploads

Exited followers that recorded nothing no longer use recording slots, a
restarted serve-sim replaces the old identity's follower, the recording
limit warns once, and each HAR upload has a 10-minute limit.

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

* [build-tools] Keep the ngrok token from the HAR follower

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

* [build-tools] Drop requests a restarted HAR follower replays

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

* [build-tools] Keep unflushed HAR requests and remove replayed parts

Rebuild every kept HAR from its entry log before its requests count as
recorded, and delete the files of a follower that held only replayed
requests when it is dropped.

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

* [build-tools] Upload network captures with the shared file upload helper

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

* [build-tools] Import formatBytes from eas-build-job

Main moved formatBytes into @expo/eas-build-job (#4854).

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-11-16 16:09:00 -07:00
110 changed files with 6470 additions and 399 deletions

No files matched your search

@@ -1,5 +0,0 @@
---
'@expo/build-tools': minor
---
Count Android web preview input as session activity, so `max_idle_time_minutes` works on Android sessions. `eas/start_serve_sim_remote_session` no longer rejects it on Android; the API does not accept an idle timeout for Android web-preview-only sessions yet.
+5
View File
@@ -0,0 +1,5 @@
---
'@expo/build-tools': minor
---
Run the `after_checkout` workflow hook in build jobs that do not use custom steps.
+5
View File
@@ -0,0 +1,5 @@
---
'@expo/eas-build-job': minor
---
Add the native job schema for Android, with the `builder` field.
+5
View File
@@ -0,0 +1,5 @@
---
'@expo/eas-build-job': minor
---
Add `builder` to the build metadata.
+5
View File
@@ -0,0 +1,5 @@
---
'@expo/eas-build-job': minor
---
Add the `NativeBuilder` enum.
+5
View File
@@ -0,0 +1,5 @@
---
'@expo/eas-build-job': minor
---
Add the native job schema for iOS: `builder`, `projectFile`, and `secrets.credentialsByBundleIdentifier`.
+5
View File
@@ -0,0 +1,5 @@
---
'@expo/build-tools': none
---
Add the step functions that install pods and detect the Xcode project for a native iOS build.
+5
View File
@@ -0,0 +1,5 @@
---
'@expo/build-tools': none
---
Extract the custom build project preparation into `prepareProjectForStepsAsync`.
-5
View File
@@ -1,5 +0,0 @@
---
'eas-cli': patch
---
Mark the default device for each platform in `eas simulator:devices` and include `isDefault` in JSON output.
@@ -1,5 +0,0 @@
---
'@expo/build-tools': patch
---
A successful remote device run session no longer fails when its agent-device, Appium, or Argent tunnel does not stop within its time-out.
+18
View File
@@ -2,6 +2,24 @@
This is the log of notable changes to EAS CLI and related packages.
## [27.11.0](https://github.com/expo/eas-cli/releases/tag/v27.11.0) - 2026-11-19
### 🎉 New features
- [build-tools] Report the identifier of the installed app as `applicationIdentifier` in the agent-device remote config, so clients can attach to the app of an `application_archive_url` session. ([#4831](https://github.com/expo/eas-cli/pull/4831) by [@expo-tuft](https://github.com/apps/expo-tuft))
- [build-tools] Count Android web preview input as session activity, so `max_idle_time_minutes` works on Android sessions. `eas/start_serve_sim_remote_session` no longer rejects it on Android; the API does not accept an idle timeout for Android web-preview-only sessions yet. ([#4890](https://github.com/expo/eas-cli/pull/4890) by [@szdziedzic](https://github.com/szdziedzic))
- [eas-build-job] Accept `issue_comment` as a `github.event_name` value in the workflow interpolation context. ([#4906](https://github.com/expo/eas-cli/pull/4906) by [@sswrk](https://github.com/sswrk))
- [eas-build-job] Support error occurrence events in Observe workflow context. ([#4860](https://github.com/expo/eas-cli/pull/4860) by [@AbbanMustafa](https://github.com/AbbanMustafa))
- [build-tools] Add start and collect steps that attach serve-sim simulator crash reports to device run sessions as IPS files. ([#4596](https://github.com/expo/eas-cli/pull/4596) by [@gwdp](https://github.com/gwdp))
- [build-tools] Add start and collect steps that attach serve-sim network captures to device run sessions as HAR files. ([#4495](https://github.com/expo/eas-cli/pull/4495) by [@gwdp](https://github.com/gwdp))
### 🐛 Bug fixes
- [eas-cli] Detect Factory Droid, Grok Bot, Claude Cowork, and Muse in EAS CLI telemetry. ([#4912](https://github.com/expo/eas-cli/pull/4912) by [@davidmokos](https://github.com/davidmokos))
- [build-tools] Default `fastlane gym` dSYM compression level to 1. ([#4909](https://github.com/expo/eas-cli/pull/4909) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
- [eas-cli] Mark the default device for each platform in `eas simulator:devices` and include `isDefault` in JSON output. ([#4895](https://github.com/expo/eas-cli/pull/4895) by [@gwdp](https://github.com/gwdp))
- [build-tools] A successful remote device run session no longer fails when its agent-device, Appium, or Argent tunnel does not stop within its time-out. ([#4893](https://github.com/expo/eas-cli/pull/4893) by [@szdziedzic](https://github.com/szdziedzic))
## [27.10.0](https://github.com/expo/eas-cli/releases/tag/v27.10.0) - 2026-11-13
### 🎉 New features
+2 -2
View File
@@ -1,4 +1,4 @@
{
"STAGING": "27.10.0",
"PRODUCTION": "27.10.0"
"STAGING": "27.11.0",
"PRODUCTION": "27.11.0"
}
+1 -1
View File
@@ -1,5 +1,5 @@
{
"npmClient": "yarn",
"version": "27.10.0",
"version": "27.11.0",
"$schema": "node_modules/lerna/schemas/lerna-schema.json"
}
+14
View File
@@ -1,5 +1,19 @@
# @expo/build-tools
## 27.11.0
### Minor Changes
- Report the identifier of the installed app as `applicationIdentifier` in the agent-device remote config, so clients can attach to the app of an `application_archive_url` session. ([#4831](https://github.com/expo/eas-cli/pull/4831) by [@expo-tuft](https://github.com/apps/expo-tuft))
- Count Android web preview input as session activity, so `max_idle_time_minutes` works on Android sessions. `eas/start_serve_sim_remote_session` no longer rejects it on Android; the API does not accept an idle timeout for Android web-preview-only sessions yet. ([#4890](https://github.com/expo/eas-cli/pull/4890) by [@szdziedzic](https://github.com/szdziedzic))
- Add start and collect steps that attach serve-sim simulator crash reports to device run sessions as IPS files. ([#4596](https://github.com/expo/eas-cli/pull/4596) by [@gwdp](https://github.com/gwdp))
- Add start and collect steps that attach serve-sim network captures to device run sessions as HAR files. ([#4495](https://github.com/expo/eas-cli/pull/4495) by [@gwdp](https://github.com/gwdp))
### Patch Changes
- Default `fastlane gym` dSYM compression level to 1. ([#4909](https://github.com/expo/eas-cli/pull/4909) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
- A successful remote device run session no longer fails when its agent-device, Appium, or Argent tunnel does not stop within its time-out. ([#4893](https://github.com/expo/eas-cli/pull/4893) by [@szdziedzic](https://github.com/szdziedzic))
## 27.10.0
### Minor Changes
+8 -7
View File
@@ -1,6 +1,6 @@
{
"name": "@expo/build-tools",
"version": "27.10.0",
"version": "27.11.0",
"bugs": "https://github.com/expo/eas-cli/issues",
"license": "BUSL-1.1",
"author": "Expo <[email protected]>",
@@ -42,17 +42,17 @@
"dependencies": {
"@expo/config": "55.0.10",
"@expo/config-plugins": "55.0.7",
"@expo/downloader": "27.10.0",
"@expo/eas-build-job": "27.10.0",
"@expo/downloader": "27.11.0",
"@expo/eas-build-job": "27.11.0",
"@expo/env": "^0.4.0",
"@expo/logger": "27.10.0",
"@expo/logger": "27.11.0",
"@expo/package-manager": "1.9.10",
"@expo/plist": "^0.3.5",
"@expo/results": "^1.0.0",
"@expo/spawn-async": "1.7.2",
"@expo/steps": "27.10.0",
"@expo/template-file": "27.10.0",
"@expo/turtle-spawn": "27.10.0",
"@expo/steps": "27.11.0",
"@expo/template-file": "27.11.0",
"@expo/turtle-spawn": "27.11.0",
"@expo/xcpretty": "^4.4.7",
"@ngrok/ngrok": "1.7.0",
"@sentry/node": "7.77.0",
@@ -80,6 +80,7 @@
"tar": "7.5.22",
"uuid": "9.0.1",
"ws": "8.21.1",
"xcode": "^3.0.1",
"yaml": "^2.9.1",
"zod": "^4.6.7"
},
@@ -91,7 +91,7 @@ describe(androidBuilder, () => {
);
});
it('passes the install_node_modules anchor and a hooks ref to setupAsync', async () => {
it('passes a hooks ref to setupAsync', async () => {
const ctx = new BuildContext(createTestAndroidJob(), {
workingdir: '/workingdir',
logBuffer: { getLogs: () => [], getPhaseLogs: () => [] },
@@ -105,7 +105,6 @@ describe(androidBuilder, () => {
expect(setupAsync).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
wrappedAnchors: ['install_node_modules'],
jobHooksRef: expect.objectContaining({ current: null }),
})
);
+1 -1
View File
@@ -72,7 +72,7 @@ async function buildInnerAsync(
ctx: BuildContext<Android.Job>,
jobHooksRef: JobHooksRef
): Promise<void> {
await setupAsync(ctx, { wrappedAnchors: ['install_node_modules'], jobHooksRef });
await setupAsync(ctx, { jobHooksRef });
const evictUsedBefore = new Date();
const workingDirectory = ctx.getReactNativeProjectDirectory();
const hasNativeCode = ctx.job.type === Workflow.GENERIC;
+2 -19
View File
@@ -9,39 +9,22 @@ import {
errors,
} from '@expo/steps';
import assert from 'assert';
import fs from 'fs/promises';
import nullthrows from 'nullthrows';
import path from 'path';
import { prepareProjectForStepsAsync } from './prepareProjectForSteps';
import { resolveEnvFromBuildProfileAsync } from '../common/easBuildInternal';
import { prepareProjectSourcesAsync } from '../common/projectSources';
import { Artifacts, BuildContext } from '../context';
import { CustomBuildContext } from '../customBuildContext';
import { Datadog } from '../datadog';
import { findAndUploadXcodeBuildLogsAsync } from '../ios/xcodeBuildLogs';
import { getEasFunctionGroups } from '../steps/easFunctionGroups';
import { getEasFunctions } from '../steps/easFunctions';
import { retryAsync } from '../utils/retry';
export async function runCustomBuildAsync(ctx: BuildContext<BuildJob>): Promise<Artifacts> {
const customBuildCtx = new CustomBuildContext(ctx);
await ctx.runBuildPhase(BuildPhase.PREPARE_PROJECT, async () => {
await retryAsync(
async () => {
await fs.rm(customBuildCtx.projectSourceDirectory, { recursive: true, force: true });
await fs.mkdir(customBuildCtx.projectSourceDirectory, { recursive: true });
await prepareProjectSourcesAsync(ctx, customBuildCtx.projectSourceDirectory);
},
{
retryOptions: {
retries: 3,
retryIntervalMs: 1_000,
},
}
);
});
await prepareProjectForStepsAsync(ctx, customBuildCtx.projectSourceDirectory);
if (ctx.job.triggeredBy === BuildTrigger.GIT_BASED_INTEGRATION) {
// We need to setup envs from eas.json
+1 -1
View File
@@ -76,7 +76,7 @@ async function buildInnerAsync(
ctx: BuildContext<Ios.Job>,
jobHooksRef: JobHooksRef
): Promise<void> {
await setupAsync(ctx, { wrappedAnchors: ['install_node_modules'], jobHooksRef });
await setupAsync(ctx, { jobHooksRef });
const hasNativeCode = ctx.job.type === Workflow.GENERIC;
const evictUsedBefore = new Date();
const credentialsManager = new CredentialsManager(ctx);
@@ -0,0 +1,28 @@
import { BuildJob, BuildPhase } from '@expo/eas-build-job';
import fs from 'fs/promises';
import { prepareProjectSourcesAsync } from '../common/projectSources';
import { BuildContext } from '../context';
import { retryAsync } from '../utils/retry';
export async function prepareProjectForStepsAsync(
ctx: BuildContext<BuildJob>,
projectSourceDirectory: string
): Promise<void> {
await ctx.runBuildPhase(BuildPhase.PREPARE_PROJECT, async () => {
await retryAsync(
async () => {
await fs.rm(projectSourceDirectory, { recursive: true, force: true });
await fs.mkdir(projectSourceDirectory, { recursive: true });
await prepareProjectSourcesAsync(ctx, projectSourceDirectory);
},
{
retryOptions: {
retries: 3,
retryIntervalMs: 1_000,
},
}
);
});
}
@@ -1,10 +1,10 @@
import { BuildPhase, BuildTrigger, Hooks, Ios } from '@expo/eas-build-job';
import { BuildPhase, BuildTrigger, HookKey, Hooks, Ios } from '@expo/eas-build-job';
import { bunyan } from '@expo/logger';
import { executeHookStepsAsync } from '@expo/steps';
import { createTestIosJob } from '../../__tests__/utils/job';
import { BuildContext } from '../../context';
import { runHookableBuildPhaseAsync } from '../hookableBuildPhase';
import { runHookEntriesAsync, runHookableBuildPhaseAsync } from '../hookableBuildPhase';
import { ParsedJobHooks, parseJobHooksAsync } from '../jobHooks';
// The primitive's step-execution rules (failure()/success(), no-if continuation,
@@ -16,7 +16,10 @@ jest.mock('@expo/steps', () => ({
}));
const executeHookStepsMock = jest.mocked(executeHookStepsAsync);
async function setup(hooks: Hooks | undefined): Promise<{
async function setup(
hooks: Hooks | undefined,
hookKeys: readonly HookKey[] = ['before_install_node_modules', 'after_install_node_modules']
): Promise<{
ctx: BuildContext<Ios.Job>;
hooks: ParsedJobHooks | null;
}> {
@@ -40,7 +43,7 @@ async function setup(hooks: Hooks | undefined): Promise<{
jest
.spyOn(ctx, 'runBuildPhase')
.mockImplementation((_phase: BuildPhase, fn: () => Promise<unknown>) => fn() as never);
return { ctx, hooks: await parseJobHooksAsync(ctx, ['install_node_modules']) };
return { ctx, hooks: await parseJobHooksAsync(ctx, hookKeys) };
}
const runArgs = <TJob extends Ios.Job>(
@@ -162,3 +165,23 @@ describe(runHookableBuildPhaseAsync, () => {
expect(writeBack).toHaveBeenCalled();
});
});
describe(runHookEntriesAsync, () => {
beforeEach(() => {
executeHookStepsMock.mockReset();
executeHookStepsMock.mockResolvedValue({ failedLocally: false, firstError: undefined });
});
it('runs the after_checkout entries that the parser built', async () => {
const { ctx, hooks } = await setup({ after_checkout: [{ run: 'echo after' }] }, [
'after_checkout',
]);
await runHookEntriesAsync({ ctx, hooks: hooks!, timing: 'after', anchor: 'checkout' });
expect(hooks!.hookEntriesByKey.after_checkout).toHaveLength(1);
expect(executeHookStepsMock).toHaveBeenCalledWith(
hooks!.globalContext,
hooks!.hookEntriesByKey.after_checkout,
{ anchor: 'checkout', timing: 'after', anchorResult: 'success' }
);
});
});
@@ -9,7 +9,7 @@ import { createTestIosJob } from '../../__tests__/utils/job';
import { BuildContext } from '../../context';
import { parseJobHooksAsync } from '../jobHooks';
const INSTALL: ['install_node_modules'] = ['install_node_modules'];
const INSTALL = ['before_install_node_modules', 'after_install_node_modules'] as const;
function createCtx(
hooks: Hooks | undefined,
@@ -4,7 +4,7 @@ import { createTestAndroidJob } from '../../__tests__/utils/job';
import { createMockLogger } from '../../__tests__/utils/logger';
import { BuildContext } from '../../context';
import { resolveEnvFromBuildProfileAsync, runEasBuildInternalAsync } from '../easBuildInternal';
import { runHookableBuildPhaseAsync } from '../hookableBuildPhase';
import { runHookEntriesAsync, runHookableBuildPhaseAsync } from '../hookableBuildPhase';
import { JobHooksRef, setupAsync } from '../setup';
import { ParsedJobHooks, parseJobHooksAsync } from '../jobHooks';
import { prepareProjectSourcesAsync } from '../projectSources';
@@ -15,7 +15,10 @@ jest.mock('../easBuildInternal', () => ({
resolveEnvFromBuildProfileAsync: jest.fn(),
runEasBuildInternalAsync: jest.fn(),
}));
jest.mock('../hookableBuildPhase', () => ({ runHookableBuildPhaseAsync: jest.fn() }));
jest.mock('../hookableBuildPhase', () => ({
runHookEntriesAsync: jest.fn(),
runHookableBuildPhaseAsync: jest.fn(),
}));
jest.mock('../jobHooks', () => ({ parseJobHooksAsync: jest.fn() }));
jest.mock('../../utils/npmrc', () => ({ setUpNpmrcAsync: jest.fn() }));
jest.mock('../../utils/hooks', () => ({
@@ -79,6 +82,9 @@ describe(setupAsync, () => {
order.push('parse-hooks');
return PARSED;
});
jest.mocked(runHookEntriesAsync).mockImplementation(async () => {
order.push('after-checkout-hooks');
});
jest.mocked(runHookableBuildPhaseAsync).mockImplementation(async () => {
// Record the wrapper call; deliberately do NOT run its `fn` so the install
// internals stay out of the ordering test.
@@ -91,23 +97,50 @@ describe(setupAsync, () => {
}));
});
it('parses hooks after project prep + profile-env + pre-install hook, and before the install wrapper', async () => {
it('parses hooks after project prep + profile-env + pre-install hook, then runs the after_checkout hooks before the install wrapper', async () => {
const jobHooksRef: JobHooksRef = { current: null };
await setupAsync(createCtx(BuildTrigger.GIT_BASED_INTEGRATION), {
wrappedAnchors: ['install_node_modules'],
jobHooksRef,
});
const parseAt = order.indexOf('parse-hooks');
expect(order.indexOf('prepare-project')).toBeLessThan(parseAt);
expect(order.indexOf('profile-env')).toBeLessThan(parseAt);
expect(order.indexOf('pre-install-hook')).toBeLessThan(parseAt);
expect(parseAt).toBeLessThan(order.indexOf('install-wrapper'));
expect(order).toEqual([
'prepare-project',
'profile-env',
'pre-install-hook',
'parse-hooks',
'after-checkout-hooks',
'install-wrapper',
]);
expect(parseJobHooksAsync).toHaveBeenCalledWith(expect.anything(), [
'after_checkout',
'before_install_node_modules',
'after_install_node_modules',
]);
expect(runHookEntriesAsync).toHaveBeenCalledWith(
expect.objectContaining({ hooks: PARSED, timing: 'after', anchor: 'checkout' })
);
});
it('publishes the parsed hooks to the ref before an after_checkout hook can fail', async () => {
jest.mocked(runHookEntriesAsync).mockRejectedValueOnce(new Error('hook boom'));
const jobHooksRef: JobHooksRef = { current: null };
await expect(
setupAsync(createCtx(BuildTrigger.GIT_BASED_INTEGRATION), { jobHooksRef })
).rejects.toThrow('hook boom');
expect(jobHooksRef.current).toBe(PARSED);
expect(runHookableBuildPhaseAsync).not.toHaveBeenCalled();
});
it('runs no after_checkout hooks when the job has no hooks', async () => {
jest.mocked(parseJobHooksAsync).mockResolvedValueOnce(null);
await setupAsync(createCtx(BuildTrigger.GIT_BASED_INTEGRATION), {
jobHooksRef: { current: null },
});
expect(runHookEntriesAsync).not.toHaveBeenCalled();
});
it('parses hooks unconditionally on a non-git-based build (never parked in the git-only branch)', async () => {
const jobHooksRef: JobHooksRef = { current: null };
await setupAsync(createCtx(BuildTrigger.EAS_CLI), {
wrappedAnchors: ['install_node_modules'],
jobHooksRef,
});
expect(parseJobHooksAsync).toHaveBeenCalledTimes(1);
@@ -119,7 +152,6 @@ describe(setupAsync, () => {
it('publishes the parsed hooks to the ref before the install wrapper runs', async () => {
const jobHooksRef: JobHooksRef = { current: null };
await setupAsync(createCtx(BuildTrigger.GIT_BASED_INTEGRATION), {
wrappedAnchors: ['install_node_modules'],
jobHooksRef,
});
expect(jobHooksRef.current).toBe(PARSED);
@@ -5,3 +5,7 @@ export const COMMON_FASTLANE_ENV = {
FASTLANE_HIDE_TIMESTAMP: 'true',
LC_ALL: 'en_US.UTF-8',
};
export const DEFAULT_FASTLANE_GYM_ENV = {
ZIPOPT: '-1',
};
@@ -57,7 +57,7 @@ export async function runHookableBuildPhaseAsync<TJob extends BuildJob, T>({
return result;
}
async function runHookEntriesAsync<TJob extends BuildJob>({
export async function runHookEntriesAsync<TJob extends BuildJob>({
ctx,
hooks,
timing,
+32 -36
View File
@@ -2,7 +2,6 @@ import {
BuildJob,
CompositeFunctionCatalog,
ErrorCode,
HookAnchorId,
HookKey,
UserError,
parseHookKey,
@@ -37,12 +36,12 @@ export interface ParsedJobHooks {
/**
* Parses the native job's `hooks` into engine-ready entries, once, at setup
* time. Shape-validates every registered key (reachable or not); constructs
* entries only for the anchors this build actually wraps. Returns null when the
* entries only for the hook keys this build runs. Returns null when the
* job declares no hooks.
*/
export async function parseJobHooksAsync<TJob extends BuildJob>(
ctx: BuildContext<TJob>,
wrappedAnchors: readonly HookAnchorId[]
hookKeys: readonly HookKey[]
): Promise<ParsedJobHooks | null> {
const hooks = ctx.job.hooks;
if (!hooks || Object.keys(hooks).length === 0) {
@@ -81,8 +80,8 @@ export async function parseJobHooksAsync<TJob extends BuildJob>(
}
}
// Construct entries for the wrapped anchors in EXECUTION order (per anchor,
// before_ then after_) so generated step ids and output references follow the
// Construct entries for the given hook keys in the order given, which is
// EXECUTION order, so generated step ids and output references follow the
// order steps actually run. All entries share one globalContext, so env and
// outputs accumulate across keys.
const hookEntriesByKey: Partial<Record<HookKey, HookEntry[]>> = {};
@@ -92,37 +91,34 @@ export async function parseJobHooksAsync<TJob extends BuildJob>(
ctx.getReactNativeProjectDirectory(),
{ logger: ctx.logger }
);
for (const anchor of wrappedAnchors) {
for (const side of ['before', 'after'] as const) {
const key: HookKey = `${side}_${anchor}`;
const steps = hooks[key];
if (!Array.isArray(steps) || steps.length === 0) {
continue;
}
let entries: HookEntry[];
try {
// Extended per key so a bad `uses:` path is attributed to that hook key.
await extendCompositeFunctionCatalogFromStepsAsync({
catalog: compositeFunctionCatalog,
rootSteps: steps,
loadCompositeFunction,
});
entries = await constructHookEntriesAsync(globalContext, steps, {
externalFunctions,
externalFunctionGroups,
compositeFunctionCatalog,
});
} catch (err) {
throw new UserError(
ErrorCode.HOOKS_ERROR,
`Failed to parse hooks.${key}: ${err instanceof Error ? err.message : String(err)}. Hooks use the same syntax as workflow steps.`,
{ cause: err }
);
}
hookEntriesByKey[key] = entries;
for (const entry of entries) {
orderedSteps.push(...entry.steps);
}
for (const key of hookKeys) {
const steps = hooks[key];
if (!Array.isArray(steps) || steps.length === 0) {
continue;
}
let entries: HookEntry[];
try {
// Extended per key so a bad `uses:` path is attributed to that hook key.
await extendCompositeFunctionCatalogFromStepsAsync({
catalog: compositeFunctionCatalog,
rootSteps: steps,
loadCompositeFunction,
});
entries = await constructHookEntriesAsync(globalContext, steps, {
externalFunctions,
externalFunctionGroups,
compositeFunctionCatalog,
});
} catch (err) {
throw new UserError(
ErrorCode.HOOKS_ERROR,
`Failed to parse hooks.${key}: ${err instanceof Error ? err.message : String(err)}. Hooks use the same syntax as workflow steps.`,
{ cause: err }
);
}
hookEntriesByKey[key] = entries;
for (const entry of entries) {
orderedSteps.push(...entry.steps);
}
}
+15 -7
View File
@@ -3,7 +3,6 @@ import {
BuildJob,
BuildPhase,
BuildTrigger,
HookAnchorId,
Ios,
Job,
Platform,
@@ -15,7 +14,7 @@ import nullthrows from 'nullthrows';
import path from 'path';
import { resolveEnvFromBuildProfileAsync, runEasBuildInternalAsync } from './easBuildInternal';
import { runHookableBuildPhaseAsync } from './hookableBuildPhase';
import { runHookEntriesAsync, runHookableBuildPhaseAsync } from './hookableBuildPhase';
import { installDependenciesAsync, resolvePackagerDir } from './installDependencies';
import { ParsedJobHooks, parseJobHooksAsync } from './jobHooks';
import { prepareProjectSourcesAsync } from './projectSources';
@@ -50,10 +49,7 @@ export interface JobHooksRef {
export async function setupAsync<TJob extends BuildJob>(
ctx: BuildContext<TJob>,
{
wrappedAnchors,
jobHooksRef,
}: { wrappedAnchors: readonly HookAnchorId[]; jobHooksRef: JobHooksRef }
{ jobHooksRef }: { jobHooksRef: JobHooksRef }
): Promise<void> {
await ctx.runBuildPhase(BuildPhase.PREPARE_PROJECT, async () => {
await retryAsync(
@@ -111,7 +107,19 @@ export async function setupAsync<TJob extends BuildJob>(
// Parse hooks unconditionally, after every pre-install env mutation
// (PREPARE_PROJECT, the git-based profile-env block, PRE_INSTALL_HOOK) and
// before the first wrapped phase.
jobHooksRef.current = await parseJobHooksAsync(ctx, wrappedAnchors);
jobHooksRef.current = await parseJobHooksAsync(ctx, [
'after_checkout',
'before_install_node_modules',
'after_install_node_modules',
]);
if (jobHooksRef.current) {
await runHookEntriesAsync({
ctx,
hooks: jobHooksRef.current,
timing: 'after',
anchor: 'checkout',
});
}
await runHookableBuildPhaseAsync({
ctx,
@@ -23,13 +23,19 @@ const WORKING_DIR = '/workingdir';
// BuildContext.getReactNativeProjectDirectory() nests the RN project under `${workingdir}/build`.
const IOS_DIR = path.join(WORKING_DIR, 'build', 'ios');
function makeIosBuildContext({ simulator }: { simulator: boolean }): BuildContext<Ios.Job> {
function makeIosBuildContext({
simulator,
env = {},
}: {
simulator: boolean;
env?: Record<string, string>;
}): BuildContext<Ios.Job> {
const job: Ios.Job = { ...createTestIosJob(), simulator };
return new BuildContext(job, {
workingdir: WORKING_DIR,
logger: createMockLogger(),
logBuffer: { getLogs: () => [], getPhaseLogs: () => [] },
env: { __API_SERVER_URL: 'http://api.expo.test' },
env: { __API_SERVER_URL: 'http://api.expo.test', ...env },
uploadArtifact: jest.fn(),
});
}
@@ -125,4 +131,25 @@ describe(runFastlaneGym, () => {
workspacePath: IOS_DIR,
});
});
it.each<{ name: string; env: Record<string, string>; expectedZipopt: string }>([
{ name: 'defaults ZIPOPT to -1', env: {}, expectedZipopt: '-1' },
{ name: 'keeps ZIPOPT from the build env', env: { ZIPOPT: '-9' }, expectedZipopt: '-9' },
])('$name', async ({ env, expectedZipopt }) => {
const ctx = makeIosBuildContext({ simulator: false, env });
await runFastlaneGym(ctx, {
scheme: 'App',
credentials: ARCHIVE_CREDENTIALS,
entitlements: null,
});
expect(spawn).toHaveBeenCalledWith(
'fastlane',
['gym'],
expect.objectContaining({
env: expect.objectContaining({ ZIPOPT: expectedZipopt }),
})
);
});
});
+1 -1
View File
@@ -84,7 +84,7 @@ async function updateVersionsAsync(
targetName,
buildConfiguration,
});
const infoPlist = xcBuildConfiguration.buildSettings.INFOPLIST_FILE;
const infoPlist = xcBuildConfiguration!.buildSettings.INFOPLIST_FILE;
if (infoPlist) {
const evaluatedInfoPlistPath = trimQuotes(
evaluateTemplateString(infoPlist, {
+2 -2
View File
@@ -10,7 +10,7 @@ import type { Credentials } from './credentials/manager';
import { createFastfileForResigningBuild } from './fastfile';
import { createGymfileForArchiveBuild, createGymfileForSimulatorBuild } from './gymfile';
import { isTVOS } from './tvos';
import { COMMON_FASTLANE_ENV } from '../common/fastlane';
import { COMMON_FASTLANE_ENV, DEFAULT_FASTLANE_GYM_ENV } from '../common/fastlane';
import { XcodeBuildLogger } from '../common/xcpretty';
import { BuildContext, SkipNativeBuildError } from '../context';
@@ -52,7 +52,7 @@ export async function runFastlaneGym<TJob extends Ios.Job>(
await runFastlane(['gym'], {
cwd: workspacePath,
logger: ctx.logger,
env: { ...ctx.env, ...extraEnv },
env: { ...DEFAULT_FASTLANE_GYM_ENV, ...ctx.env, ...extraEnv },
});
} finally {
await buildLogger.flush();
+1 -1
View File
@@ -28,5 +28,5 @@ export async function isTVOS(ctx: BuildContext<Ios.Job>): Promise<boolean> {
targetName,
buildConfiguration,
});
return xcBuildConfiguration?.buildSettings?.SDKROOT?.includes('appletv');
return xcBuildConfiguration?.buildSettings?.SDKROOT?.includes('appletv') ?? false;
}
@@ -62,9 +62,13 @@ import { createStartWebPreviewRemoteSessionBuildFunction } from './functions/sta
import { createStartServeSimMetricsBuildFunction } from './functions/startServeSimMetrics';
import { createStartServeSimLogsBuildFunction } from './functions/startServeSimLogs';
import { createCollectServeSimLogsBuildFunction } from './functions/collectServeSimLogs';
import { createStartServeSimNetworkCaptureBuildFunction } from './functions/startServeSimNetworkCapture';
import { createStartServeSimCrashesBuildFunction } from './functions/startServeSimCrashes';
import { createCollectServeSimCrashesBuildFunction } from './functions/collectServeSimCrashes';
import { createCollectAndroidEmulatorLogsBuildFunction } from './functions/collectAndroidEmulatorLogs';
import { createStartSandboxBuildFunction } from './functions/startSandbox';
import { createCollectServeSimMetricsBuildFunction } from './functions/collectServeSimMetrics';
import { createCollectServeSimNetworkCaptureBuildFunction } from './functions/collectServeSimNetworkCapture';
import { createUploadArtifactBuildFunction } from './functions/uploadArtifact';
import { createUploadDeviceRunSessionScreenRecordingsBuildFunction } from './functions/uploadDeviceRunSessionScreenRecordings';
import { createUploadEmbeddedBundleBuildFunction } from './functions/uploadEmbeddedBundle';
@@ -129,11 +133,15 @@ export function getEasFunctions(ctx: CustomBuildContext): BuildFunction[] {
createStartWebPreviewRemoteSessionBuildFunction(ctx, { warm: true }),
createStartServeSimMetricsBuildFunction(),
createStartServeSimLogsBuildFunction(),
createStartServeSimCrashesBuildFunction(),
createCollectServeSimCrashesBuildFunction(ctx),
createCollectServeSimLogsBuildFunction(ctx),
createCollectAndroidEmulatorLogsBuildFunction(ctx),
createStartSandboxBuildFunction(ctx),
createRunAgentBuildFunction(ctx),
createCollectServeSimMetricsBuildFunction(ctx),
createStartServeSimNetworkCaptureBuildFunction(),
createCollectServeSimNetworkCaptureBuildFunction(ctx),
createInstallMaestroBuildFunction(),
createInstallMitmproxyBuildFunction(),
@@ -0,0 +1,121 @@
import { type bunyan } from '@expo/logger';
import { type BuildStepContext, type BuildStepEnv } from '@expo/steps';
import { access, mkdir, mkdtemp, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { type CustomBuildContext } from '../../../customBuildContext';
import { Sentry } from '../../../sentry';
import { getDeviceRunSessionIdOrThrow } from '../../utils/remoteDeviceRunSession';
import { uploadServeSimCrashesFileAsync } from '../../utils/serveSimCrashesArtifacts';
import { ServeSimCrashesRecorder } from '../../utils/serveSimCrashesRecorder';
import { createCollectServeSimCrashesBuildFunction } from '../collectServeSimCrashes';
import { createStartServeSimCrashesBuildFunction } from '../startServeSimCrashes';
jest.mock('../../../sentry');
jest.mock('../../utils/serveSimCrashesRecorder');
jest.mock('../../utils/serveSimCrashesArtifacts');
jest.mock('../../utils/remoteDeviceRunSession');
const logger = { info: jest.fn(), warn: jest.fn() } as unknown as bunyan;
const ctx = {} as CustomBuildContext;
const step = { logger } as BuildStepContext;
const args = { inputs: {}, outputs: {}, env: {} as BuildStepEnv };
beforeEach(() => {
jest.mocked(getDeviceRunSessionIdOrThrow).mockReturnValue('session-id');
jest
.mocked(ServeSimCrashesRecorder.finishAsync)
.mockResolvedValue({ outputDirectory: null, crashes: [] });
});
it('starts collection and tolerates startup failures', async () => {
jest.mocked(ServeSimCrashesRecorder.startAsync).mockRejectedValueOnce(new Error('disk failure'));
await expect(createStartServeSimCrashesBuildFunction().fn?.(step, args)).resolves.toBeUndefined();
expect(logger.warn).toHaveBeenCalled();
expect(Sentry.capture).toHaveBeenCalledWith(
'Could not start serve-sim simulator crashes',
expect.any(Error)
);
});
it('uploads each report and removes the collection directory', async () => {
const directory = '/tmp/crashes-collected';
await mkdir(directory, { recursive: true });
await writeFile(`${directory}/A.ips`, 'private crash report');
jest.mocked(ServeSimCrashesRecorder.finishAsync).mockResolvedValue({
outputDirectory: directory,
crashes: [
{ udid: 'A', filePath: `${directory}/A.ips`, size: 20, number: 1 },
{ udid: 'B', filePath: `${directory}/B.ips`, size: 20, number: 1 },
],
});
await createCollectServeSimCrashesBuildFunction(ctx).fn?.(step, args);
expect(uploadServeSimCrashesFileAsync).toHaveBeenCalledTimes(2);
expect(uploadServeSimCrashesFileAsync).toHaveBeenCalledWith(ctx, {
deviceRunSessionId: 'session-id',
crash: { udid: 'A', filePath: `${directory}/A.ips`, size: 20, number: 1 },
logger,
signal: expect.any(AbortSignal),
});
await expect(access(directory)).rejects.toMatchObject({ code: 'ENOENT' });
});
it('skips empty collection and warns on finalization failure', async () => {
await createCollectServeSimCrashesBuildFunction(ctx).fn?.(step, args);
expect(uploadServeSimCrashesFileAsync).not.toHaveBeenCalled();
jest.mocked(ServeSimCrashesRecorder.finishAsync).mockRejectedValueOnce(new Error('failure'));
await expect(
createCollectServeSimCrashesBuildFunction(ctx).fn?.(step, args)
).resolves.toBeUndefined();
expect(logger.warn).toHaveBeenCalled();
expect(Sentry.capture).toHaveBeenCalledWith(
'Could not finalize serve-sim simulator crashes',
expect.any(Error)
);
});
it.each([
['no crashes were recorded', [], false],
['session resolution fails', [{ udid: 'A', filePath: 'A.ips', size: 20, number: 1 }], true],
])('removes the collection directory when %s', async (_name, crashes, failSession) => {
const outputDirectory = await mkdtemp(path.join(os.tmpdir(), 'crashes-collected-'));
jest.mocked(ServeSimCrashesRecorder.finishAsync).mockResolvedValue({ outputDirectory, crashes });
if (failSession) {
jest.mocked(getDeviceRunSessionIdOrThrow).mockImplementationOnce(() => {
throw new Error('Missing session ID');
});
}
await expect(
createCollectServeSimCrashesBuildFunction(ctx).fn?.(step, args)
).resolves.toBeUndefined();
await expect(access(outputDirectory)).rejects.toMatchObject({ code: 'ENOENT' });
expect(uploadServeSimCrashesFileAsync).not.toHaveBeenCalled();
});
it('skips remaining reports for an exhausted device and continues with other devices', async () => {
jest.mocked(ServeSimCrashesRecorder.finishAsync).mockResolvedValue({
outputDirectory: null,
crashes: [
{ udid: 'A', filePath: '/tmp/A-1.ips', size: 20, number: 1 },
{ udid: 'A', filePath: '/tmp/A-2.ips', size: 20, number: 2 },
{ udid: 'B', filePath: '/tmp/B-1.ips', size: 20, number: 1 },
],
});
const controller = new AbortController();
const timeout = jest.spyOn(AbortSignal, 'timeout').mockReturnValueOnce(controller.signal);
jest.mocked(uploadServeSimCrashesFileAsync).mockImplementationOnce(async () => {
controller.abort(new Error('Upload budget exhausted'));
});
try {
await createCollectServeSimCrashesBuildFunction(ctx).fn?.(step, args);
expect(
jest.mocked(uploadServeSimCrashesFileAsync).mock.calls.map(([, { crash }]) => crash.filePath)
).toEqual(['/tmp/A-1.ips', '/tmp/B-1.ips']);
expect(logger.warn).toHaveBeenCalledWith(
'Simulator crash upload reached its time limit for A; remaining reports will not be uploaded.'
);
} finally {
timeout.mockRestore();
}
});
@@ -0,0 +1,104 @@
import { bunyan } from '@expo/logger';
import { type BuildStepEnv } from '@expo/steps';
import { access, mkdtemp } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { type CustomBuildContext } from '../../../customBuildContext';
import { uploadServeSimNetworkCaptureFileAsync } from '../../utils/serveSimNetworkCaptureArtifacts';
import { ServeSimNetworkCaptureRecorder } from '../../utils/serveSimNetworkCaptureRecorder';
import { createCollectServeSimNetworkCaptureBuildFunction } from '../collectServeSimNetworkCapture';
import { createStartServeSimNetworkCaptureBuildFunction } from '../startServeSimNetworkCapture';
jest.mock('../../../sentry');
jest.mock('../../utils/serveSimNetworkCaptureArtifacts');
jest.mock('../../utils/serveSimNetworkCaptureRecorder');
const ctx = {} as CustomBuildContext;
const logger = {
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
debug: jest.fn(),
} as unknown as bunyan;
type Fn = (stepCtx: unknown, options: unknown) => Promise<void>;
function runFn(
fn: unknown,
options: { env: BuildStepEnv; inputs?: Record<string, { value: unknown }> }
): Promise<void> {
return (fn as Fn)({ logger }, { inputs: {}, ...options });
}
beforeEach(() => {
jest.clearAllMocks();
});
it('starts the recorder with the session package version and never fails the step', async () => {
const buildFunction = createStartServeSimNetworkCaptureBuildFunction();
expect(buildFunction.id).toBe('start_serve_sim_network_capture');
const { fn } = buildFunction as unknown as { fn: Fn };
const env = {} as BuildStepEnv;
await runFn(fn, { env, inputs: { package_version: { value: '0.5.0' } } });
expect(ServeSimNetworkCaptureRecorder.startAsync).toHaveBeenCalledWith({
logger,
env,
packageVersion: '0.5.0',
});
jest.mocked(ServeSimNetworkCaptureRecorder.startAsync).mockRejectedValueOnce(new Error('ENOSPC'));
await expect(
runFn(fn, { env, inputs: { package_version: { value: undefined } } })
).resolves.toBeUndefined();
expect(logger.warn).toHaveBeenCalledWith(
{ err: expect.objectContaining({ message: 'ENOSPC' }) },
'Could not start the serve-sim network capture recorder.'
);
});
it('uploads each recorded HAR as a numbered part per device, then removes the directory', async () => {
const outputDirectory = await mkdtemp(path.join(os.tmpdir(), 'serve-sim-network-capture-'));
const captures = [
{ udid: 'SIM-A', filePath: path.join(outputDirectory, 'SIM-A-1.har'), size: 24 },
{ udid: 'SIM-B', filePath: path.join(outputDirectory, 'SIM-B-1.har'), size: 25 },
{ udid: 'SIM-A', filePath: path.join(outputDirectory, 'SIM-A-3.har'), size: 26 },
];
jest
.mocked(ServeSimNetworkCaptureRecorder.finishAsync)
.mockResolvedValueOnce({ outputDirectory, captures });
const { fn } = createCollectServeSimNetworkCaptureBuildFunction(ctx) as unknown as { fn: Fn };
await runFn(fn, { env: { DEVICE_RUN_SESSION_ID: 'drs-id' } as BuildStepEnv });
const signal = expect.any(AbortSignal);
expect(jest.mocked(uploadServeSimNetworkCaptureFileAsync).mock.calls).toEqual([
[ctx, { deviceRunSessionId: 'drs-id', ...captures[0], part: 1, logger, signal }],
[ctx, { deviceRunSessionId: 'drs-id', ...captures[1], part: 1, logger, signal }],
[ctx, { deviceRunSessionId: 'drs-id', ...captures[2], part: 2, logger, signal }],
]);
await expect(access(outputDirectory)).rejects.toThrow();
});
it('does not fail the step without a device run session, and still removes the directory', async () => {
const outputDirectory = await mkdtemp(path.join(os.tmpdir(), 'serve-sim-network-capture-'));
jest.mocked(ServeSimNetworkCaptureRecorder.finishAsync).mockResolvedValueOnce({
outputDirectory,
captures: [{ udid: 'SIM-A', filePath: path.join(outputDirectory, 'SIM-A-1.har'), size: 24 }],
});
const { fn } = createCollectServeSimNetworkCaptureBuildFunction(ctx) as unknown as { fn: Fn };
await expect(runFn(fn, { env: {} as BuildStepEnv })).resolves.toBeUndefined();
expect(uploadServeSimNetworkCaptureFileAsync).not.toHaveBeenCalled();
expect(logger.warn).toHaveBeenCalledWith(
{ err: expect.any(Error) },
'Could not upload the network capture.'
);
await expect(access(outputDirectory)).rejects.toThrow();
});
it('skips the upload when nothing was recorded', async () => {
jest
.mocked(ServeSimNetworkCaptureRecorder.finishAsync)
.mockResolvedValueOnce({ outputDirectory: null, captures: [] });
const { fn } = createCollectServeSimNetworkCaptureBuildFunction(ctx) as unknown as { fn: Fn };
await runFn(fn, { env: { DEVICE_RUN_SESSION_ID: 'drs-id' } as BuildStepEnv });
expect(uploadServeSimNetworkCaptureFileAsync).not.toHaveBeenCalled();
expect(logger.info).toHaveBeenCalledWith('No network capture was recorded; skipping upload.');
});
@@ -216,6 +216,36 @@ describe('runAgentDeviceRemoteSessionAsync orchestration', () => {
);
});
it.each([
[
BuildRuntimePlatform.DARWIN,
{
iosSimulatorUdid: 'selected-udid',
application: Promise.resolve({
installAppPath: '/tmp/App.app',
launchAppIdentifier: 'com.example.archive',
}),
},
],
[
BuildRuntimePlatform.LINUX,
{ booted: Promise.resolve(), ready: Promise.resolve('com.example.archive') },
],
])(
'reports the identifier of the app the %s device launched',
async (runtimePlatform, device) => {
const logger = { info: jest.fn(), warn: jest.fn(), child: jest.fn().mockReturnThis() };
await runAsync(logger, runtimePlatform, { device });
expect(uploadRemoteSessionConfigAsync).toHaveBeenCalledWith(
expect.objectContaining({
remoteConfig: expect.objectContaining({ applicationIdentifier: 'com.example.archive' }),
})
);
}
);
it('uses the warm daemon after adoption and starts no daemon of its own', async () => {
const logger = { info: jest.fn(), warn: jest.fn(), child: jest.fn().mockReturnThis() };
const warmServer = { port: 3200 } as never;
@@ -517,6 +517,10 @@ describe(createStartAgentDeviceSessionBuildFunction, () => {
expect(launchApplicationAsync).toHaveBeenCalledWith(
expect.objectContaining({ applicationIdentifier: 'dev.example.app', activityName: '.Main' })
);
// The remote session reports it so clients can attach to an archive session's app.
await expect((sessionDevice() as { ready: Promise<unknown> }).ready).resolves.toBe(
'dev.example.app'
);
});
it('stops the download and waits for it when Android boot fails', async () => {
@@ -0,0 +1,62 @@
import { BuildFunction, BuildRuntimePlatform } from '@expo/steps';
import { rm } from 'node:fs/promises';
import { type CustomBuildContext } from '../../customBuildContext';
import { Sentry } from '../../sentry';
import { getDeviceRunSessionIdOrThrow } from '../utils/remoteDeviceRunSession';
import { uploadServeSimCrashesFileAsync } from '../utils/serveSimCrashesArtifacts';
import { ServeSimCrashesRecorder } from '../utils/serveSimCrashesRecorder';
const UPLOAD_TIMEOUT_MS = 30_000;
export function createCollectServeSimCrashesBuildFunction(ctx: CustomBuildContext): BuildFunction {
return new BuildFunction({
namespace: 'eas',
id: 'collect_serve_sim_crashes',
name: 'Collect serve-sim simulator crashes',
__metricsId: 'eas/collect_serve_sim_crashes',
supportedRuntimePlatforms: [BuildRuntimePlatform.DARWIN],
fn: async ({ logger }, { env }) => {
let outputDirectory: string | null = null;
try {
const collected = await ServeSimCrashesRecorder.finishAsync();
outputDirectory = collected.outputDirectory;
if (collected.crashes.length === 0) {
logger.info('No simulator crashes collected; skipping upload.');
return;
}
const deviceRunSessionId = getDeviceRunSessionIdOrThrow(env);
for (const udid of new Set(collected.crashes.map(crash => crash.udid))) {
const signal = AbortSignal.timeout(UPLOAD_TIMEOUT_MS);
for (const crash of collected.crashes.filter(crash => crash.udid === udid)) {
if (signal.aborted) {
logger.warn(
`Simulator crash upload reached its time limit for ${udid}; remaining reports will not be uploaded.`
);
break;
}
await uploadServeSimCrashesFileAsync(ctx, {
deviceRunSessionId,
crash,
logger,
signal,
});
}
}
} catch (err) {
const error = err instanceof Error ? err : new Error(String(err));
Sentry.capture('Could not finalize serve-sim simulator crashes', error);
logger.warn(
{ err: error },
'Could not finalize simulator crashes; the session result is unchanged.'
);
} finally {
if (outputDirectory) {
await rm(outputDirectory, { recursive: true, force: true }).catch(err => {
logger.warn({ err }, 'Could not remove the simulator crash directory.');
});
}
}
},
});
}
@@ -0,0 +1,63 @@
import { BuildFunction, BuildRuntimePlatform } from '@expo/steps';
import { rm } from 'node:fs/promises';
import { type CustomBuildContext } from '../../customBuildContext';
import { Sentry } from '../../sentry';
import { getDeviceRunSessionIdOrThrow } from '../utils/remoteDeviceRunSession';
import { uploadServeSimNetworkCaptureFileAsync } from '../utils/serveSimNetworkCaptureArtifacts';
import { ServeSimNetworkCaptureRecorder } from '../utils/serveSimNetworkCaptureRecorder';
// Each HAR may be up to 500 MiB, so one slow upload gets its own long limit.
const UPLOAD_TIMEOUT_MS = 10 * 60 * 1000;
export function createCollectServeSimNetworkCaptureBuildFunction(
ctx: CustomBuildContext
): BuildFunction {
return new BuildFunction({
namespace: 'eas',
id: 'collect_serve_sim_network_capture',
name: 'Collect serve-sim network capture',
__metricsId: 'eas/collect_serve_sim_network_capture',
supportedRuntimePlatforms: [BuildRuntimePlatform.DARWIN],
fn: async ({ logger }, { env }) => {
const { outputDirectory, captures } = await ServeSimNetworkCaptureRecorder.finishAsync({
logger,
});
try {
if (captures.length === 0) {
logger.info('No network capture was recorded; skipping upload.');
return;
}
const deviceRunSessionId = getDeviceRunSessionIdOrThrow(env);
// A device's HARs are numbered parts, one per capture har run that recorded requests.
const parts = new Map<string, number>();
for (const { udid, filePath, size } of captures) {
const part = (parts.get(udid) ?? 0) + 1;
parts.set(udid, part);
await uploadServeSimNetworkCaptureFileAsync(ctx, {
deviceRunSessionId,
udid,
filePath,
size,
part,
logger,
signal: AbortSignal.timeout(UPLOAD_TIMEOUT_MS),
});
}
} catch (err) {
const error = err instanceof Error ? err : new Error(String(err));
Sentry.capture('Could not upload the network capture', error);
logger.warn({ err: error }, 'Could not upload the network capture.');
} finally {
if (outputDirectory) {
await rm(outputDirectory, { recursive: true, force: true }).catch(err => {
logger.warn(
{ err },
`Could not remove the network capture directory ${outputDirectory}.`
);
});
}
}
},
});
}
@@ -1,4 +1,4 @@
import { BuildFunction } from '@expo/steps';
import { BuildFunction, BuildStepContext, BuildStepEnv } from '@expo/steps';
import spawn from '@expo/turtle-spawn';
export function createInstallPodsBuildFunction(): BuildFunction {
@@ -8,29 +8,36 @@ export function createInstallPodsBuildFunction(): BuildFunction {
name: 'Install Pods',
__metricsId: 'eas/install_pods',
fn: async (stepsCtx, { env }) => {
stepsCtx.logger.info('Installing pods');
const verboseFlag = stepsCtx.global.env['EAS_VERBOSE'] === '1' ? ['--verbose'] : [];
const cocoapodsDeploymentFlag =
stepsCtx.global.env['POD_INSTALL_DEPLOYMENT'] === '1' ? ['--deployment'] : [];
await runPodInstallAsync(stepsCtx, env);
},
});
}
await spawn('pod', ['install', ...verboseFlag, ...cocoapodsDeploymentFlag], {
logger: stepsCtx.logger,
env: {
...env,
LANG: 'en_US.UTF-8',
},
cwd: stepsCtx.workingDirectory,
lineTransformer: (line?: string) => {
if (
!line ||
/\[!\] '[\w-]+' uses the unencrypted 'http' protocol to transfer the Pod\./.exec(line)
) {
return null;
} else {
return line;
}
},
});
export async function runPodInstallAsync(
stepsCtx: BuildStepContext,
env: BuildStepEnv
): Promise<void> {
stepsCtx.logger.info('Installing pods');
const verboseFlag = stepsCtx.global.env['EAS_VERBOSE'] === '1' ? ['--verbose'] : [];
const cocoapodsDeploymentFlag =
stepsCtx.global.env['POD_INSTALL_DEPLOYMENT'] === '1' ? ['--deployment'] : [];
await spawn('pod', ['install', ...verboseFlag, ...cocoapodsDeploymentFlag], {
logger: stepsCtx.logger,
env: {
...env,
LANG: 'en_US.UTF-8',
},
cwd: stepsCtx.workingDirectory,
lineTransformer: (line?: string) => {
if (
!line ||
/\[!\] '[\w-]+' uses the unencrypted 'http' protocol to transfer the Pod\./.exec(line)
) {
return null;
} else {
return line;
}
},
});
}
@@ -0,0 +1,288 @@
import spawn from '@expo/turtle-spawn';
import { vol } from 'memfs';
import path from 'path';
import { createGlobalContextMock } from '../../../../../__tests__/utils/context';
import { createDetectNativeXcodeBuildFunction } from '../detectNativeXcode';
jest.mock('@expo/turtle-spawn', () => ({ __esModule: true, default: jest.fn() }));
const originalFs = jest.requireActual('fs');
const projectDirectory = '/project';
const fixturesDirectory = path.join(
__dirname,
'../../../../utils/ios/xcodeProject/__tests__/fixtures'
);
const FRAMEWORK_ONLY_SCHEME = `<?xml version="1.0" encoding="UTF-8"?>
<Scheme version = "1.3">
<BuildAction>
<BuildActionEntries>
<BuildActionEntry buildForArchiving = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "BBCC7F97904CEBE3743A2D6F"
BuildableName = "Core.framework"
BlueprintName = "Core"
ReferencedContainer = "container:NativeApp.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<LaunchAction buildConfiguration = "Debug"></LaunchAction>
<ArchiveAction buildConfiguration = "Release"></ArchiveAction>
</Scheme>`;
function writeProject(extraFiles: Record<string, string> = {}): void {
vol.fromJSON(
{
'NativeApp.xcodeproj/project.pbxproj': originalFs.readFileSync(
path.join(fixturesDirectory, 'native-app.pbxproj'),
'utf-8'
),
'NativeApp.xcodeproj/xcshareddata/xcschemes/NativeApp.xcscheme': originalFs.readFileSync(
path.join(fixturesDirectory, 'native-app.xcscheme'),
'utf-8'
),
...extraFiles,
},
projectDirectory
);
}
const APPLICATION_BUILD_SETTINGS = {
PLATFORM_NAME: 'iphoneos',
PRODUCT_BUNDLE_IDENTIFIER: 'dev.expo.nativeapp',
PROVISIONING_PROFILE_REQUIRED: 'YES',
};
const WIDGET_BUILD_SETTINGS = {
PLATFORM_NAME: 'iphoneos',
PRODUCT_BUNDLE_IDENTIFIER: 'dev.expo.nativeapp.widget',
PROVISIONING_PROFILE_REQUIRED: 'YES',
};
const BUILD_SETTINGS_BY_TARGET_NAME = {
NativeApp: APPLICATION_BUILD_SETTINGS,
Widget: WIDGET_BUILD_SETTINGS,
Core: { PLATFORM_NAME: 'iphoneos', PRODUCT_BUNDLE_IDENTIFIER: 'dev.expo.nativeapp.core' },
Support: { PLATFORM_NAME: 'iphoneos' },
};
function mockBuildSettings(
...buildSettingsByTargetNameOfEachCall: Record<string, Record<string, string>>[]
): void {
for (const buildSettingsByTargetName of buildSettingsByTargetNameOfEachCall) {
jest.mocked(spawn).mockResolvedValueOnce({
stdout: JSON.stringify(
Object.entries(buildSettingsByTargetName).map(([target, buildSettings]) => ({
action: 'build',
target,
buildSettings,
}))
),
} as any);
}
}
function createDetectStep({
job,
callInputs = {},
}: {
job: Record<string, unknown>;
callInputs?: Record<string, unknown>;
}): ReturnType<
ReturnType<typeof createDetectNativeXcodeBuildFunction>['createBuildStepFromFunctionCall']
> {
const globalCtx = createGlobalContextMock({
projectTargetDirectory: projectDirectory,
staticContextContent: { job },
});
return createDetectNativeXcodeBuildFunction().createBuildStepFromFunctionCall(globalCtx, {
callInputs,
});
}
const signedJob = { simulator: false };
afterEach(() => {
vol.reset();
jest.mocked(spawn).mockReset();
});
describe(createDetectNativeXcodeBuildFunction, () => {
it('detects the project, the scheme, the archive configuration and the targets that need a provisioning profile', async () => {
writeProject();
mockBuildSettings(BUILD_SETTINGS_BY_TARGET_NAME);
const step = createDetectStep({
job: signedJob,
callInputs: { expected_identifier: 'dev.expo.nativeapp' },
});
await step.executeAsync();
expect(step.outputById.project_file.value).toBe('/project/NativeApp.xcodeproj');
expect(step.outputById.scheme.value).toBe('NativeApp');
expect(step.outputById.build_configuration.value).toBe('Release');
expect(step.outputById.xcodeproj_path.value).toBe('/project/NativeApp.xcodeproj');
expect(JSON.parse(step.outputById.targets.value as string)).toEqual([
{ id: '2870BA69F546F142D461562E', name: 'NativeApp', bundleIdentifier: 'dev.expo.nativeapp' },
{
id: '5CAE5500641C3F327B201839',
name: 'Widget',
bundleIdentifier: 'dev.expo.nativeapp.widget',
},
]);
expect(spawn).toHaveBeenCalledWith(
'xcodebuild',
[
'-project',
'/project/NativeApp.xcodeproj',
'-target',
'NativeApp',
'-target',
'Widget',
'-target',
'Core',
'-target',
'Support',
'-configuration',
'Release',
'-showBuildSettings',
'-json',
],
expect.anything()
);
expect(spawn).toHaveBeenCalledTimes(1);
});
it('reads the settings again with the iOS SDK for the targets that Xcode resolved no platform for', async () => {
writeProject();
mockBuildSettings(
{
...BUILD_SETTINGS_BY_TARGET_NAME,
Widget: { PRODUCT_BUNDLE_IDENTIFIER: 'dev.expo.nativeapp.widget' },
Support: {},
},
{ Widget: WIDGET_BUILD_SETTINGS, Support: { PLATFORM_NAME: 'iphoneos' } }
);
const step = createDetectStep({ job: signedJob });
await step.executeAsync();
expect(JSON.parse(step.outputById.targets.value as string)).toEqual([
{ id: '2870BA69F546F142D461562E', name: 'NativeApp', bundleIdentifier: 'dev.expo.nativeapp' },
{
id: '5CAE5500641C3F327B201839',
name: 'Widget',
bundleIdentifier: 'dev.expo.nativeapp.widget',
},
]);
expect(spawn).toHaveBeenCalledTimes(2);
expect(jest.mocked(spawn).mock.calls[1][1]).toEqual([
'-project',
'/project/NativeApp.xcodeproj',
'-target',
'Widget',
'-target',
'Support',
'-configuration',
'Release',
'-sdk',
'iphoneos',
'-showBuildSettings',
'-json',
]);
});
it('uses the Run configuration, the simulator SDK and only the application target for a simulator build', async () => {
writeProject();
mockBuildSettings({ NativeApp: APPLICATION_BUILD_SETTINGS });
const step = createDetectStep({ job: { simulator: true } });
await step.executeAsync();
expect(step.outputById.build_configuration.value).toBe('Debug');
expect(JSON.parse(step.outputById.targets.value as string)).toEqual([
{ id: '2870BA69F546F142D461562E', name: 'NativeApp', bundleIdentifier: 'dev.expo.nativeapp' },
]);
expect(jest.mocked(spawn).mock.calls[0][1]).toEqual(
expect.arrayContaining([
'-target',
'NativeApp',
'-configuration',
'Debug',
'-sdk',
'iphonesimulator',
])
);
expect(jest.mocked(spawn).mock.calls[0][1]).not.toContain('Widget');
});
it('uses the given build configuration', async () => {
writeProject();
mockBuildSettings(BUILD_SETTINGS_BY_TARGET_NAME);
const step = createDetectStep({
job: signedJob,
callInputs: { build_configuration: 'Debug' },
});
await step.executeAsync();
expect(step.outputById.build_configuration.value).toBe('Debug');
});
it('fails with the build configurations of the target when the given one does not exist', async () => {
writeProject();
const step = createDetectStep({
job: signedJob,
callInputs: { build_configuration: 'Staging' },
});
await expect(step.executeAsync()).rejects.toMatchObject({
errorCode: 'NATIVE_XCODE_BUILD_CONFIGURATION_NOT_FOUND',
message: expect.stringContaining(
'"Staging". Build configurations of the target: Debug, Release.'
),
});
expect(spawn).not.toHaveBeenCalled();
});
it('fails when the bundle identifier differs from the expected identifier', async () => {
writeProject();
mockBuildSettings(BUILD_SETTINGS_BY_TARGET_NAME);
const step = createDetectStep({
job: signedJob,
callInputs: { expected_identifier: 'dev.expo.other' },
});
await expect(step.executeAsync()).rejects.toMatchObject({
errorCode: 'NATIVE_XCODE_APP_IDENTIFIER_MISMATCH',
message: expect.stringMatching(/"dev\.expo\.other".*"NativeApp".*"dev\.expo\.nativeapp"/),
});
});
it('fails when a target that needs a provisioning profile has no bundle identifier', async () => {
writeProject();
mockBuildSettings({
...BUILD_SETTINGS_BY_TARGET_NAME,
Widget: { PLATFORM_NAME: 'iphoneos', PROVISIONING_PROFILE_REQUIRED: 'YES' },
});
const step = createDetectStep({ job: signedJob });
await expect(step.executeAsync()).rejects.toMatchObject({
errorCode: 'NATIVE_XCODE_NO_BUNDLE_IDENTIFIER',
message: expect.stringContaining('The target "Widget" has no bundle identifier'),
});
});
it('fails with the other schemes when the scheme builds no application', async () => {
writeProject({
'NativeApp.xcodeproj/xcshareddata/xcschemes/Core.xcscheme': FRAMEWORK_ONLY_SCHEME,
});
const step = createDetectStep({ job: signedJob, callInputs: { scheme: 'Core' } });
await expect(step.executeAsync()).rejects.toMatchObject({
errorCode: 'NATIVE_XCODE_NO_APPLICATION_TARGET',
message: expect.stringMatching(/scheme "Core".*Other shared schemes: NativeApp\./),
});
});
});
@@ -0,0 +1,43 @@
import spawn from '@expo/turtle-spawn';
import { vol } from 'memfs';
import { createGlobalContextMock } from '../../../../../__tests__/utils/context';
import { createInstallNativePodsBuildFunction } from '../installNativePods';
jest.mock('@expo/turtle-spawn', () => ({ __esModule: true, default: jest.fn() }));
const projectDirectory = '/project';
async function runInstallNativePodsAsync(): Promise<void> {
const globalCtx = createGlobalContextMock({ projectTargetDirectory: projectDirectory });
await createInstallNativePodsBuildFunction()
.createBuildStepFromFunctionCall(globalCtx)
.executeAsync();
}
afterEach(() => {
vol.reset();
});
describe(createInstallNativePodsBuildFunction, () => {
it('runs pod install in the project directory when it has a Podfile', async () => {
vol.fromJSON({ Podfile: '', 'App.xcodeproj/project.pbxproj': '' }, projectDirectory);
await runInstallNativePodsAsync();
expect(spawn).toHaveBeenCalledTimes(1);
expect(spawn).toHaveBeenCalledWith(
'pod',
['install'],
expect.objectContaining({ cwd: projectDirectory })
);
});
it('does nothing when the project directory has no Podfile', async () => {
vol.fromJSON({ 'App.xcodeproj/project.pbxproj': '', 'ios/Podfile': '' }, projectDirectory);
await runInstallNativePodsAsync();
expect(spawn).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,176 @@
import { IOSConfig } from '@expo/config-plugins';
import { Ios, UserError } from '@expo/eas-build-job';
import {
BuildFunction,
BuildStepInput,
BuildStepInputValueTypeName,
BuildStepOutput,
} from '@expo/steps';
import path from 'node:path';
import { XcodeProject } from 'xcode';
import { readBuildSettingsByTargetNameAsync } from '../../../utils/ios/xcodeProject/buildSettings';
import {
XcodeTarget,
XcodeTargetWithBundleIdentifier,
findApplicationTargetById,
findDependencyTargets,
getBuildConfigurations,
openXcodeProject,
} from '../../../utils/ios/xcodeProject/pbxproj';
import { resolveProjectFilePathAsync } from '../../../utils/ios/xcodeProject/projectFile';
import {
XcodeSchemeDetails,
findSharedSchemesAsync,
readSchemeAsync,
selectScheme,
} from '../../../utils/ios/xcodeProject/schemes';
export function createDetectNativeXcodeBuildFunction(): BuildFunction {
return new BuildFunction({
namespace: 'eas',
id: 'detect_native_xcode',
name: 'Detect Xcode project',
__metricsId: 'eas/detect_native_xcode',
inputProviders: [
BuildStepInput.createProvider({
id: 'project_file',
required: false,
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
}),
BuildStepInput.createProvider({
id: 'scheme',
required: false,
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
}),
BuildStepInput.createProvider({
id: 'build_configuration',
required: false,
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
}),
BuildStepInput.createProvider({
id: 'expected_identifier',
required: false,
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
}),
],
outputProviders: [
BuildStepOutput.createProvider({ id: 'project_file', required: true }),
BuildStepOutput.createProvider({ id: 'scheme', required: true }),
BuildStepOutput.createProvider({ id: 'build_configuration', required: true }),
BuildStepOutput.createProvider({ id: 'xcodeproj_path', required: true }),
BuildStepOutput.createProvider({ id: 'targets', required: true }),
],
fn: async (stepsCtx, { inputs, outputs, env }) => {
const { logger, workingDirectory } = stepsCtx;
const job = stepsCtx.global.staticContext.job as Ios.Job;
const needsSigning = !job.simulator;
const projectFilePath = await resolveProjectFilePathAsync(
workingDirectory,
inputs.project_file.value as string | undefined
);
const schemes = await findSharedSchemesAsync(projectFilePath);
const scheme = selectScheme(schemes, {
requestedName: inputs.scheme.value as string | undefined,
logger,
});
const { applicationTargetReference, archiveConfiguration, launchConfiguration } =
await readSchemeAsync(scheme);
const application = openApplicationTarget(applicationTargetReference);
if (!application) {
const otherSchemeNames = schemes
.map(({ name }) => name)
.filter(name => name !== scheme.name);
throw new UserError(
'NATIVE_XCODE_NO_APPLICATION_TARGET',
`The scheme "${scheme.name}" does not build an iOS application target, so EAS has no app to sign and upload. ${
otherSchemeNames.length > 0
? `Other shared schemes: ${otherSchemeNames.sort().join(', ')}. Set "xcode_scheme" to the scheme of the app.`
: 'Share the scheme of the app in Xcode (Product > Scheme > Manage Schemes) and commit its ".xcscheme" file.'
}`
);
}
const { project, xcodeprojPath, target: applicationTarget } = application;
const buildConfiguration =
(inputs.build_configuration.value as string | undefined) ??
(needsSigning ? archiveConfiguration : launchConfiguration);
const buildConfigurationNames = getBuildConfigurations(project, applicationTarget.id).map(
({ name }) => IOSConfig.XcodeUtils.unquote(name)
);
if (!buildConfiguration || !buildConfigurationNames.includes(buildConfiguration)) {
throw new UserError(
'NATIVE_XCODE_BUILD_CONFIGURATION_NOT_FOUND',
`${
buildConfiguration
? `The target "${applicationTarget.name}" has no build configuration named "${buildConfiguration}".`
: `The scheme "${scheme.name}" names no build configuration for its ${needsSigning ? 'Archive' : 'Run'} action.`
} Build configurations of the target: ${buildConfigurationNames.join(', ')}. Set "xcode_configuration" to one of them.`
);
}
const dependencyTargets = needsSigning
? findDependencyTargets(project, applicationTarget.id)
: [];
const buildSettingsByTargetName = await readBuildSettingsByTargetNameAsync({
xcodeprojPath,
targetNames: [applicationTarget, ...dependencyTargets].map(({ name }) => name),
buildConfiguration,
sdk: job.simulator ? 'iphonesimulator' : undefined,
env,
logger,
});
const targets: XcodeTargetWithBundleIdentifier[] = [
applicationTarget,
// Xcode sets this on products that need a provisioning profile (DarwinProductTypes.xcspec).
...dependencyTargets.filter(
({ name }) => buildSettingsByTargetName[name]?.PROVISIONING_PROFILE_REQUIRED === 'YES'
),
].map(target => {
const bundleIdentifier = buildSettingsByTargetName[target.name]?.PRODUCT_BUNDLE_IDENTIFIER;
if (!bundleIdentifier) {
throw new UserError(
'NATIVE_XCODE_NO_BUNDLE_IDENTIFIER',
`The target "${target.name}" has no bundle identifier in the build configuration "${buildConfiguration}". EAS finds the built app and picks the signing credentials by bundle identifier, for the application target and for every target it depends on that needs a provisioning profile. Set PRODUCT_BUNDLE_IDENTIFIER for this target in Xcode.`
);
}
return { ...target, bundleIdentifier };
});
const expectedIdentifier = inputs.expected_identifier.value as string | undefined;
const [{ bundleIdentifier: applicationIdentifier }] = targets;
if (expectedIdentifier && applicationIdentifier !== expectedIdentifier) {
throw new UserError(
'NATIVE_XCODE_APP_IDENTIFIER_MISMATCH',
`"app_identifier" is "${expectedIdentifier}", but the target "${applicationTarget.name}" has the bundle identifier "${applicationIdentifier}" in the build configuration "${buildConfiguration}". Set "app_identifier" to "${applicationIdentifier}", or set "xcode_scheme" and "xcode_configuration" to the ones that build "${expectedIdentifier}".`
);
}
logger.info(
`Building the scheme "${scheme.name}" of "${path.basename(projectFilePath)}" with the build configuration "${buildConfiguration}".`
);
for (const { name, bundleIdentifier } of targets) {
logger.info(`Target "${name}": ${bundleIdentifier}`);
}
outputs.project_file.set(projectFilePath);
outputs.scheme.set(scheme.name);
outputs.build_configuration.set(buildConfiguration);
outputs.xcodeproj_path.set(xcodeprojPath);
outputs.targets.set(JSON.stringify(targets));
},
});
}
function openApplicationTarget(
reference: XcodeSchemeDetails['applicationTargetReference']
): { project: XcodeProject; xcodeprojPath: string; target: XcodeTarget } | undefined {
if (!reference) {
return undefined;
}
const project = openXcodeProject(reference.xcodeprojPath);
const target = findApplicationTargetById(project, reference.targetId);
return target && { project, xcodeprojPath: reference.xcodeprojPath, target };
}
@@ -0,0 +1,21 @@
import { BuildFunction } from '@expo/steps';
import fs from 'node:fs';
import path from 'node:path';
import { runPodInstallAsync } from '../../installPods';
export function createInstallNativePodsBuildFunction(): BuildFunction {
return new BuildFunction({
namespace: 'eas',
id: 'install_native_pods',
name: 'Install Pods',
__metricsId: 'eas/install_native_pods',
fn: async (stepsCtx, { env }) => {
if (!fs.existsSync(path.join(stepsCtx.workingDirectory, 'Podfile'))) {
stepsCtx.logger.info('The project directory has no Podfile. Skipping "pod install".');
return;
}
await runPodInstallAsync(stepsCtx, env);
},
});
}
@@ -126,7 +126,8 @@ export async function runAgentDeviceRemoteSessionAsync(
device:
| {
booted: Promise<unknown>;
ready: Promise<unknown>;
/** Resolves with the identifier of the app it installed, if any. */
ready: Promise<string | void>;
}
| {
iosSimulatorUdid: string;
@@ -244,6 +245,7 @@ export async function runAgentDeviceRemoteSessionAsync(
const [
{ port: daemonPort, token: daemonToken, remoteSessionUrl: agentDeviceRemoteSessionUrl },
webPreview,
installedApplicationIdentifier,
] = await Promise.all([agentDeviceStartup, sessionHostStartup, deviceReady]).catch(
(err: unknown) => {
// Also aborts for a `device.ready` that does not come from `tasks.run`.
@@ -253,6 +255,11 @@ export async function runAgentDeviceRemoteSessionAsync(
);
tasks.signal.throwIfAborted();
logger.info(tasks.summary());
// Reported so clients can attach to the app of a session with no build record, like an
// `application_archive_url` one. The session host already launched the iOS app.
const applicationIdentifier = hostBootedDevice?.application
? (await tasks.untilAborted(hostBootedDevice.application))?.launchAppIdentifier
: installedApplicationIdentifier;
const sessionStart = await uploadRemoteSessionConfigWithLocalEgressAsync({
env,
@@ -265,6 +272,7 @@ export async function runAgentDeviceRemoteSessionAsync(
webPreviewUrl: webPreview.previewPageUrl,
previewApiUrl: webPreview.apiUrl,
...(webPreview.previewToken ? { webPreviewToken: webPreview.previewToken } : {}),
...(applicationIdentifier ? { applicationIdentifier } : {}),
},
logger,
});
@@ -226,6 +226,7 @@ export function createStartAgentDeviceSessionBuildFunction(
let sessionOwnsTeardown = false;
let downloaded: Promise<string> | undefined;
let applicationReady: Promise<ServeSimApplicationOptions | void> | undefined;
let installedAndroidApplication: Promise<string> | undefined;
try {
if (isIos) {
@@ -321,7 +322,7 @@ export function createStartAgentDeviceSessionBuildFunction(
installAppPath,
});
} else if (!isIos && (installAppPath || downloadedApp)) {
applicationReady = tasks.run('app install and launch', async taskLogger => {
installedAndroidApplication = tasks.run('app install and launch', async taskLogger => {
await tasks.untilAborted(booted!);
const artifactPath = installAppPath ?? (await downloadedApp);
if (!artifactPath) {
@@ -344,6 +345,7 @@ export function createStartAgentDeviceSessionBuildFunction(
env,
logger: taskLogger,
});
return applicationIdentifier;
});
}
@@ -374,7 +376,7 @@ export function createStartAgentDeviceSessionBuildFunction(
}
: {
booted,
ready: applicationReady ?? tasks.untilAborted(booted),
ready: installedAndroidApplication ?? tasks.untilAborted(booted),
},
});
} catch (error) {
@@ -388,7 +390,12 @@ export function createStartAgentDeviceSessionBuildFunction(
throw error;
} finally {
tasks.abort(new Error('Agent-device session ended.'));
await Promise.allSettled([booted, downloaded, applicationReady]);
await Promise.allSettled([
booted,
downloaded,
applicationReady,
installedAndroidApplication,
]);
}
};
try {
@@ -0,0 +1,26 @@
import { BuildFunction, BuildRuntimePlatform } from '@expo/steps';
import { Sentry } from '../../sentry';
import { ServeSimCrashesRecorder } from '../utils/serveSimCrashesRecorder';
export function createStartServeSimCrashesBuildFunction(): BuildFunction {
return new BuildFunction({
namespace: 'eas',
id: 'start_serve_sim_crashes',
name: 'Start serve-sim simulator crashes',
__metricsId: 'eas/start_serve_sim_crashes',
supportedRuntimePlatforms: [BuildRuntimePlatform.DARWIN],
fn: async ({ logger }) => {
try {
await ServeSimCrashesRecorder.startAsync({ logger });
} catch (err) {
const error = err instanceof Error ? err : new Error(String(err));
Sentry.capture('Could not start serve-sim simulator crashes', error);
logger.warn(
{ err: error },
'Could not start simulator crash collection; the session will continue.'
);
}
},
});
}
@@ -0,0 +1,39 @@
import {
BuildFunction,
BuildRuntimePlatform,
BuildStepInput,
BuildStepInputValueTypeName,
} from '@expo/steps';
import { Sentry } from '../../sentry';
import { ServeSimNetworkCaptureRecorder } from '../utils/serveSimNetworkCaptureRecorder';
export function createStartServeSimNetworkCaptureBuildFunction(): BuildFunction {
return new BuildFunction({
namespace: 'eas',
id: 'start_serve_sim_network_capture',
name: 'Start serve-sim network capture',
__metricsId: 'eas/start_serve_sim_network_capture',
supportedRuntimePlatforms: [BuildRuntimePlatform.DARWIN],
inputProviders: [
BuildStepInput.createProvider({
id: 'package_version',
required: false,
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
}),
],
fn: async ({ logger }, { inputs, env }) => {
try {
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
packageVersion: inputs.package_version.value as string | undefined,
});
} catch (err) {
const error = err instanceof Error ? err : new Error(String(err));
Sentry.capture('Could not start the serve-sim network capture recorder', error);
logger.warn({ err: error }, 'Could not start the serve-sim network capture recorder.');
}
},
});
}
@@ -47,9 +47,11 @@ import {
} from '../serveSimActions';
import { startPreviewActivityPolling } from '../previewActivity';
import { readServeSimServersAsync } from '../serveSimMetricsRecorder';
import { ServeSimCrashesRecorder } from '../serveSimCrashesRecorder';
import * as previewCapture from '../serveSimPreviewCapture';
jest.mock('@ngrok/ngrok');
jest.mock('../serveSimCrashesRecorder');
jest.mock('@expo/turtle-spawn');
jest.mock('../../../utils/IosSimulatorUtils', () => ({
IosSimulatorUtils: { disableApsdAsync: jest.fn(), waitForReadyAsync: jest.fn() },
@@ -152,6 +154,7 @@ const stopSessionPreview = jest.fn();
beforeEach(() => {
jest.clearAllMocks();
jest.mocked(ServeSimCrashesRecorder.stopAsync).mockReset().mockResolvedValue(undefined);
jest
.mocked(startNgrokTunnelAsync)
.mockReset()
@@ -2360,6 +2363,22 @@ it('cancels an in-flight install while Simulator setup is pending', async () =>
expect(stopServer).toHaveBeenCalledTimes(1);
});
it('finishes in-flight crash collection before stopping the host', async () => {
const host = await startHostAsync();
const collecting = deferred<void>();
const entered = deferred<void>();
jest.mocked(ServeSimCrashesRecorder.stopAsync).mockImplementationOnce(async () => {
entered.resolve();
await collecting.promise;
});
const finishing = host.finishAsync();
await entered.promise;
expect(stopServer).not.toHaveBeenCalled();
collecting.resolve();
await finishing;
expect(stopServer).toHaveBeenCalledTimes(1);
});
it('redacts bearer tokens from preview readiness diagnostics while preserving the failure', async () => {
const output = [
'Native addon failed to initialize',
@@ -0,0 +1,69 @@
import type { bunyan } from '@expo/logger';
import { mkdtemp, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import type { CustomBuildContext } from '../../../customBuildContext';
import { Sentry } from '../../../sentry';
import { uploadDeviceRunSessionArtifactAsync } from '../deviceRunSessionArtifacts';
import { uploadServeSimCrashesFileAsync } from '../serveSimCrashesArtifacts';
jest.mock('../../../sentry');
jest.mock('../deviceRunSessionArtifacts');
jest.unmock('fs');
jest.unmock('node:fs');
jest.unmock('fs/promises');
jest.unmock('node:fs/promises');
const ctx = {} as CustomBuildContext;
const logger = { info: jest.fn(), warn: jest.fn() } as unknown as bunyan;
let crash: { udid: string; filePath: string; size: number; number: number };
beforeAll(async () => {
const filePath = path.join(await mkdtemp(path.join(os.tmpdir(), 'crash-test-')), 'A-2.ips');
await writeFile(filePath, '{"app_name":"Crash"}');
crash = { udid: 'ABCDEF123456', filePath, size: 20, number: 2 };
});
beforeEach(() => {
jest.clearAllMocks();
});
it.each([
[undefined, 'Crash report 2 (ABCDEF12)', 'crash-2.ips'],
['My/App:Beta\n', 'Crash report 2: My/App:Beta\n (ABCDEF12)', 'My-App-Beta--2.ips'],
])('names the report for process %j', async (processName, name, filename) => {
await uploadServeSimCrashesFileAsync(ctx, {
deviceRunSessionId: 'drs-id',
crash: { ...crash, ...(processName ? { processName } : {}) },
logger,
});
expect(uploadDeviceRunSessionArtifactAsync).toHaveBeenCalledWith(ctx, {
deviceRunSessionId: 'drs-id',
artifactId: 'simulator-crash-ABCDEF123456-2',
name,
filename,
kind: 'simulator-crash',
metadata: { __eas_type: 'simulator-crash', udid: 'ABCDEF123456', source: 'serve-sim/crashes' },
size: 20,
openStream: expect.any(Function),
signal: expect.any(AbortSignal),
attempts: 3,
});
});
it('reports a failed upload by report number without rejecting', async () => {
jest.mocked(uploadDeviceRunSessionArtifactAsync).mockRejectedValueOnce(new Error('offline'));
await expect(
uploadServeSimCrashesFileAsync(ctx, { deviceRunSessionId: 'drs-id', crash, logger })
).resolves.toBeUndefined();
expect(Sentry.capture).toHaveBeenCalledWith(
'Could not upload a simulator crash report',
expect.objectContaining({ message: 'offline' }),
{ level: 'warning' }
);
expect(logger.warn).toHaveBeenCalledWith(
{ err: expect.objectContaining({ message: 'offline' }) },
'Could not upload crash report 2 for ABCDEF123456; other artifacts will continue.'
);
});
@@ -0,0 +1,816 @@
import { type bunyan } from '@expo/logger';
import { mkdtemp, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises';
import { type IncomingMessage, type Server, type ServerResponse, createServer } from 'node:http';
import { type AddressInfo } from 'node:net';
import os from 'node:os';
import path from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { type CustomBuildContext } from '../../../customBuildContext';
import { DEVICE_RUN_SESSION_TOKEN_HEADER } from '../deviceRunSessionWorkerApi';
import { uploadServeSimCrashesFileAsync } from '../serveSimCrashesArtifacts';
import { ServeSimCrashesRecorder } from '../serveSimCrashesRecorder';
import * as serveSimServers from '../serveSimMetricsRecorder';
jest.mock('../../../sentry');
jest.unmock('fs');
jest.unmock('node:fs');
jest.unmock('fs/promises');
jest.unmock('node:fs/promises');
jest.unmock('node-fetch');
const fs = jest.requireActual<typeof import('node:fs/promises')>('node:fs/promises');
const logger = { info: jest.fn(), warn: jest.fn() } as unknown as bunyan;
let directory: string;
let server: Server;
let baseUrl: string;
const summary = { id: 'crash/a', appName: 'Fixture', occurrenceTimes: [{ key: 1 }, { key: 2 }] };
const report = (key: number) =>
JSON.stringify({ app_name: 'Fixture 서울 🌲', incident_id: `INC-${key}` }) +
'\n' +
JSON.stringify({ exception: { type: 'EXC_CRASH', signal: 'SIGABRT' }, incident: `INC-${key}` }) +
'\n';
const detail = (key: number) => ({
record: { id: summary.id, bundleId: 'dev.expo.fixture' },
occurrence: { key, incidentId: `INC-${key}`, logTail: ['PRIVATE APP LOG'], pid: 123 },
report: report(key),
reportError: null,
});
/** Answers the one-shot list that stopping reads; returns false for other requests. */
function answerList(
request: IncomingMessage,
response: ServerResponse,
crashes: unknown[] = []
): boolean {
if (request.headers.accept !== 'application/json') {
return false;
}
response.setHeader('Content-Type', 'application/json');
response.end(JSON.stringify({ meta: { statusError: null }, crashes }));
return true;
}
function stoppedRetrying(): boolean {
return jest
.mocked(logger.warn)
.mock.calls.some(([message]) =>
String(message).startsWith('Stopped retrying simulator crash collection')
);
}
async function waitFor(read: () => boolean | Promise<boolean>): Promise<void> {
for (let i = 0; i < 200; i++) {
if (await read()) {
return;
}
await delay(10);
}
throw new Error('Timed out waiting for crash recording');
}
async function start(maxBytes?: number): Promise<void> {
await writeFile(
path.join(directory, 'server-device-A.json'),
JSON.stringify({
device: 'device-A',
url: baseUrl,
token: 'test-token',
})
);
await ServeSimCrashesRecorder.startAsync({
logger,
stateDir: directory,
pollIntervalMs: 10,
maxBytes,
});
}
beforeEach(async () => {
directory = await mkdtemp(path.join(os.tmpdir(), 'crashes-http-test-'));
server = createServer();
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});
afterEach(async () => {
const { outputDirectory } = await ServeSimCrashesRecorder.finishAsync();
if (outputDirectory) {
await rm(outputDirectory, { recursive: true, force: true });
}
server.closeAllConnections();
await new Promise<void>(resolve => server.close(() => resolve()));
await rm(directory, { recursive: true, force: true });
});
it('saves recurrences as separate private IPS files and uploads unchanged reports without app logs', async () => {
let connections = 0;
let requests = 0;
const uploaded: Buffer[] = [];
let uploadAttempts = 0;
const uploadInputs: { filename: string }[] = [];
server.on('request', (request, response) => {
if (request.url === '/v2/device-run-session-worker/artifact-upload-sessions') {
expect(request.method).toBe('POST');
expect(request.headers[DEVICE_RUN_SESSION_TOKEN_HEADER]).toBe('worker-token');
const chunks: Buffer[] = [];
request.on('data', chunk => chunks.push(chunk));
request.on('end', () => {
uploadInputs.push(JSON.parse(Buffer.concat(chunks).toString()));
response.setHeader('Content-Type', 'application/json');
response.end(
JSON.stringify({ data: { uploadSession: { url: baseUrl + '/upload', headers: {} } } })
);
});
return;
}
if (request.method === 'PUT') {
const chunks: Buffer[] = [];
request.on('data', chunk => chunks.push(chunk));
request.on('end', () => {
uploaded.push(Buffer.concat(chunks));
uploadAttempts += 1;
response.writeHead(uploadAttempts === 1 ? 503 : 200).end();
});
return;
}
expect(request.headers.authorization).toBe('Bearer test-token');
const url = new URL(request.url!, baseUrl);
expect(url.searchParams.get('device')).toBe('device-A');
if (answerList(request, response, [summary])) {
return;
}
if (url.pathname === '/crashes') {
expect(url.searchParams.has('tail')).toBe(false);
expect(request.headers.accept).toBe('text/event-stream');
connections += 1;
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
const initial = { ...summary, occurrenceTimes: [{ key: 1 }] };
const wire = `data: ${JSON.stringify({ type: 'list', crashes: [initial] })}\r\n\r\n`;
if (connections === 1) {
response.end(wire);
} else {
response.write(
wire + `data: ${JSON.stringify({ type: 'recurred', record: summary })}\r\n\r\n`
);
}
} else {
expect(url.pathname).toBe('/crashes/crash%2Fa');
requests += 1;
response.end(JSON.stringify(detail(Number(url.searchParams.get('key')))));
}
});
await start();
await waitFor(() => requests === 2);
await ServeSimCrashesRecorder.stopAsync();
const { crashes: files } = await ServeSimCrashesRecorder.finishAsync();
expect(files).toHaveLength(2);
expect(requests).toBe(2);
const expected = [Buffer.from(report(1)), Buffer.from(report(2))];
for (const [index, file] of files.entries()) {
expect(path.extname(file.filePath)).toBe('.ips');
expect(await readFile(file.filePath)).toEqual(expected[index]);
expect((await stat(file.filePath)).mode & 0o777).toBe(0o600);
expect((await stat(path.dirname(file.filePath))).mode & 0o777).toBe(0o700);
}
expect(files[0].filePath).not.toBe(files[1].filePath);
const context = {
env: { EAS_DEVICE_RUN_SESSION_TOKEN: 'worker-token' },
expoApiV2BaseUrl: baseUrl + '/v2/',
} as unknown as CustomBuildContext;
for (const crash of files) {
await uploadServeSimCrashesFileAsync(context, {
deviceRunSessionId: 'session-id',
crash,
logger,
});
}
expect(uploaded).toEqual([expected[0], expected[0], expected[1]]);
expect(uploadAttempts).toBe(3);
expect(uploadInputs.map(input => input.filename)).toEqual(['Fixture-1.ips', 'Fixture-2.ips']);
expect(uploadInputs[0]).toMatchObject({
name: 'Crash report 1: Fixture (device-A)',
kind: 'simulator-crash',
metadata: { __eas_type: 'simulator-crash', udid: 'device-A', source: 'serve-sim/crashes' },
});
expect(JSON.stringify(uploadInputs)).not.toContain('PRIVATE APP LOG');
expect(await ServeSimCrashesRecorder.finishAsync()).toEqual({
outputDirectory: null,
crashes: [],
});
await rm(path.dirname(files[0].filePath), { recursive: true, force: true });
});
it('keeps an in-flight report download alive during stop and waits for its write', async () => {
let requested = false;
let finishReport: () => void = () => {};
server.on('request', (request, response) => {
if (request.url!.startsWith('/crashes?')) {
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
response.write(`data: ${JSON.stringify({ type: 'crash', record: summary })}\n\n`);
} else {
requested = true;
finishReport = () => response.end(JSON.stringify(detail(1)));
}
});
await start();
await waitFor(() => requested);
const stopped = ServeSimCrashesRecorder.stopAsync();
finishReport();
await stopped;
const { crashes: files } = await ServeSimCrashesRecorder.finishAsync();
expect(await readFile(files[0].filePath, 'utf8')).toBe(report(1));
await rm(path.dirname(files[0].filePath), { recursive: true, force: true });
});
it('closes a rejected stream socket and produces no artifact for an empty session', async () => {
let closed = false;
server.on('request', (request, response) => {
request.socket.on('close', () => {
closed = true;
});
response.writeHead(403).write('unfinished response');
});
await start();
await waitFor(() => closed);
const collected = await ServeSimCrashesRecorder.finishAsync();
expect(collected.crashes).toEqual([]);
expect(collected.outputDirectory).toEqual(expect.any(String));
await rm(collected.outputDirectory!, { recursive: true, force: true });
expect(JSON.stringify(jest.mocked(logger.warn).mock.calls)).not.toContain('test-token');
});
it('stops at a complete-record byte limit and keeps earlier reports', async () => {
let requested = 0;
server.on('request', (request, response) => {
if (request.url!.startsWith('/crashes?')) {
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
response.write(`data: ${JSON.stringify({ type: 'list', crashes: [summary] })}\n\n`);
} else {
requested += 1;
response.end(
JSON.stringify(detail(Number(new URL(request.url!, baseUrl).searchParams.get('key'))))
);
}
});
await writeFile(
path.join(directory, 'server-device-A.json'),
JSON.stringify({ device: 'device-A', url: baseUrl })
);
await ServeSimCrashesRecorder.startAsync({
logger,
stateDir: directory,
pollIntervalMs: 10,
maxBytes: Buffer.byteLength(report(1)),
});
await waitFor(() => requested === 2);
await ServeSimCrashesRecorder.stopAsync();
const { crashes: files } = await ServeSimCrashesRecorder.finishAsync();
expect(await readFile(files[0].filePath, 'utf8')).toBe(report(1));
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('reached its limit'));
await rm(path.dirname(files[0].filePath), { recursive: true, force: true });
});
it.each([
[
'fails on every request',
3,
'Could not download crash occurrence 1 for device-A; skipping it.',
(response: ServerResponse) => response.writeHead(500).end(),
],
[
'is refused with a permanent 4xx',
1,
'Could not download crash occurrence 1 for device-A; skipping it.',
(response: ServerResponse) => response.writeHead(400).end(),
],
[
'is not valid JSON',
1,
'Could not download crash occurrence 1 for device-A; skipping it.',
(response: ServerResponse) => response.end('{broken'),
],
[
'exceeds 8 MiB',
1,
'Could not download crash occurrence 1 for device-A; skipping it.',
(response: ServerResponse) =>
response.end(JSON.stringify({ ...detail(1), report: 'x'.repeat(8 * 1024 * 1024) })),
],
[
'does not match the occurrence',
1,
'Could not download crash occurrence 1 for device-A; skipping it.',
(response: ServerResponse) => response.end(JSON.stringify(detail(2))),
],
[
'is no longer kept',
1,
'Crash occurrence 1 is no longer available for device-A; earlier reports will be retained.',
(response: ServerResponse) => response.writeHead(404).end(),
],
])(
'skips an occurrence whose detail %s after %i attempts and keeps collecting the device',
async (_name, attempts, warning, respond) => {
let connections = 0;
let badRequests = 0;
server.on('request', (request, response) => {
const url = new URL(request.url!, baseUrl);
if (answerList(request, response)) {
return;
}
if (url.pathname === '/crashes') {
connections += 1;
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
// Every stream ends, so each reconnect replays the bad occurrence.
response.end(
`data: ${JSON.stringify({
type: 'list',
crashes: [
{ id: 'crash/b', occurrenceTimes: [{ key: 1 }] },
{ ...summary, occurrenceTimes: [{ key: 1 }] },
],
})}\n\n`
);
} else if (url.pathname === '/crashes/crash%2Fb') {
badRequests += 1;
respond(response);
} else {
response.end(JSON.stringify(detail(1)));
}
});
await start();
await waitFor(() => connections >= 12);
const collected = await ServeSimCrashesRecorder.finishAsync();
expect(badRequests).toBe(attempts);
expect(stoppedRetrying()).toBe(false);
expect(jest.mocked(logger.warn).mock.calls.filter(call => call.includes(warning))).toHaveLength(
1
);
expect(collected.crashes).toHaveLength(1);
expect(await readFile(collected.crashes[0].filePath, 'utf8')).toBe(report(1));
await rm(collected.outputDirectory!, { recursive: true, force: true });
}
);
it('saves an occurrence whose detail fails once, without reconnecting', async () => {
let connections = 0;
let requests = 0;
server.on('request', (request, response) => {
if (answerList(request, response)) {
return;
}
if (request.url!.startsWith('/crashes?')) {
connections += 1;
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
response.write(
`data: ${JSON.stringify({ type: 'list', crashes: [{ ...summary, occurrenceTimes: [{ key: 1 }] }] })}\n\n`
);
} else {
requests += 1;
if (requests === 1) {
response.writeHead(503).end();
} else {
response.end(JSON.stringify(detail(1)));
}
}
});
await start();
await waitFor(() => requests === 2);
const collected = await ServeSimCrashesRecorder.finishAsync();
expect(connections).toBe(1);
expect(collected.crashes).toHaveLength(1);
expect(await readFile(collected.crashes[0].filePath, 'utf8')).toBe(report(1));
expect(logger.warn).not.toHaveBeenCalledWith(
expect.anything(),
expect.stringContaining('Could not download')
);
await rm(collected.outputDirectory!, { recursive: true, force: true });
});
it('collects an occurrence listed after the stream last delivered, when stopping', async () => {
let streaming = false;
server.on('request', (request, response) => {
const url = new URL(request.url!, baseUrl);
const listed = { ...summary, appName: '', procName: 'FixtureProcess' };
if (answerList(request, response, [{ ...listed, occurrenceTimes: [{ key: 1 }] }])) {
return;
}
if (url.pathname === '/crashes') {
streaming = true;
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
response.write(`data: ${JSON.stringify({ type: 'list', crashes: [] })}\n\n`);
} else {
response.end(JSON.stringify(detail(1)));
}
});
await start();
await waitFor(() => streaming);
const collected = await ServeSimCrashesRecorder.finishAsync();
expect(collected.crashes).toEqual([
{
udid: 'device-A',
filePath: path.join(collected.outputDirectory!, 'device-A-1.ips'),
size: Buffer.byteLength(report(1)),
number: 1,
processName: 'FixtureProcess',
},
]);
expect(await readFile(collected.crashes[0].filePath, 'utf8')).toBe(report(1));
await rm(collected.outputDirectory!, { recursive: true, force: true });
});
it('stops the final pass at its deadline and warns', async () => {
let streaming = false;
server.on('request', (request, response) => {
if (answerList(request, response, [{ ...summary, occurrenceTimes: [{ key: 1 }] }])) {
return;
}
if (request.url!.startsWith('/crashes?')) {
streaming = true;
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
response.write(`data: ${JSON.stringify({ type: 'list', crashes: [] })}\n\n`);
}
// The detail never answers.
});
await writeFile(
path.join(directory, 'server-device-A.json'),
JSON.stringify({ device: 'device-A', url: baseUrl, token: 'test-token' })
);
await ServeSimCrashesRecorder.startAsync({
logger,
stateDir: directory,
pollIntervalMs: 10,
finalPassTimeoutMs: 100,
});
await waitFor(() => streaming);
const collected = await ServeSimCrashesRecorder.finishAsync();
expect(collected.crashes).toEqual([]);
expect(logger.warn).toHaveBeenCalledWith(
'Stopped checking device-A for crashes at the end-of-session deadline; collected reports will be retained.'
);
await rm(collected.outputDirectory!, { recursive: true, force: true });
});
it('warns once per device when serve-sim cannot watch crash reports', async () => {
let connections = 0;
server.on('request', (_request, response) => {
connections += 1;
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
response.end(
`data: ${JSON.stringify({ type: 'meta', meta: { statusError: 'EACCES' } })}\n\n` +
`data: ${JSON.stringify({ type: 'list', crashes: [] })}\n\n`
);
});
await start();
await waitFor(() => connections >= 3);
const collected = await ServeSimCrashesRecorder.finishAsync();
expect(
jest
.mocked(logger.warn)
.mock.calls.filter(([message]) => String(message).startsWith('serve-sim cannot watch'))
).toHaveLength(1);
await rm(collected.outputDirectory!, { recursive: true, force: true });
});
it.each([
['empty', ''],
['heartbeat-only', ': heartbeat\n\n'],
['meta-only', `data: ${JSON.stringify({ type: 'meta', meta: { statusError: null } })}\n\n`],
['invalid JSON', 'data: {invalid}\n\n'],
['invalid frame', 'data: {"type":"list","crashes":false}\n\n'],
])('stops retrying after ten %s streams', async (_name, payload) => {
let connections = 0;
server.on('request', (_request, response) => {
connections += 1;
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
response.end(payload);
});
await start();
await waitFor(stoppedRetrying);
await delay(30);
expect(connections).toBe(10);
const collected = await ServeSimCrashesRecorder.finishAsync();
expect(collected.crashes).toEqual([]);
await rm(collected.outputDirectory!, { recursive: true, force: true });
});
it('keeps retrying streams that process a healthy empty crash list', async () => {
let connections = 0;
server.on('request', (_request, response) => {
connections += 1;
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
const frame = `data: ${JSON.stringify({ type: 'list', crashes: [] })}\n\n`;
if (connections < 12) {
response.end(frame);
} else {
response.write(frame);
}
});
await start();
await waitFor(() => connections === 12);
expect(stoppedRetrying()).toBe(false);
});
it('recovers the same server after registry absence without resetting dedupe or the byte budget', async () => {
let connections = 0;
let healthy = false;
let expectAbsence = false;
let observedAbsence = false;
const keys: number[] = [];
const readServers = serveSimServers.readServeSimServersAsync;
const registry = jest
.spyOn(serveSimServers, 'readServeSimServersAsync')
.mockImplementation(async stateDir => {
const servers = await readServers(stateDir);
if (expectAbsence && servers.length === 0) {
observedAbsence = true;
}
return servers;
});
server.on('request', (request, response) => {
const url = new URL(request.url!, baseUrl);
if (url.pathname === '/crashes') {
connections += 1;
if (connections > 1 && !healthy) {
response.writeHead(503).end();
return;
}
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
const record = {
...summary,
occurrenceTimes: healthy ? [{ key: 1 }, { key: 2 }, { key: 3 }] : [{ key: 1 }],
};
const frame = `data: ${JSON.stringify({ type: 'list', crashes: [record] })}\n\n`;
if (healthy) {
response.write(frame);
} else {
response.end(frame);
}
} else {
const key = Number(url.searchParams.get('key'));
keys.push(key);
response.end(JSON.stringify(detail(key)));
}
});
try {
const expected = report(1) + report(2);
await start(Buffer.byteLength(expected));
await waitFor(stoppedRetrying);
expect(connections).toBe(11);
expectAbsence = true;
await rm(path.join(directory, 'server-device-A.json'));
await waitFor(() => observedAbsence);
healthy = true;
await writeFile(
path.join(directory, 'server-device-A.json'),
JSON.stringify({
device: 'device-A',
url: baseUrl,
token: 'test-token',
})
);
await waitFor(() => keys.includes(3));
const collected = await ServeSimCrashesRecorder.finishAsync();
expect(connections).toBe(12);
expect(keys).toEqual([1, 2, 3]);
expect(collected.crashes).toHaveLength(2);
expect(
(await Promise.all(collected.crashes.map(file => readFile(file.filePath, 'utf8')))).join('')
).toBe(expected);
await rm(collected.outputDirectory!, { recursive: true, force: true });
} finally {
registry.mockRestore();
}
});
it('closes a stalled upload within its budget and lets another device upload', async () => {
const firstFile = path.join(directory, 'A.ips');
const secondFile = path.join(directory, 'B.ips');
await writeFile(firstFile, report(1));
const expected = Buffer.from(report(2));
await writeFile(secondFile, expected);
let firstClosed = false;
let firstRequests = 0;
let uploaded: Buffer | undefined;
let sessions = 0;
server.on('request', (request, response) => {
if (request.url === '/v2/device-run-session-worker/artifact-upload-sessions') {
expect(request.method).toBe('POST');
expect(request.headers[DEVICE_RUN_SESSION_TOKEN_HEADER]).toBe('worker-token');
request.resume();
request.on('end', () => {
response.setHeader('Content-Type', 'application/json');
response.end(
JSON.stringify({
data: {
uploadSession: {
url: baseUrl + (sessions++ === 0 ? '/stalled' : '/upload'),
headers: {},
},
},
})
);
});
return;
}
if (request.url === '/stalled') {
firstRequests += 1;
response.on('close', () => {
firstClosed = true;
});
request.resume();
} else {
const chunks: Buffer[] = [];
request.on('data', chunk => chunks.push(chunk));
request.on('end', () => {
uploaded = Buffer.concat(chunks);
response.end();
});
}
});
const context = {
env: { EAS_DEVICE_RUN_SESSION_TOKEN: 'worker-token' },
expoApiV2BaseUrl: baseUrl + '/v2/',
} as unknown as CustomBuildContext;
await uploadServeSimCrashesFileAsync(context, {
deviceRunSessionId: 'session-id',
crash: { udid: 'A', filePath: firstFile, size: Buffer.byteLength(report(1)), number: 1 },
logger,
signal: AbortSignal.timeout(50),
});
await waitFor(() => firstClosed);
expect(firstRequests).toBe(1);
expect(logger.warn).toHaveBeenCalledWith(
expect.any(Object),
'Could not upload crash report 1 for A; other artifacts will continue.'
);
await uploadServeSimCrashesFileAsync(context, {
deviceRunSessionId: 'session-id',
crash: { udid: 'B', filePath: secondFile, size: expected.length, number: 1 },
logger,
signal: AbortSignal.timeout(1_000),
});
expect(sessions).toBe(2);
expect(uploaded).toEqual(expected);
});
it.each([null, ''])(
'does not create an artifact when the native report is %s',
async nativeReport => {
let requested = false;
server.on('request', (request, response) => {
if (request.url!.startsWith('/crashes?')) {
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
response.write(
`data: ${JSON.stringify({ type: 'list', crashes: [{ ...summary, occurrenceTimes: [{ key: 1 }] }] })}\n\n`
);
} else {
requested = true;
response.end(
JSON.stringify({ ...detail(1), report: nativeReport, reportError: 'Report unavailable' })
);
}
});
await start();
await waitFor(() => requested);
const collected = await ServeSimCrashesRecorder.finishAsync();
expect(collected.crashes).toEqual([]);
expect(await readdir(collected.outputDirectory!)).toEqual([]);
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('has no native report'));
await rm(collected.outputDirectory!, { recursive: true, force: true });
}
);
it('does not duplicate a saved incident when a restarted serve-sim reuses occurrence keys', async () => {
let requested = 0;
server.on('request', (request, response) => {
if (answerList(request, response)) {
return;
}
// A restarted serve-sim numbers occurrences from 1 again; the capture time tells them apart.
const restarted = request.headers.authorization === 'Bearer new-token';
if (request.url!.startsWith('/crashes?')) {
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
const occurrence = restarted
? { key: 1, capturedAtMs: 2_000, rawPath: '/DiagnosticReports/Fixture-2.ips' }
: { key: 1, capturedAtMs: 1_000, rawPath: '/DiagnosticReports/Fixture-1.ips' };
response.write(
`data: ${JSON.stringify({ type: 'list', crashes: [{ ...summary, occurrenceTimes: [occurrence] }] })}\n\n`
);
} else {
requested += 1;
response.end(JSON.stringify(detail(1)));
}
});
await start();
await waitFor(() => requested === 1);
await writeFile(
path.join(directory, 'server-device-A.json'),
JSON.stringify({ device: 'device-A', url: baseUrl, token: 'new-token' })
);
server.closeAllConnections();
await waitFor(() => requested === 2);
const collected = await ServeSimCrashesRecorder.finishAsync();
expect(collected.crashes).toHaveLength(1);
expect(await readFile(collected.crashes[0].filePath, 'utf8')).toBe(report(1));
await rm(collected.outputDirectory!, { recursive: true, force: true });
});
it('removes a partial file before retrying a failed write', async () => {
const write = fs.writeFile;
let attempted = 0;
const writing = jest.spyOn(fs, 'writeFile').mockImplementation(async (file, data, options) => {
if (String(file).endsWith('.ips') && attempted++ === 0) {
await write(file, 'partial report', options);
throw new Error('disk write failed');
}
await write(file, data, options);
});
server.on('request', (request, response) => {
if (request.url!.startsWith('/crashes?')) {
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
response.write(
`data: ${JSON.stringify({ type: 'list', crashes: [{ ...summary, occurrenceTimes: [{ key: 1 }] }] })}\n\n`
);
} else {
response.end(JSON.stringify(detail(1)));
}
});
try {
await start();
await waitFor(() => attempted >= 2);
const collected = await ServeSimCrashesRecorder.finishAsync();
expect(collected.crashes).toHaveLength(1);
expect(await readdir(collected.outputDirectory!)).toEqual([
path.basename(collected.crashes[0].filePath),
]);
expect(await readFile(collected.crashes[0].filePath, 'utf8')).toBe(report(1));
await rm(collected.outputDirectory!, { recursive: true, force: true });
} finally {
writing.mockRestore();
}
});
it('keeps the report allowance and deduplicates reconnects after more missing reports than the allowance', async () => {
const missingCount = 1_001;
const requested: number[] = [];
let connections = 0;
let completed: (() => void) | undefined;
const processed = new Promise<void>(resolve => {
completed = resolve;
});
const occurrence = (key: number) => ({ ...summary, occurrenceTimes: [{ key }] });
server.on('request', (request, response) => {
if (answerList(request, response)) {
return;
}
if (request.url!.startsWith('/crashes?')) {
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
connections += 1;
if (connections === 1) {
for (let key = 1; key <= missingCount; key++) {
response.write(
`data: ${JSON.stringify({ type: 'recurred', record: occurrence(key) })}\n\n`
);
}
} else {
const retained = {
...summary,
occurrenceTimes: Array.from({ length: 5 }, (_, index) => ({
key: missingCount - 4 + index,
})),
};
response.write(`data: ${JSON.stringify({ type: 'list', crashes: [retained] })}\n\n`);
}
if (connections < 3) {
response.end();
} else {
response.write(
`data: ${JSON.stringify({ type: 'recurred', record: occurrence(missingCount + 1) })}\n\n`
);
}
} else {
const key = Number(new URL(request.url!, baseUrl).searchParams.get('key'));
requested.push(key);
response.end(
JSON.stringify({ ...detail(key), report: key <= missingCount ? null : report(key) })
);
if (key === missingCount + 1) {
completed?.();
}
}
});
await start();
await processed;
const collected = await ServeSimCrashesRecorder.finishAsync();
try {
expect(connections).toBe(3);
expect(requested).toEqual(Array.from({ length: missingCount + 1 }, (_, index) => index + 1));
expect(collected.crashes).toHaveLength(1);
expect(await readFile(collected.crashes[0].filePath, 'utf8')).toBe(report(missingCount + 1));
expect(logger.warn).not.toHaveBeenCalledWith(expect.stringContaining('reached its limit'));
} finally {
await rm(collected.outputDirectory!, { recursive: true, force: true });
}
}, 15_000);
@@ -0,0 +1,94 @@
import type { bunyan } from '@expo/logger';
import { mkdtemp, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import type { CustomBuildContext } from '../../../customBuildContext';
import { Sentry } from '../../../sentry';
import { uploadDeviceRunSessionArtifactAsync } from '../deviceRunSessionArtifacts';
import { uploadServeSimNetworkCaptureFileAsync } from '../serveSimNetworkCaptureArtifacts';
jest.mock('../../../sentry');
jest.mock('../deviceRunSessionArtifacts');
const ctx = {} as CustomBuildContext;
const logger = { info: jest.fn(), warn: jest.fn() } as unknown as bunyan;
async function harAsync(name: string): Promise<string> {
const filePath = path.join(await mkdtemp(path.join(os.tmpdir(), 'network-capture-test-')), name);
await writeFile(filePath, '{"log":{"entries":[{}]}}');
return filePath;
}
beforeEach(() => {
jest.clearAllMocks();
jest.mocked(uploadDeviceRunSessionArtifactAsync).mockImplementation(async (_ctx, options) => {
options.openStream().destroy();
});
});
it.each([
[1, 'Network capture (ABCDEF12)'],
[2, 'Network capture (ABCDEF12, part 2)'],
])('uploads part %i as a network-capture artifact', async (part, name) => {
const filePath = await harAsync('A.har');
await uploadServeSimNetworkCaptureFileAsync(ctx, {
deviceRunSessionId: 'drs-id',
udid: 'ABCDEF123456',
filePath,
size: 24,
part,
logger,
});
expect(uploadDeviceRunSessionArtifactAsync).toHaveBeenCalledWith(ctx, {
deviceRunSessionId: 'drs-id',
artifactId: `network-capture-ABCDEF123456-${part}`,
name,
filename: 'network-capture.har',
kind: 'network-capture',
metadata: { __eas_type: 'network-capture', format: 'har', udid: 'ABCDEF123456', part },
size: 24,
openStream: expect.any(Function),
signal: expect.any(AbortSignal),
attempts: 3,
});
});
it('logs a failed upload without rejecting', async () => {
jest.mocked(uploadDeviceRunSessionArtifactAsync).mockRejectedValueOnce(new Error('offline'));
await expect(
uploadServeSimNetworkCaptureFileAsync(ctx, {
deviceRunSessionId: 'drs-id',
udid: 'A',
filePath: await harAsync('A.har'),
size: 24,
part: 1,
logger,
})
).resolves.toBeUndefined();
expect(logger.warn).toHaveBeenCalledWith(
{ err: expect.objectContaining({ message: 'offline' }) },
'Could not upload the network capture for A.'
);
expect(Sentry.capture).toHaveBeenCalledTimes(1);
});
it('accepts 500 MiB and skips larger HARs', async () => {
const limit = 500 * 1024 * 1024;
const filePath = await harAsync('A.har');
for (const size of [limit, limit + 1]) {
await uploadServeSimNetworkCaptureFileAsync(ctx, {
deviceRunSessionId: 'drs-id',
udid: 'A',
filePath,
size,
part: 1,
logger,
});
}
expect(uploadDeviceRunSessionArtifactAsync).toHaveBeenCalledTimes(1);
expect(logger.warn).toHaveBeenCalledWith(
'Skipping network capture for A: exceeds the 500 MB upload limit.'
);
expect(Sentry.capture).not.toHaveBeenCalled();
});
@@ -0,0 +1,606 @@
import { bunyan } from '@expo/logger';
import { type BuildStepEnv } from '@expo/steps';
import { appendFileSync, existsSync, writeFileSync } from 'node:fs';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { spawnDetached } from '../remoteDeviceRunSession';
import { ServeSimNetworkCaptureRecorder } from '../serveSimNetworkCaptureRecorder';
jest.mock('../../../sentry');
jest.mock('../remoteDeviceRunSession', () => ({
...jest.requireActual('../remoteDeviceRunSession'),
spawnDetached: jest.fn(),
}));
const logger = {
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
debug: jest.fn(),
} as unknown as bunyan;
const env = {} as BuildStepEnv;
const stopFollower = jest.fn();
let stateDir: string;
async function writeServerAsync(udid: string, state: Record<string, unknown>): Promise<void> {
await writeFile(
path.join(stateDir, `server-${udid}.json`),
JSON.stringify({ device: udid, ...state })
);
}
/** Writes what `capture har` leaves: a HAR, and its entry log with one line per request. */
function record(harPath: string, entries: number): void {
writeFileSync(harPath, `${JSON.stringify({ log: { entries: Array(entries).fill({}) } })}\n`);
writeFileSync(harPath.replace(/\.har$/, '.entries.ndjson'), '{}\n'.repeat(entries));
}
type Request = { id: string; startedAt: number };
function entryFor({ id, startedAt }: Request) {
return {
startedDateTime: new Date(startedAt).toISOString(),
request: { url: `https://example.com/${id}` },
_captureId: id,
_captureStartedAt: startedAt,
};
}
/** Writes a recording as serve-sim does: entries by completion time, the HAR in start order. */
function recordRequests(harPath: string, requests: Request[]): void {
const entries = requests.map(entryFor);
const sorted = [...entries].sort((a, b) => a._captureStartedAt - b._captureStartedAt);
writeFileSync(
harPath,
`${JSON.stringify({
log: {
version: '1.2',
creator: { name: '@expo/serve-sim', version: '0.10.2' },
entries: sorted,
},
})}\n`
);
writeFileSync(
harPath.replace(/\.har$/, '.entries.ndjson'),
entries.map(entry => `${JSON.stringify(entry)}\n`).join('')
);
}
async function readHarAsync(harPath: string): Promise<any> {
return JSON.parse(await readFile(harPath, 'utf8'));
}
function followerArgs(): string[][] {
return jest.mocked(spawnDetached).mock.calls.map(([options]) => options.args);
}
async function waitForFollowersAsync(count: number): Promise<void> {
for (let i = 0; i < 300 && jest.mocked(spawnDetached).mock.calls.length < count; i++) {
await delay(10);
}
expect(spawnDetached).toHaveBeenCalledTimes(count);
}
beforeEach(async () => {
jest.clearAllMocks();
stopFollower.mockResolvedValue(undefined);
jest.mocked(spawnDetached).mockImplementation(() => ({
pid: 1234,
getOutput: () => 'Stopped before recording began.',
getExitError: () => undefined,
stopAsync: stopFollower,
}));
stateDir = await mkdtemp(path.join(os.tmpdir(), 'serve-sim-network-capture-test-'));
await mkdir(stateDir, { recursive: true });
});
afterEach(async () => {
await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
await rm(stateDir, { recursive: true, force: true });
});
it('starts one capture har follower per serve-sim that can serve capture routes', async () => {
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await writeServerAsync('SIM-B', { url: 'http://127.0.0.1:4200' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
packageVersion: '0.5.0',
stateDir,
pollIntervalMs: 10,
});
await waitForFollowersAsync(1);
await delay(50);
expect(spawnDetached).toHaveBeenCalledTimes(1);
const [options] = jest.mocked(spawnDetached).mock.calls[0];
expect(options.command).toBe('npx');
expect(options.args).toEqual([
'--yes',
'@expo/[email protected]',
'capture',
'har',
'-o',
expect.stringMatching(/SIM-A-1\.har$/),
'-d',
'SIM-A',
]);
expect(options.stopGracePeriodMs).toBe(60_000);
});
it('does not pass the ngrok token to the follower', async () => {
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env: { NGROK_AUTHTOKEN: 'ngrok-secret', PATH: '/usr/bin' } as BuildStepEnv,
stateDir,
pollIntervalMs: 10,
});
await waitForFollowersAsync(1);
expect(jest.mocked(spawnDetached).mock.calls[0][0].env).toEqual({ PATH: '/usr/bin' });
});
it('starts a new follower only when serve-sim restarts for the device', async () => {
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
stateDir,
pollIntervalMs: 10,
packageVersion: '0.5.0',
});
await waitForFollowersAsync(1);
await delay(50);
expect(spawnDetached).toHaveBeenCalledTimes(1);
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-restarted' });
await waitForFollowersAsync(2);
expect(jest.mocked(spawnDetached).mock.calls[1][0].command).toBe('npx');
expect(followerArgs()[1]).toEqual([
'--yes',
'@expo/[email protected]',
'capture',
'har',
'-o',
expect.stringMatching(/SIM-A-2\.har$/),
'-d',
'SIM-A',
]);
});
it('stops every follower and returns only the HARs that hold requests', async () => {
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await writeServerAsync('SIM-B', { url: 'http://127.0.0.1:4200', token: 'token-b' });
await ServeSimNetworkCaptureRecorder.startAsync({ logger, env, stateDir, pollIntervalMs: 10 });
await waitForFollowersAsync(2);
const recorded = followerArgs().find(args => args.includes('SIM-A'))!;
record(recorded[recorded.indexOf('-o') + 1], 1);
// serve-sim writes an empty HAR when recording begins, before any request.
const empty = followerArgs().find(args => args.includes('SIM-B'))!;
record(empty[empty.indexOf('-o') + 1], 0);
const { outputDirectory, captures } = await ServeSimNetworkCaptureRecorder.finishAsync({
logger,
});
expect(stopFollower).toHaveBeenCalledTimes(2);
expect(captures).toEqual([
{ udid: 'SIM-A', filePath: recorded[recorded.indexOf('-o') + 1], size: 25 },
]);
expect(outputDirectory).toBe(path.dirname(captures[0].filePath));
expect(logger.info).toHaveBeenCalledWith(
{ output: 'Stopped before recording began.' },
'No network capture was recorded for SIM-B.'
);
});
it('stops followers in parallel', async () => {
let stopping = 0;
let mostAtOnce = 0;
stopFollower.mockImplementation(async () => {
stopping += 1;
mostAtOnce = Math.max(mostAtOnce, stopping);
await delay(20);
stopping -= 1;
});
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await writeServerAsync('SIM-B', { url: 'http://127.0.0.1:4200', token: 'token-b' });
await ServeSimNetworkCaptureRecorder.startAsync({ logger, env, stateDir, pollIntervalMs: 10 });
await waitForFollowersAsync(2);
await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
expect(mostAtOnce).toBe(2);
});
it('keeps collecting when a follower cannot be stopped', async () => {
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({ logger, env, stateDir, pollIntervalMs: 10 });
await waitForFollowersAsync(1);
stopFollower.mockRejectedValueOnce(new Error('EPERM'));
await expect(ServeSimNetworkCaptureRecorder.finishAsync({ logger })).resolves.toEqual({
outputDirectory: expect.any(String),
captures: [],
});
expect(logger.warn).toHaveBeenCalledWith(
{ err: expect.objectContaining({ message: 'EPERM' }) },
'Could not stop the network capture follower for SIM-A.'
);
});
it('returns nothing when the recorder never started', async () => {
await expect(ServeSimNetworkCaptureRecorder.finishAsync({ logger })).resolves.toEqual({
outputDirectory: null,
captures: [],
});
});
describe('restarting followers', () => {
const exits: (Error | undefined)[] = [];
beforeEach(() => {
exits.length = 0;
jest.mocked(spawnDetached).mockImplementation(() => {
const index = exits.push(undefined) - 1;
return {
pid: 1234,
getOutput: () => 'Network capture is not enabled on this device.',
getExitError: () => exits[index],
stopAsync: stopFollower,
};
});
});
function outPath(call: number): string {
const args = followerArgs()[call];
return args[args.indexOf('-o') + 1];
}
it('starts another follower when one exits before capture was on, and drops the empty one', async () => {
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
stateDir,
pollIntervalMs: 10,
idleRestartIntervalMs: 30,
});
await waitForFollowersAsync(1);
exits[0] = new Error('Process exited with code 1.');
await waitForFollowersAsync(2);
expect(outPath(1)).toMatch(/SIM-A-2\.har$/);
record(outPath(1), 1);
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
expect(captures).toEqual([{ udid: 'SIM-A', filePath: outPath(1), size: 25 }]);
expect(stopFollower).toHaveBeenCalledTimes(1);
});
it('keeps a recording when its stream drops and records the rest in a new part', async () => {
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
stateDir,
pollIntervalMs: 10,
restartIntervalMs: 30,
});
await waitForFollowersAsync(1);
record(outPath(0), 2);
exits[0] = new Error('Process exited with code 1.');
await waitForFollowersAsync(2);
record(outPath(1), 1);
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
expect(captures).toEqual([
{ udid: 'SIM-A', filePath: outPath(0), size: 28 },
{ udid: 'SIM-A', filePath: outPath(1), size: 25 },
]);
});
describe('when a new follower replays the requests serve-sim holds', () => {
const r1 = { id: 'r1', startedAt: 1_000 };
const r2 = { id: 'r2', startedAt: 2_000 };
async function startAsync(): Promise<void> {
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
stateDir,
pollIntervalMs: 10,
restartIntervalMs: 30,
});
await waitForFollowersAsync(1);
}
it('drops a part that holds only replayed requests', async () => {
await startAsync();
recordRequests(outPath(0), [r2, r1]);
exits[0] = new Error('Process exited with code 1.');
await waitForFollowersAsync(2);
recordRequests(outPath(1), [r2, r1]);
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
expect(captures.map(capture => capture.filePath)).toEqual([outPath(0)]);
});
it('keeps only the new requests in a later part, in start order', async () => {
await startAsync();
recordRequests(outPath(0), [r1]);
exits[0] = new Error('Process exited with code 1.');
await waitForFollowersAsync(2);
// A request from a later capture session reuses the id r1 with another start time.
const r1Again = { id: 'r1', startedAt: 4_000 };
recordRequests(outPath(1), [r1Again, r1, r2]);
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
expect(captures.map(capture => capture.filePath)).toEqual([outPath(0), outPath(1)]);
const har = await readHarAsync(outPath(1));
expect(har.log.creator).toEqual({ name: '@expo/serve-sim', version: '0.10.2' });
expect(har.log.entries.map((entry: any) => entry._captureStartedAt)).toEqual([2_000, 4_000]);
expect(captures[1].size).toBe((await readFile(outPath(1))).length);
});
it('keeps the requests a killed follower logged before its HAR caught up', async () => {
const r3 = { id: 'r3', startedAt: 3_000 };
await startAsync();
// serve-sim writes the entry log before it rebuilds the HAR, so a killed follower's HAR can
// lack r2 although its entry log has it.
recordRequests(outPath(0), [r1]);
appendFileSync(
outPath(0).replace(/\.har$/, '.entries.ndjson'),
`${JSON.stringify(entryFor(r2))}\n`
);
exits[0] = new Error('Process exited with code 1.');
await waitForFollowersAsync(2);
recordRequests(outPath(1), [r1, r2, r3]);
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
expect(captures.map(capture => capture.filePath)).toEqual([outPath(0), outPath(1)]);
const ids = async (harPath: string): Promise<string[]> =>
(await readHarAsync(harPath)).log.entries.map((entry: any) => entry._captureId);
expect(await ids(outPath(0))).toEqual(['r1', 'r2']);
expect(await ids(outPath(1))).toEqual(['r3']);
});
it('leaves out a line a killed follower cut off', async () => {
await startAsync();
recordRequests(outPath(0), [r1]);
appendFileSync(outPath(0).replace(/\.har$/, '.entries.ndjson'), '{"startedDateTime":"20');
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
expect(captures.map(capture => capture.filePath)).toEqual([outPath(0)]);
const har = await readHarAsync(outPath(0));
expect(har.log.entries.map((entry: any) => entry._captureId)).toEqual(['r1']);
});
it('removes the files of a part that holds only replayed requests', async () => {
await startAsync();
recordRequests(outPath(0), [r1]);
exits[0] = new Error('Process exited with code 1.');
await waitForFollowersAsync(2);
recordRequests(outPath(1), [r1]);
const replayedFiles = [
outPath(1),
outPath(1).replace(/\.har$/, '.entries.ndjson'),
outPath(1).replace(/\.har$/, '.network-capture.json'),
`${outPath(1)}.0f7c2a4e-9d1b-4c3a-8e5f-6a7b8c9d0e1f.seed.tmp`,
];
for (const file of replayedFiles.slice(2)) {
writeFileSync(file, '{}');
}
exits[1] = new Error('Process exited with code 1.');
await waitForFollowersAsync(3);
expect(replayedFiles.filter(file => existsSync(file))).toEqual([]);
expect(existsSync(outPath(0))).toBe(true);
});
it('does not use a recording slot for followers that recorded no new request', async () => {
jest.mocked(spawnDetached).mockImplementation(({ args }) => {
recordRequests(args[args.indexOf('-o') + 1], [r1]);
return {
pid: 1234,
getOutput: () => '',
getExitError: () => new Error('Process exited with code 1.'),
stopAsync: stopFollower,
};
});
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
stateDir,
pollIntervalMs: 1,
restartIntervalMs: 0,
});
for (let i = 0; i < 300 && jest.mocked(spawnDetached).mock.calls.length < 25; i++) {
await delay(10);
}
expect(jest.mocked(spawnDetached).mock.calls.length).toBeGreaterThanOrEqual(25);
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
expect(captures.map(capture => capture.filePath)).toEqual([outPath(0)]);
expect(logger.warn).not.toHaveBeenCalledWith(
'Network capture reached its limit of 20 recordings; recorded captures will be retained.'
);
});
});
it('waits longer to replace a follower that recorded nothing than one that recorded requests', async () => {
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
stateDir,
pollIntervalMs: 10,
restartIntervalMs: 30,
idleRestartIntervalMs: 60_000,
});
await waitForFollowersAsync(1);
exits[0] = new Error('Process exited with code 1.');
await delay(100);
expect(spawnDetached).toHaveBeenCalledTimes(1);
record(outPath(0), 1);
await waitForFollowersAsync(2);
});
it('drops an empty follower from an earlier serve-sim when serve-sim restarts', async () => {
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({ logger, env, stateDir, pollIntervalMs: 10 });
await waitForFollowersAsync(1);
exits[0] = new Error('Process exited with code 1.');
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-restarted' });
await waitForFollowersAsync(2);
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
expect(captures).toEqual([]);
// Only the new follower is left to stop, and the device is reported once.
expect(stopFollower).toHaveBeenCalledTimes(1);
expect(
jest
.mocked(logger.info)
.mock.calls.filter(
([, message]) => message === 'No network capture was recorded for SIM-A.'
)
).toHaveLength(1);
});
it('waits 30 s by default before replacing a follower that recorded nothing', async () => {
const startedAt = Date.now();
const now = jest.spyOn(Date, 'now');
try {
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
stateDir,
pollIntervalMs: 10,
restartIntervalMs: 0,
});
await waitForFollowersAsync(1);
exits[0] = new Error('Process exited with code 1.');
now.mockReturnValue(startedAt + 29_000);
await delay(50);
expect(spawnDetached).toHaveBeenCalledTimes(1);
now.mockReturnValue(startedAt + 31_000);
await waitForFollowersAsync(2);
} finally {
now.mockRestore();
}
});
it('stops starting followers once 20 HARs hold requests', async () => {
jest.mocked(spawnDetached).mockImplementation(({ args }) => {
record(args[args.indexOf('-o') + 1], 1);
return {
pid: 1234,
getOutput: () => '',
getExitError: () => new Error('Process exited with code 1.'),
stopAsync: stopFollower,
};
});
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
stateDir,
pollIntervalMs: 1,
restartIntervalMs: 0,
});
await waitForFollowersAsync(20);
await delay(50);
expect(spawnDetached).toHaveBeenCalledTimes(20);
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
expect(captures).toHaveLength(20);
expect(logger.warn).toHaveBeenCalledTimes(1);
expect(logger.warn).toHaveBeenCalledWith(
'Network capture reached its limit of 20 recordings; recorded captures will be retained.'
);
});
});
it('keeps polling after a follower fails to start, and retries on the next poll', async () => {
jest.mocked(spawnDetached).mockImplementationOnce(() => {
throw new Error('spawn EAGAIN');
});
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
stateDir,
pollIntervalMs: 10,
restartIntervalMs: 60_000,
idleRestartIntervalMs: 60_000,
});
await waitForFollowersAsync(2);
expect(logger.warn).toHaveBeenCalledWith(
{ err: expect.objectContaining({ message: 'spawn EAGAIN' }) },
'Could not start the network capture follower for SIM-A; retrying.'
);
expect(followerArgs()[1]).toContainEqual(expect.stringMatching(/SIM-A-2\.har$/));
});
it('bounds followers that record nothing, warns once, and retries a new server identity', async () => {
jest.mocked(spawnDetached).mockImplementation(() => ({
pid: 1234,
getOutput: () => 'npm error: the requested serve-sim package was not found',
getExitError: () => new Error('Process exited with code 1.'),
stopAsync: stopFollower,
}));
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
stateDir,
pollIntervalMs: 1,
idleRestartIntervalMs: 0,
});
// Runs that recorded nothing do not use up the 20 HARs that may hold requests.
await waitForFollowersAsync(120);
await delay(50);
expect(spawnDetached).toHaveBeenCalledTimes(120);
const warnings = jest
.mocked(logger.warn)
.mock.calls.filter(([, message]) =>
String(message).startsWith('Stopped retrying network capture')
);
expect(warnings).toEqual([
[
{ output: 'npm error: the requested serve-sim package was not found' },
'Stopped retrying network capture for SIM-A after 120 attempts; recorded captures will be retained.',
],
]);
jest.mocked(spawnDetached).mockImplementation(() => ({
pid: 1234,
getOutput: () => '',
getExitError: () => undefined,
stopAsync: stopFollower,
}));
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'new-token' });
await waitForFollowersAsync(121);
await delay(50);
expect(spawnDetached).toHaveBeenCalledTimes(121);
expect(followerArgs()[120]).toContainEqual(expect.stringMatching(/SIM-A-121\.har$/));
});
it('keeps a running empty follower waiting without spending more attempts', async () => {
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
stateDir,
pollIntervalMs: 1,
restartIntervalMs: 0,
idleRestartIntervalMs: 0,
});
await waitForFollowersAsync(1);
await delay(50);
expect(spawnDetached).toHaveBeenCalledTimes(1);
expect(logger.warn).not.toHaveBeenCalled();
});
@@ -47,6 +47,7 @@ import {
IosSimulatorRecordingUtils,
SERVE_SIM_STOP_GRACE_PERIOD_MS,
} from './IosSimulatorRecordingUtils';
import { ServeSimCrashesRecorder } from './serveSimCrashesRecorder';
import { SERVE_SIM_STATE_DIR, readServeSimServersAsync } from './serveSimMetricsRecorder';
import { startLogPhase } from '../../utils/logPhase';
import { runServeSimActionAsync, stageServeSimAppAsync } from './serveSimActions';
@@ -128,7 +129,7 @@ export function corsOriginArgs(corsOrigins: readonly string[]): string[] {
return corsOrigins.flatMap(origin => ['--cors-origin', origin]);
}
function createServeSimPackageSpec(packageVersion: string | undefined): string {
export function createServeSimPackageSpec(packageVersion: string | undefined): string {
return `${SERVE_SIM_PACKAGE_NAME}@${packageVersion ?? 'latest'}`;
}
@@ -1175,6 +1176,8 @@ async function finishDeviceSessionHostAsync(
logger,
});
}
// Crash reports are read from serve-sim, so collection finishes before it stops.
await ServeSimCrashesRecorder.stopAsync();
let hostStopped = false;
try {
await previewServer.stopAsync();
@@ -64,7 +64,7 @@ export async function updateVersionsAsync(
targetName,
buildConfiguration,
});
const infoPlist = xcBuildConfiguration.buildSettings.INFOPLIST_FILE;
const infoPlist = xcBuildConfiguration!.buildSettings.INFOPLIST_FILE;
if (infoPlist) {
const evaluatedInfoPlistPath = trimQuotes(
evaluateTemplateString(infoPlist, {
@@ -3,7 +3,7 @@ import { BuildStepEnv } from '@expo/steps';
import spawn, { SpawnResult } from '@expo/turtle-spawn';
import path from 'path';
import { COMMON_FASTLANE_ENV } from '../../../common/fastlane';
import { COMMON_FASTLANE_ENV, DEFAULT_FASTLANE_GYM_ENV } from '../../../common/fastlane';
import { XcodeBuildLogger } from '../../../common/xcpretty';
export async function runFastlaneGym({
@@ -25,7 +25,7 @@ export async function runFastlaneGym({
await runFastlane(['gym'], {
cwd: path.join(workingDir, 'ios'),
logger,
env,
env: { ...DEFAULT_FASTLANE_GYM_ENV, ...env },
extraEnv,
});
} finally {
@@ -20,5 +20,5 @@ export async function isTVOS({
targetName,
buildConfiguration,
});
return xcBuildConfiguration?.buildSettings?.SDKROOT?.includes('appletv');
return xcBuildConfiguration?.buildSettings?.SDKROOT?.includes('appletv') ?? false;
}
@@ -0,0 +1,761 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objects = {
/* Begin PBXAggregateTarget section */
AA0972AD056CF1AA745384D9 /* Lint */ = {
isa = PBXAggregateTarget;
buildConfigurationList = 37F79570590137683618CC14 /* Build configuration list for PBXAggregateTarget "Lint" */;
buildPhases = (
);
dependencies = (
);
name = Lint;
};
/* End PBXAggregateTarget section */
/* Begin PBXBuildFile section */
144EE44844237E8D1BAD0B92 /* Greeting.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2D3FA1A9A20E3DBA95E17837 /* Greeting.swift */; };
2218D7F88BCBE6C2D4177A78 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6478BC5E0C545D3EC92F5EA9 /* Foundation.framework */; };
23ADF4ADC2937631265FD29B /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6478BC5E0C545D3EC92F5EA9 /* Foundation.framework */; };
31175A6A1677527EEB0EED05 /* Widget.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 51A5C364F3CFE932AF83CAB2 /* Widget.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
5F0DE6FE8D331C264105CBA3 /* Core.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 7FF3D9921A8A29C50D4B07B7 /* Core.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
82BED379719AC2CE6F2393A2 /* NativeApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 65DA6C73F53AD6CC7C332321 /* NativeApp.swift */; };
894365371155CA33659EDB82 /* Support.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2A7B5AFEDD988A449721494 /* Support.swift */; };
B6AE519B17BF24827B395062 /* GreetingWidget.swift in Sources */ = {isa = PBXBuildFile; fileRef = A66B51AE6ACE9B9B488C8A41 /* GreetingWidget.swift */; };
CE4544811A89EFEDEDDF9412 /* Core.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7FF3D9921A8A29C50D4B07B7 /* Core.framework */; };
F3C25B06A9F92BF85C99ADF6 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6478BC5E0C545D3EC92F5EA9 /* Foundation.framework */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
375E604E1CA2168C5E822022 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = C75C66BBF3354F3049AAA60E /* Project object */;
proxyType = 1;
remoteGlobalIDString = 5CAE5500641C3F327B201839;
remoteInfo = Widget;
};
471B7528B0221F80F79A25C5 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = C75C66BBF3354F3049AAA60E /* Project object */;
proxyType = 1;
remoteGlobalIDString = AA0972AD056CF1AA745384D9;
remoteInfo = Lint;
};
47FB00078332DE52B8D7255A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = C75C66BBF3354F3049AAA60E /* Project object */;
proxyType = 1;
remoteGlobalIDString = 296D4EDB5005323FF2B08181;
remoteInfo = Support;
};
A7003A6658D89F6E78E36826 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = C75C66BBF3354F3049AAA60E /* Project object */;
proxyType = 1;
remoteGlobalIDString = BBCC7F97904CEBE3743A2D6F;
remoteInfo = Core;
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
46CDA025D9DC4A61CB3AB9AF /* Embed Frameworks */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 10;
files = (
5F0DE6FE8D331C264105CBA3 /* Core.framework in Embed Frameworks */,
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
};
9C91122BAB8FFE27175072EF /* Embed Foundation Extensions */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 13;
files = (
31175A6A1677527EEB0EED05 /* Widget.appex in Embed Foundation Extensions */,
);
name = "Embed Foundation Extensions";
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
11DE2FF23E4AC6F76FABBB1D /* libSupport.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libSupport.a; sourceTree = BUILT_PRODUCTS_DIR; };
2D3FA1A9A20E3DBA95E17837 /* Greeting.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Greeting.swift; path = Core/Greeting.swift; sourceTree = "<group>"; };
47DA19BCE076B15FEA9B79A1 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; name = Info.plist; path = Widget/Info.plist; sourceTree = "<group>"; };
51A5C364F3CFE932AF83CAB2 /* Widget.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = Widget.appex; sourceTree = BUILT_PRODUCTS_DIR; };
6478BC5E0C545D3EC92F5EA9 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS18.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; };
65DA6C73F53AD6CC7C332321 /* NativeApp.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NativeApp.swift; path = NativeApp/NativeApp.swift; sourceTree = "<group>"; };
7FF3D9921A8A29C50D4B07B7 /* Core.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Core.framework; sourceTree = BUILT_PRODUCTS_DIR; };
A2A7B5AFEDD988A449721494 /* Support.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Support.swift; path = Support/Support.swift; sourceTree = "<group>"; };
A66B51AE6ACE9B9B488C8A41 /* GreetingWidget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GreetingWidget.swift; path = Widget/GreetingWidget.swift; sourceTree = "<group>"; };
AA231F722FEC2EB357212099 /* NativeApp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = NativeApp.app; sourceTree = BUILT_PRODUCTS_DIR; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
2056D3AA5D49B17DC0153CB0 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
F3C25B06A9F92BF85C99ADF6 /* Foundation.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
6EC16D28E54F8F68FE086D37 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
23ADF4ADC2937631265FD29B /* Foundation.framework in Frameworks */,
CE4544811A89EFEDEDDF9412 /* Core.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
C44CDCD723A2DAA347D04C7A /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
2218D7F88BCBE6C2D4177A78 /* Foundation.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
C5D938C3A819B40682F51DD1 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
32A67717355E8BF242ED1F13 /* Frameworks */ = {
isa = PBXGroup;
children = (
33825DA984E9128A82ED505C /* iOS */,
);
name = Frameworks;
sourceTree = "<group>";
};
33825DA984E9128A82ED505C /* iOS */ = {
isa = PBXGroup;
children = (
6478BC5E0C545D3EC92F5EA9 /* Foundation.framework */,
);
name = iOS;
sourceTree = "<group>";
};
3CEA16253E62954CB779B248 /* Products */ = {
isa = PBXGroup;
children = (
AA231F722FEC2EB357212099 /* NativeApp.app */,
51A5C364F3CFE932AF83CAB2 /* Widget.appex */,
7FF3D9921A8A29C50D4B07B7 /* Core.framework */,
11DE2FF23E4AC6F76FABBB1D /* libSupport.a */,
);
name = Products;
sourceTree = "<group>";
};
E6417B2588EE50DE15C4D4D1 = {
isa = PBXGroup;
children = (
3CEA16253E62954CB779B248 /* Products */,
32A67717355E8BF242ED1F13 /* Frameworks */,
65DA6C73F53AD6CC7C332321 /* NativeApp.swift */,
A66B51AE6ACE9B9B488C8A41 /* GreetingWidget.swift */,
2D3FA1A9A20E3DBA95E17837 /* Greeting.swift */,
A2A7B5AFEDD988A449721494 /* Support.swift */,
47DA19BCE076B15FEA9B79A1 /* Info.plist */,
);
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXHeadersBuildPhase section */
7EC7463F6E7F782E448DAFA5 /* Headers */ = {
isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
B29686537EC43AD1F01306E0 /* Headers */ = {
isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXHeadersBuildPhase section */
/* Begin PBXNativeTarget section */
2870BA69F546F142D461562E /* NativeApp */ = {
isa = PBXNativeTarget;
buildConfigurationList = 04088B0315B894E16A5BDA25 /* Build configuration list for PBXNativeTarget "NativeApp" */;
buildPhases = (
BA163C68DE3F2AEA1D1DCF95 /* Sources */,
6EC16D28E54F8F68FE086D37 /* Frameworks */,
4B0841232EC55F472FAA0ECC /* Resources */,
46CDA025D9DC4A61CB3AB9AF /* Embed Frameworks */,
9C91122BAB8FFE27175072EF /* Embed Foundation Extensions */,
);
buildRules = (
);
dependencies = (
E3FBA1ECC518F70A99D92C03 /* PBXTargetDependency */,
4757AF74BA80578D6EF06225 /* PBXTargetDependency */,
485D98E6FE58D82F919C302B /* PBXTargetDependency */,
243A10E40BACFB1588AC5DF1 /* PBXTargetDependency */,
);
name = NativeApp;
productName = NativeApp;
productReference = AA231F722FEC2EB357212099 /* NativeApp.app */;
productType = "com.apple.product-type.application";
};
296D4EDB5005323FF2B08181 /* Support */ = {
isa = PBXNativeTarget;
buildConfigurationList = D1B4C46B47DDA87E6589E8CA /* Build configuration list for PBXNativeTarget "Support" */;
buildPhases = (
B29686537EC43AD1F01306E0 /* Headers */,
BC6C693DF6787CE4EC4DB31D /* Sources */,
C5D938C3A819B40682F51DD1 /* Frameworks */,
);
buildRules = (
);
dependencies = (
);
name = Support;
productName = Support;
productReference = 11DE2FF23E4AC6F76FABBB1D /* libSupport.a */;
productType = "com.apple.product-type.library.static";
};
5CAE5500641C3F327B201839 /* Widget */ = {
isa = PBXNativeTarget;
buildConfigurationList = 87AF324C840AE3D7583DD7B8 /* Build configuration list for PBXNativeTarget "Widget" */;
buildPhases = (
99EF0AFFD1109F2B91CC1EAC /* Sources */,
C44CDCD723A2DAA347D04C7A /* Frameworks */,
0E24870040684F507D97FDE5 /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = Widget;
productName = Widget;
productReference = 51A5C364F3CFE932AF83CAB2 /* Widget.appex */;
productType = "com.apple.product-type.app-extension";
};
BBCC7F97904CEBE3743A2D6F /* Core */ = {
isa = PBXNativeTarget;
buildConfigurationList = F6DEF016482C0375FB3B61AF /* Build configuration list for PBXNativeTarget "Core" */;
buildPhases = (
7EC7463F6E7F782E448DAFA5 /* Headers */,
AB5CD0C037E2DD1858A66377 /* Sources */,
2056D3AA5D49B17DC0153CB0 /* Frameworks */,
7CD44BD0D12AD945AA08FD50 /* Resources */,
);
buildRules = (
);
dependencies = (
54E7D4DE151ABCD6F98FF82E /* PBXTargetDependency */,
);
name = Core;
productName = Core;
productReference = 7FF3D9921A8A29C50D4B07B7 /* Core.framework */;
productType = "com.apple.product-type.framework";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
C75C66BBF3354F3049AAA60E /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 1600;
};
buildConfigurationList = B0BEA4AA6955A5973605EE5C /* Build configuration list for PBXProject "NativeApp" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = E6417B2588EE50DE15C4D4D1;
minimizedProjectReferenceProxies = 0;
preferredProjectObjectVersion = 77;
productRefGroup = 3CEA16253E62954CB779B248 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
2870BA69F546F142D461562E /* NativeApp */,
5CAE5500641C3F327B201839 /* Widget */,
BBCC7F97904CEBE3743A2D6F /* Core */,
296D4EDB5005323FF2B08181 /* Support */,
AA0972AD056CF1AA745384D9 /* Lint */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
0E24870040684F507D97FDE5 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
4B0841232EC55F472FAA0ECC /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
7CD44BD0D12AD945AA08FD50 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
99EF0AFFD1109F2B91CC1EAC /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
B6AE519B17BF24827B395062 /* GreetingWidget.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
AB5CD0C037E2DD1858A66377 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
144EE44844237E8D1BAD0B92 /* Greeting.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
BA163C68DE3F2AEA1D1DCF95 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
82BED379719AC2CE6F2393A2 /* NativeApp.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
BC6C693DF6787CE4EC4DB31D /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
894365371155CA33659EDB82 /* Support.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
243A10E40BACFB1588AC5DF1 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
productRef = D4740D82A230FFA7F1D439B2 /* plugin:LintPlugin */;
};
4757AF74BA80578D6EF06225 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = Core;
target = BBCC7F97904CEBE3743A2D6F /* Core */;
targetProxy = A7003A6658D89F6E78E36826 /* PBXContainerItemProxy */;
};
485D98E6FE58D82F919C302B /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = Lint;
target = AA0972AD056CF1AA745384D9 /* Lint */;
targetProxy = 471B7528B0221F80F79A25C5 /* PBXContainerItemProxy */;
};
54E7D4DE151ABCD6F98FF82E /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = Support;
target = 296D4EDB5005323FF2B08181 /* Support */;
targetProxy = 47FB00078332DE52B8D7255A /* PBXContainerItemProxy */;
};
E3FBA1ECC518F70A99D92C03 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = Widget;
target = 5CAE5500641C3F327B201839 /* Widget */;
targetProxy = 375E604E1CA2168C5E822022 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
0A5BC5CAC395DFF87A92041A /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_OBJC_WEAK = NO;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 7;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = Widget/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
MARKETING_VERSION = 1.2;
PRODUCT_BUNDLE_IDENTIFIER = dev.expo.nativeapp.widget;
SDKROOT = iphoneos;
SKIP_INSTALL = YES;
SWIFT_VERSION = 5.0;
};
name = Debug;
};
0AB93216703FC0D37CA3CF32 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_OBJC_WEAK = NO;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 7;
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
GENERATE_INFOPLIST_FILE = YES;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
MARKETING_VERSION = 1.2;
PRODUCT_BUNDLE_IDENTIFIER = dev.expo.nativeapp.core;
PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)";
SDKROOT = iphoneos;
SKIP_INSTALL = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
name = Debug;
};
15B0373638DA4E491112500A /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
};
name = Release;
};
2D67EBD1D908CD52AFB8120A /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_OBJC_WEAK = NO;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 7;
GENERATE_INFOPLIST_FILE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
MARKETING_VERSION = 1.2;
OTHER_LDFLAGS = "-ObjC";
SDKROOT = iphoneos;
SKIP_INSTALL = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
3673C8DB14C31D877D76DB6E /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
};
name = Debug;
};
53E857695AF3FF267C15C534 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
SWIFT_VERSION = 5.0;
};
name = Release;
};
6A00D3809325A3FAA6DB3D7F /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
};
name = Debug;
};
87A6150656443BAE41AF0B13 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_OBJC_WEAK = NO;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 7;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = Widget/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
MARKETING_VERSION = 1.2;
PRODUCT_BUNDLE_IDENTIFIER = dev.expo.nativeapp.widget;
SDKROOT = iphoneos;
SKIP_INSTALL = YES;
SWIFT_VERSION = 5.0;
VALIDATE_PRODUCT = YES;
};
name = Release;
};
AF27A794370D7C64D912580A /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CLANG_ENABLE_OBJC_WEAK = NO;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 7;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
MARKETING_VERSION = 1.2;
PRODUCT_BUNDLE_IDENTIFIER = dev.expo.nativeapp;
SDKROOT = iphoneos;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
D9A85F0620A7FF71CAF47739 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_OBJC_WEAK = NO;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 7;
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
GENERATE_INFOPLIST_FILE = YES;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
MARKETING_VERSION = 1.2;
PRODUCT_BUNDLE_IDENTIFIER = dev.expo.nativeapp.core;
PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)";
SDKROOT = iphoneos;
SKIP_INSTALL = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
name = Release;
};
D9BC3BDC445700C84377561C /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CLANG_ENABLE_OBJC_WEAK = NO;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 7;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
MARKETING_VERSION = 1.2;
PRODUCT_BUNDLE_IDENTIFIER = dev.expo.nativeapp;
SDKROOT = iphoneos;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
};
name = Release;
};
FB2D52D62F852BBD5D3E2573 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_OBJC_WEAK = NO;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 7;
GENERATE_INFOPLIST_FILE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
MARKETING_VERSION = 1.2;
OTHER_LDFLAGS = "-ObjC";
SDKROOT = iphoneos;
SKIP_INSTALL = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
04088B0315B894E16A5BDA25 /* Build configuration list for PBXNativeTarget "NativeApp" */ = {
isa = XCConfigurationList;
buildConfigurations = (
D9BC3BDC445700C84377561C /* Release */,
AF27A794370D7C64D912580A /* Debug */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
37F79570590137683618CC14 /* Build configuration list for PBXAggregateTarget "Lint" */ = {
isa = XCConfigurationList;
buildConfigurations = (
15B0373638DA4E491112500A /* Release */,
6A00D3809325A3FAA6DB3D7F /* Debug */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
87AF324C840AE3D7583DD7B8 /* Build configuration list for PBXNativeTarget "Widget" */ = {
isa = XCConfigurationList;
buildConfigurations = (
87A6150656443BAE41AF0B13 /* Release */,
0A5BC5CAC395DFF87A92041A /* Debug */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
B0BEA4AA6955A5973605EE5C /* Build configuration list for PBXProject "NativeApp" */ = {
isa = XCConfigurationList;
buildConfigurations = (
3673C8DB14C31D877D76DB6E /* Debug */,
53E857695AF3FF267C15C534 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
D1B4C46B47DDA87E6589E8CA /* Build configuration list for PBXNativeTarget "Support" */ = {
isa = XCConfigurationList;
buildConfigurations = (
FB2D52D62F852BBD5D3E2573 /* Release */,
2D67EBD1D908CD52AFB8120A /* Debug */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
F6DEF016482C0375FB3B61AF /* Build configuration list for PBXNativeTarget "Core" */ = {
isa = XCConfigurationList;
buildConfigurations = (
D9A85F0620A7FF71CAF47739 /* Release */,
0AB93216703FC0D37CA3CF32 /* Debug */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCSwiftPackageProductDependency section */
D4740D82A230FFA7F1D439B2 /* plugin:LintPlugin */ = {
isa = XCSwiftPackageProductDependency;
productName = "plugin:LintPlugin";
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = C75C66BBF3354F3049AAA60E /* Project object */;
}
@@ -0,0 +1,87 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1600"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2870BA69F546F142D461562E"
BuildableName = "NativeApp.app"
BlueprintName = "NativeApp"
ReferencedContainer = "container:NativeApp.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2870BA69F546F142D461562E"
BuildableName = "NativeApp.app"
BlueprintName = "NativeApp"
ReferencedContainer = "container:NativeApp.xcodeproj">
</BuildableReference>
</MacroExpansion>
<Testables>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2870BA69F546F142D461562E"
BuildableName = "NativeApp.app"
BlueprintName = "NativeApp"
ReferencedContainer = "container:NativeApp.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2870BA69F546F142D461562E"
BuildableName = "NativeApp.app"
BlueprintName = "NativeApp"
ReferencedContainer = "container:NativeApp.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,77 @@
import { vol } from 'memfs';
import path from 'path';
import {
findApplicationTargetById,
findDependencyTargets,
getBuildConfigurations,
openXcodeProject,
} from '../pbxproj';
const originalFs = jest.requireActual('fs');
const APPLICATION_TARGET_ID = '2870BA69F546F142D461562E';
const FRAMEWORK_TARGET_ID = 'BBCC7F97904CEBE3743A2D6F';
const AGGREGATE_TARGET_ID = 'AA0972AD056CF1AA745384D9';
function openFixtureProject(): ReturnType<typeof openXcodeProject> {
vol.fromJSON({
'/project/NativeApp.xcodeproj/project.pbxproj': originalFs.readFileSync(
path.join(__dirname, 'fixtures/native-app.pbxproj'),
'utf-8'
),
});
return openXcodeProject('/project/NativeApp.xcodeproj');
}
afterEach(() => {
vol.reset();
});
describe(openXcodeProject, () => {
it('fails with the path when the project file cannot be parsed', () => {
vol.fromJSON({ '/project/Broken.xcodeproj/project.pbxproj': 'not a project file' });
expect(() => openXcodeProject('/project/Broken.xcodeproj')).toThrow(
expect.objectContaining({
errorCode: 'NATIVE_XCODE_PROJECT_UNREADABLE',
message: expect.stringContaining('/project/Broken.xcodeproj/project.pbxproj'),
})
);
});
});
describe(findApplicationTargetById, () => {
it('returns an application target', () => {
expect(findApplicationTargetById(openFixtureProject(), APPLICATION_TARGET_ID)).toEqual({
id: APPLICATION_TARGET_ID,
name: 'NativeApp',
});
});
it.each([
['a framework target', FRAMEWORK_TARGET_ID],
['an aggregate target', AGGREGATE_TARGET_ID],
['an unknown id', 'UNKNOWN'],
])('returns nothing for %s', (_description, targetId) => {
expect(findApplicationTargetById(openFixtureProject(), targetId)).toBeUndefined();
});
});
describe(findDependencyTargets, () => {
it('returns the targets a target depends on at any depth, without aggregate targets and Swift package products', () => {
expect(findDependencyTargets(openFixtureProject(), APPLICATION_TARGET_ID)).toEqual([
{ id: '5CAE5500641C3F327B201839', name: 'Widget' },
{ id: FRAMEWORK_TARGET_ID, name: 'Core' },
{ id: '296D4EDB5005323FF2B08181', name: 'Support' },
]);
});
});
describe(getBuildConfigurations, () => {
it('returns the build configurations of a target', () => {
expect(
getBuildConfigurations(openFixtureProject(), APPLICATION_TARGET_ID).map(({ name }) => name)
).toEqual(['Debug', 'Release']);
});
});
@@ -0,0 +1,89 @@
import { vol } from 'memfs';
import { resolveProjectFilePathAsync } from '../projectFile';
const projectDirectory = '/project';
function createDirectories(...names: string[]): void {
vol.fromJSON(
Object.fromEntries(names.map(name => [`${name}/placeholder`, ''])),
projectDirectory
);
}
afterEach(() => {
vol.reset();
});
describe(resolveProjectFilePathAsync, () => {
it('uses the only workspace, also when the directory has a project', async () => {
createDirectories('App.xcworkspace', 'App.xcodeproj', 'Pods');
await expect(resolveProjectFilePathAsync(projectDirectory)).resolves.toBe(
'/project/App.xcworkspace'
);
});
it('uses the only project when the directory has no workspace', async () => {
createDirectories('App.xcodeproj', 'Sources');
await expect(resolveProjectFilePathAsync(projectDirectory)).resolves.toBe(
'/project/App.xcodeproj'
);
});
it('fails with the candidates when the directory has several workspaces', async () => {
createDirectories('B.xcworkspace', 'A.xcworkspace', 'App.xcodeproj');
await expect(resolveProjectFilePathAsync(projectDirectory)).rejects.toMatchObject({
errorCode: 'NATIVE_XCODE_AMBIGUOUS_PROJECT_FILE',
message: expect.stringMatching(
/2 "\.xcworkspace" entries.*A\.xcworkspace, B\.xcworkspace.*"xcode_project_file"/
),
});
});
it('fails with the candidates when the directory has several projects and no workspace', async () => {
createDirectories('App.xcodeproj', 'Tools.xcodeproj');
await expect(resolveProjectFilePathAsync(projectDirectory)).rejects.toMatchObject({
errorCode: 'NATIVE_XCODE_AMBIGUOUS_PROJECT_FILE',
message: expect.stringMatching(/2 "\.xcodeproj" entries.*App\.xcodeproj, Tools\.xcodeproj/),
});
});
it('fails when the directory has no workspace and no project', async () => {
createDirectories('Sources');
await expect(resolveProjectFilePathAsync(projectDirectory)).rejects.toMatchObject({
errorCode: 'NATIVE_XCODE_PROJECT_FILE_NOT_FOUND',
});
});
it('uses the given project file, relative to the project directory', async () => {
createDirectories('A.xcworkspace', 'B.xcworkspace', 'apps/App.xcodeproj');
await expect(resolveProjectFilePathAsync(projectDirectory, 'apps/App.xcodeproj')).resolves.toBe(
'/project/apps/App.xcodeproj'
);
});
it('fails when the given project file is not a workspace or a project', async () => {
createDirectories('App.xcodeproj');
await expect(
resolveProjectFilePathAsync(projectDirectory, 'App.xcodeproj/project.pbxproj')
).rejects.toMatchObject({ errorCode: 'NATIVE_XCODE_INVALID_PROJECT_FILE' });
});
it('fails when the given project file does not exist', async () => {
createDirectories('App.xcodeproj');
await expect(
resolveProjectFilePathAsync(projectDirectory, 'App.xcworkspace')
).rejects.toMatchObject({
errorCode: 'NATIVE_XCODE_PROJECT_FILE_NOT_FOUND',
message: expect.stringContaining('/project/App.xcworkspace'),
});
});
});
@@ -0,0 +1,242 @@
import { vol } from 'memfs';
import { createMockLogger } from '../../../../../__tests__/utils/logger';
import { XcodeScheme, findSharedSchemesAsync, readSchemeAsync, selectScheme } from '../schemes';
function createSchemeXml({
buildables,
archiveConfiguration = 'Release',
launchConfiguration = 'Debug',
}: {
buildables: { name: string; product: string; id: string; container: string }[];
archiveConfiguration?: string;
launchConfiguration?: string;
}): string {
const entries = buildables
.map(
({ name, product, id, container }) => `
<BuildActionEntry buildForArchiving = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "${id}"
BuildableName = "${product}"
BlueprintName = "${name}"
ReferencedContainer = "container:${container}">
</BuildableReference>
</BuildActionEntry>`
)
.join('');
return `<?xml version="1.0" encoding="UTF-8"?>
<Scheme LastUpgradeVersion = "1600" version = "1.3">
<BuildAction parallelizeBuildables = "YES">
<BuildActionEntries>${entries}
</BuildActionEntries>
</BuildAction>
<LaunchAction buildConfiguration = "${launchConfiguration}"></LaunchAction>
<ArchiveAction buildConfiguration = "${archiveConfiguration}" revealArchiveInOrganizer = "YES"></ArchiveAction>
</Scheme>`;
}
function createScheme(name: string): XcodeScheme {
return {
name,
path: `/project/App.xcodeproj/xcshareddata/xcschemes/${name}.xcscheme`,
containerPathBase: '/project',
};
}
afterEach(() => {
vol.reset();
});
describe(findSharedSchemesAsync, () => {
it('lists the shared schemes of a project', async () => {
vol.fromJSON({
'/project/App.xcodeproj/xcshareddata/xcschemes/App.xcscheme': '',
'/project/App.xcodeproj/xcshareddata/xcschemes/App Staging.xcscheme': '',
'/project/App.xcodeproj/xcshareddata/xcschemes/xcschememanagement.plist': '',
'/project/App.xcodeproj/xcuserdata/user.xcuserdatad/xcschemes/Private.xcscheme': '',
});
const schemes = await findSharedSchemesAsync('/project/App.xcodeproj');
expect(schemes).toEqual(
expect.arrayContaining([createScheme('App'), createScheme('App Staging')])
);
expect(schemes).toHaveLength(2);
});
it('returns no scheme when the project has no shared scheme', async () => {
vol.fromJSON({ '/project/App.xcodeproj/project.pbxproj': '' });
await expect(findSharedSchemesAsync('/project/App.xcodeproj')).resolves.toEqual([]);
});
it('lists the shared schemes of a workspace and of the projects it references', async () => {
vol.fromJSON({
'/project/App.xcworkspace/contents.xcworkspacedata': `<?xml version="1.0" encoding="UTF-8"?>
<Workspace version = "1.0">
<FileRef location = "group:App.xcodeproj"></FileRef>
<FileRef location = "group:README.md"></FileRef>
<FileRef location = "group:Modules/Core/Core.xcodeproj"></FileRef>
<FileRef location = "container:Tools/Tools.xcodeproj"></FileRef>
</Workspace>`,
'/project/App.xcworkspace/xcshareddata/xcschemes/Everything.xcscheme': '',
'/project/App.xcodeproj/xcshareddata/xcschemes/App.xcscheme': '',
'/project/Modules/Core/Core.xcodeproj/xcshareddata/xcschemes/Core.xcscheme': '',
'/project/Tools/Tools.xcodeproj/xcshareddata/xcschemes/Tools.xcscheme': '',
'/project/Unreferenced.xcodeproj/xcshareddata/xcschemes/Unreferenced.xcscheme': '',
});
const schemes = await findSharedSchemesAsync('/project/App.xcworkspace');
expect(schemes.map(({ name, containerPathBase }) => [name, containerPathBase])).toEqual([
['Everything', '/project'],
['App', '/project'],
['Core', '/project/Modules/Core'],
['Tools', '/project/Tools'],
]);
});
it('lists the shared schemes of the projects that a workspace keeps in groups', async () => {
vol.fromJSON({
'/project/App.xcworkspace/contents.xcworkspacedata': `<?xml version="1.0" encoding="UTF-8"?>
<Workspace version = "1.0">
<Group location = "group:Apps" name = "Apps">
<FileRef location = "group:App/App.xcodeproj"></FileRef>
<FileRef location = "container:Tools/Tools.xcodeproj"></FileRef>
<Group location = "group:Modules" name = "Modules">
<FileRef location = "group:Core.xcodeproj"></FileRef>
</Group>
</Group>
</Workspace>`,
'/project/Apps/App/App.xcodeproj/xcshareddata/xcschemes/App.xcscheme': '',
'/project/Tools/Tools.xcodeproj/xcshareddata/xcschemes/Tools.xcscheme': '',
'/project/Apps/Modules/Core.xcodeproj/xcshareddata/xcschemes/Core.xcscheme': '',
});
const schemes = await findSharedSchemesAsync('/project/App.xcworkspace');
expect(schemes.map(({ name, containerPathBase }) => [name, containerPathBase])).toEqual([
['App', '/project/Apps/App'],
['Tools', '/project/Tools'],
['Core', '/project/Apps/Modules'],
]);
});
it('keeps the scheme of the workspace when a referenced project has a scheme with the same name', async () => {
vol.fromJSON({
'/project/App.xcworkspace/contents.xcworkspacedata':
'<Workspace version = "1.0"><FileRef location = "group:App.xcodeproj"></FileRef></Workspace>',
'/project/App.xcworkspace/xcshareddata/xcschemes/App.xcscheme': '',
'/project/App.xcodeproj/xcshareddata/xcschemes/App.xcscheme': '',
});
await expect(findSharedSchemesAsync('/project/App.xcworkspace')).resolves.toEqual([
{
name: 'App',
path: '/project/App.xcworkspace/xcshareddata/xcschemes/App.xcscheme',
containerPathBase: '/project',
},
]);
});
});
describe(selectScheme, () => {
it('fails when there is no shared scheme', () => {
expect(() => selectScheme([], { logger: createMockLogger() })).toThrow(
expect.objectContaining({ errorCode: 'NATIVE_XCODE_NO_SHARED_SCHEME' })
);
});
it('uses the only shared scheme', () => {
const logger = createMockLogger();
expect(selectScheme([createScheme('App')], { logger })).toEqual(createScheme('App'));
expect(logger.info).not.toHaveBeenCalled();
});
it('uses the first scheme by name whose name does not contain tvOS, and logs the candidates', () => {
const logger = createMockLogger();
const scheme = selectScheme(
[createScheme('Widget'), createScheme('App-tvOS'), createScheme('App')],
{ logger }
);
expect(scheme).toEqual(createScheme('App'));
expect(logger.info).toHaveBeenCalledWith(
'Found 3 shared schemes: App, App-tvOS, Widget. Using "App". Set "xcode_scheme" to build another scheme.'
);
});
it('uses the first scheme by name when every name contains tvOS', () => {
expect(
selectScheme([createScheme('B-tvOS'), createScheme('A-tvOS')], {
logger: createMockLogger(),
})
).toEqual(createScheme('A-tvOS'));
});
it('uses the requested scheme', () => {
expect(
selectScheme([createScheme('App'), createScheme('Widget')], {
requestedName: 'Widget',
logger: createMockLogger(),
})
).toEqual(createScheme('Widget'));
});
it('fails with the candidates when the requested scheme is not shared', () => {
expect(() =>
selectScheme([createScheme('Widget'), createScheme('App')], {
requestedName: 'Missing',
logger: createMockLogger(),
})
).toThrow(
expect.objectContaining({
errorCode: 'NATIVE_XCODE_SCHEME_NOT_FOUND',
message: expect.stringContaining('Shared schemes: App, Widget.'),
})
);
});
});
describe(readSchemeAsync, () => {
it('reads the application target and the configurations', async () => {
const scheme = createScheme('App');
vol.fromJSON({
[scheme.path]: createSchemeXml({
buildables: [
{ name: 'Core', product: 'Core.framework', id: 'CORE', container: 'Core/Core.xcodeproj' },
{ name: 'App', product: 'App.app', id: 'APP', container: 'App.xcodeproj' },
],
archiveConfiguration: 'App Store',
launchConfiguration: 'Development',
}),
});
await expect(readSchemeAsync(scheme)).resolves.toEqual({
applicationTargetReference: { targetId: 'APP', xcodeprojPath: '/project/App.xcodeproj' },
archiveConfiguration: 'App Store',
launchConfiguration: 'Development',
});
});
it('returns no application target when no buildable of the scheme is an application', async () => {
const scheme = createScheme('Core');
vol.fromJSON({
[scheme.path]: createSchemeXml({
buildables: [
{ name: 'Core', product: 'Core.framework', id: 'CORE', container: 'App.xcodeproj' },
],
}),
});
await expect(readSchemeAsync(scheme)).resolves.toEqual({
applicationTargetReference: undefined,
archiveConfiguration: 'Release',
launchConfiguration: 'Debug',
});
});
});
@@ -0,0 +1,85 @@
import { UserError } from '@expo/eas-build-job';
import { bunyan } from '@expo/logger';
import { BuildStepEnv } from '@expo/steps';
import spawn from '@expo/turtle-spawn';
import { z } from 'zod';
const ShowBuildSettingsOutputZ = z.array(
z.object({
target: z.string(),
buildSettings: z.record(z.string(), z.string()),
})
);
interface BuildSettingsQuery {
xcodeprojPath: string;
targetNames: string[];
buildConfiguration: string;
sdk?: string;
env: BuildStepEnv;
logger: bunyan;
}
type BuildSettingsByTargetName = Record<string, Record<string, string>>;
export async function readBuildSettingsByTargetNameAsync(
query: BuildSettingsQuery
): Promise<BuildSettingsByTargetName> {
const buildSettingsByTargetName = await showBuildSettingsAsync(query);
// Without -sdk, xcodebuild resolves no platform for a target that has SDKROOT = auto.
const targetNamesWithoutPlatform = query.targetNames.filter(
targetName => !buildSettingsByTargetName[targetName]?.PLATFORM_NAME
);
if (targetNamesWithoutPlatform.length === 0) {
return buildSettingsByTargetName;
}
return {
...buildSettingsByTargetName,
...(await showBuildSettingsAsync({
...query,
targetNames: targetNamesWithoutPlatform,
sdk: 'iphoneos',
})),
};
}
async function showBuildSettingsAsync({
xcodeprojPath,
targetNames,
buildConfiguration,
sdk,
env,
logger,
}: BuildSettingsQuery): Promise<BuildSettingsByTargetName> {
let stdout: string;
try {
({ stdout } = await spawn(
'xcodebuild',
[
'-project',
xcodeprojPath,
...targetNames.flatMap(targetName => ['-target', targetName]),
'-configuration',
buildConfiguration,
...(sdk ? ['-sdk', sdk] : []),
'-showBuildSettings',
'-json',
],
{ stdio: 'pipe', env }
));
} catch (err: any) {
logger.error(err.stderr || err.stdout || err.message);
throw new UserError(
'NATIVE_XCODE_BUILD_SETTINGS_FAILED',
`xcodebuild could not read the build settings of "${xcodeprojPath}" for the configuration "${buildConfiguration}". The xcodebuild output above has the reason. A common cause is a Swift package or an ".xcconfig" file that cannot be resolved on the builder.`,
{ cause: err }
);
}
return Object.fromEntries(
ShowBuildSettingsOutputZ.parse(JSON.parse(stdout)).map(({ target, buildSettings }) => [
target,
buildSettings,
])
);
}
@@ -0,0 +1,86 @@
import { IOSConfig } from '@expo/config-plugins';
import { UserError } from '@expo/eas-build-job';
import path from 'path';
import {
PBXNativeTarget,
XCBuildConfiguration,
XcodeProject,
project as parseProject,
} from 'xcode';
const { TargetType, getNativeTargets, isTargetOfType } = IOSConfig.Target;
const { getBuildConfigurationsForListId, unquote } = IOSConfig.XcodeUtils;
export interface XcodeTarget {
id: string;
name: string;
}
export interface XcodeTargetWithBundleIdentifier extends XcodeTarget {
bundleIdentifier: string;
}
export function openXcodeProject(xcodeprojPath: string): XcodeProject {
const pbxprojPath = path.join(xcodeprojPath, 'project.pbxproj');
const project = parseProject(pbxprojPath);
try {
project.parseSync();
} catch (err: any) {
throw new UserError(
'NATIVE_XCODE_PROJECT_UNREADABLE',
`Failed to read the Xcode project file "${pbxprojPath}": ${err.message}. Check that the file is committed and that Xcode can open the project.`,
{ cause: err }
);
}
return project;
}
export function findApplicationTargetById(
project: XcodeProject,
targetId: string
): XcodeTarget | undefined {
const target = findNativeTarget(project, targetId);
return target && isTargetOfType(target, TargetType.APPLICATION)
? { id: targetId, name: unquote(target.name) }
: undefined;
}
export function findDependencyTargets(project: XcodeProject, targetId: string): XcodeTarget[] {
const dependencyTargetById = new Map<string, XcodeTarget>();
const visit = (parentTargetId: string): void => {
const dependencies: { value: string }[] =
findNativeTarget(project, parentTargetId)?.dependencies ?? [];
for (const { value: dependencyId } of dependencies) {
const dependency = project.getPBXGroupByKeyAndType(dependencyId, 'PBXTargetDependency') as {
target?: string;
};
const [id, target] =
getNativeTargets(project).find(
([nativeTargetId]) => nativeTargetId === dependency.target
) ?? [];
if (!id || !target || dependencyTargetById.has(id)) {
continue;
}
dependencyTargetById.set(id, { id, name: unquote(target.name) });
visit(id);
}
};
visit(targetId);
return [...dependencyTargetById.values()];
}
export function getBuildConfigurations(
project: XcodeProject,
targetId: string
): XCBuildConfiguration[] {
const target = findNativeTarget(project, targetId);
return target
? getBuildConfigurationsForListId(project, target.buildConfigurationList).map(
([, buildConfiguration]) => buildConfiguration
)
: [];
}
function findNativeTarget(project: XcodeProject, targetId: string): PBXNativeTarget | undefined {
return getNativeTargets(project).find(([id]) => id === targetId)?.[1];
}
@@ -0,0 +1,50 @@
import { UserError } from '@expo/eas-build-job';
import fs from 'node:fs';
import path from 'node:path';
const WORKSPACE_EXTENSION = '.xcworkspace';
const PROJECT_EXTENSION = '.xcodeproj';
export function isWorkspace(projectFilePath: string): boolean {
return path.extname(projectFilePath) === WORKSPACE_EXTENSION;
}
export async function resolveProjectFilePathAsync(
projectDirectory: string,
projectFile?: string
): Promise<string> {
if (projectFile) {
if (![WORKSPACE_EXTENSION, PROJECT_EXTENSION].includes(path.extname(projectFile))) {
throw new UserError(
'NATIVE_XCODE_INVALID_PROJECT_FILE',
`"xcode_project_file" is "${projectFile}", which is not an Xcode workspace or project. Set it to the path of a "${WORKSPACE_EXTENSION}" or "${PROJECT_EXTENSION}", relative to the project directory.`
);
}
const projectFilePath = path.resolve(projectDirectory, projectFile);
if (!fs.existsSync(projectFilePath)) {
throw new UserError(
'NATIVE_XCODE_PROJECT_FILE_NOT_FOUND',
`"xcode_project_file" is "${projectFile}", but "${projectFilePath}" does not exist. Check that the path is relative to the project directory and that the file is committed. A workspace that "pod install" creates exists only when the project directory has a Podfile.`
);
}
return projectFilePath;
}
const entries = (await fs.promises.readdir(projectDirectory)).sort();
for (const extension of [WORKSPACE_EXTENSION, PROJECT_EXTENSION]) {
const candidates = entries.filter(entry => path.extname(entry) === extension);
if (candidates.length > 1) {
throw new UserError(
'NATIVE_XCODE_AMBIGUOUS_PROJECT_FILE',
`Found ${candidates.length} "${extension}" entries in the project directory: ${candidates.join(', ')}. EAS cannot tell which one to build. Set "xcode_project_file" to one of them.`
);
}
if (candidates.length === 1) {
return path.join(projectDirectory, candidates[0]);
}
}
throw new UserError(
'NATIVE_XCODE_PROJECT_FILE_NOT_FOUND',
`Found no "${WORKSPACE_EXTENSION}" and no "${PROJECT_EXTENSION}" in the project directory "${projectDirectory}". If the Xcode project is in a subdirectory of the repository, set "project_directory" to that subdirectory, or set "xcode_project_file" to the path of the workspace or project.`
);
}
@@ -0,0 +1,138 @@
import { UserError } from '@expo/eas-build-job';
import { bunyan } from '@expo/logger';
import { XMLParser } from 'fast-xml-parser';
import sortBy from 'lodash/sortBy';
import uniqBy from 'lodash/uniqBy';
import fs from 'node:fs';
import path from 'node:path';
import { isWorkspace } from './projectFile';
export interface XcodeScheme {
name: string;
path: string;
containerPathBase: string;
}
export interface XcodeSchemeDetails {
applicationTargetReference?: {
targetId: string;
xcodeprojPath: string;
};
archiveConfiguration?: string;
launchConfiguration?: string;
}
const xmlParser = new XMLParser({
ignoreAttributes: false,
attributeNamePrefix: '',
isArray: name => ['BuildActionEntry', 'FileRef', 'Group'].includes(name),
});
export async function findSharedSchemesAsync(projectFilePath: string): Promise<XcodeScheme[]> {
const schemeOwnersByPrecedence = isWorkspace(projectFilePath)
? [projectFilePath, ...(await findWorkspaceProjectsAsync(projectFilePath))]
: [projectFilePath];
const schemesByOwner = await Promise.all(
schemeOwnersByPrecedence.map(async schemeOwner => {
const schemesDirectory = path.join(schemeOwner, 'xcshareddata', 'xcschemes');
const fileNames = fs.existsSync(schemesDirectory)
? await fs.promises.readdir(schemesDirectory)
: [];
return fileNames
.filter(fileName => path.extname(fileName) === '.xcscheme')
.map(fileName => ({
name: path.basename(fileName, '.xcscheme'),
path: path.join(schemesDirectory, fileName),
containerPathBase: path.dirname(schemeOwner),
}));
})
);
return uniqBy(schemesByOwner.flat(), scheme => scheme.name);
}
export function selectScheme(
schemes: XcodeScheme[],
{ requestedName, logger }: { requestedName?: string; logger: bunyan }
): XcodeScheme {
const sortedSchemes = sortBy(schemes, scheme => scheme.name);
const schemeNames = sortedSchemes.map(scheme => scheme.name).join(', ');
if (sortedSchemes.length === 0) {
throw new UserError(
'NATIVE_XCODE_NO_SHARED_SCHEME',
'Found no shared scheme in the Xcode project. EAS builds a shared scheme, because only shared schemes are stored in the repository. In Xcode, open Product > Scheme > Manage Schemes, select "Shared" for the scheme of the app, and commit the ".xcscheme" file.'
);
}
if (requestedName) {
const requestedScheme = sortedSchemes.find(scheme => scheme.name === requestedName);
if (!requestedScheme) {
throw new UserError(
'NATIVE_XCODE_SCHEME_NOT_FOUND',
`"xcode_scheme" is "${requestedName}", but the Xcode project has no shared scheme with this name. Shared schemes: ${schemeNames}. Set "xcode_scheme" to one of them, or mark the scheme as "Shared" in Xcode and commit its ".xcscheme" file.`
);
}
return requestedScheme;
}
const firstSchemeNotForTvos = sortedSchemes.find(({ name }) => !name.includes('tvOS'));
const scheme = firstSchemeNotForTvos ?? sortedSchemes[0];
if (sortedSchemes.length > 1) {
logger.info(
`Found ${sortedSchemes.length} shared schemes: ${schemeNames}. Using "${scheme.name}". Set "xcode_scheme" to build another scheme.`
);
}
return scheme;
}
export async function readSchemeAsync(scheme: XcodeScheme): Promise<XcodeSchemeDetails> {
const { Scheme } = xmlParser.parse(await fs.promises.readFile(scheme.path, 'utf8'));
const applicationReference: Record<string, string | undefined> | undefined = (
Scheme?.BuildAction?.BuildActionEntries?.BuildActionEntry ?? []
)
.map((entry: any) => entry.BuildableReference)
.find((reference: any) => reference?.BuildableName?.endsWith('.app'));
return {
applicationTargetReference:
applicationReference?.BlueprintIdentifier && applicationReference.ReferencedContainer
? {
targetId: applicationReference.BlueprintIdentifier,
xcodeprojPath: path.resolve(
scheme.containerPathBase,
applicationReference.ReferencedContainer.replace(/^container:/, '')
),
}
: undefined,
archiveConfiguration: Scheme?.ArchiveAction?.buildConfiguration,
launchConfiguration: Scheme?.LaunchAction?.buildConfiguration,
};
}
interface WorkspaceGroup {
location?: string;
FileRef?: { location: string }[];
Group?: WorkspaceGroup[];
}
async function findWorkspaceProjectsAsync(workspacePath: string): Promise<string[]> {
const { Workspace } = xmlParser.parse(
await fs.promises.readFile(path.join(workspacePath, 'contents.xcworkspacedata'), 'utf8')
);
const workspaceDirectory = path.dirname(workspacePath);
// Xcode: "group:" is relative to the enclosing group, "container:" to the workspace directory.
const resolveLocation = (location: string, groupDirectory: string): string =>
location.startsWith('container:')
? path.resolve(workspaceDirectory, location.slice('container:'.length))
: path.resolve(groupDirectory, location.replace(/^group:/, ''));
const listFileLocations = (group: WorkspaceGroup, groupDirectory: string): string[] => [
...(group.FileRef ?? []).map(({ location }) => resolveLocation(location, groupDirectory)),
...(group.Group ?? []).flatMap(subgroup =>
listFileLocations(subgroup, resolveLocation(subgroup.location ?? '', groupDirectory))
),
];
return listFileLocations(Workspace ?? {}, workspaceDirectory).filter(
location => path.extname(location) === '.xcodeproj'
);
}
@@ -0,0 +1,48 @@
import { type bunyan } from '@expo/logger';
import { type CustomBuildContext } from '../../customBuildContext';
import { Sentry } from '../../sentry';
import { type CollectedCrash } from './serveSimCrashesRecorder';
import { uploadDeviceRunSessionFileAsync } from './uploadDeviceRunSessionFile';
export async function uploadServeSimCrashesFileAsync(
ctx: CustomBuildContext,
{
deviceRunSessionId,
crash: { udid, filePath, number, processName },
logger,
signal,
}: {
deviceRunSessionId: string;
crash: CollectedCrash;
logger: bunyan;
signal?: AbortSignal;
}
): Promise<void> {
const device = udid.slice(0, 8);
try {
await uploadDeviceRunSessionFileAsync(ctx, {
filePath,
describe: () => ({
deviceRunSessionId,
artifactId: `simulator-crash-${udid}-${number}`,
name: processName
? `Crash report ${number}: ${processName} (${device})`
: `Crash report ${number} (${device})`,
// Process names are not paths; keep separators out of the download name.
filename: `${(processName ?? 'crash').replace(/[/\\:\x00-\x1f]/g, '-')}-${number}.ips`,
kind: 'simulator-crash',
metadata: { __eas_type: 'simulator-crash', udid, source: 'serve-sim/crashes' },
}),
attempts: 3,
signal,
});
} catch (err) {
const error = err instanceof Error ? err : new Error(String(err));
Sentry.capture('Could not upload a simulator crash report', error, { level: 'warning' });
logger.warn(
{ err: error },
`Could not upload crash report ${number} for ${udid}; other artifacts will continue.`
);
}
}
@@ -0,0 +1,521 @@
import { type bunyan } from '@expo/logger';
import fetch from 'node-fetch';
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { z } from 'zod';
import { Sentry } from '../../sentry';
import { SERVE_SIM_STATE_DIR, readServeSimServersAsync } from './serveSimMetricsRecorder';
const MAX_BYTES_PER_DEVICE = 20 * 1024 * 1024;
const MAX_REPORTS_PER_DEVICE = 1_000;
const MAX_CONSECUTIVE_FAILURES = 10;
const MAX_FRAME_LENGTH = 1024 * 1024;
const MAX_DETAIL_BYTES = 8 * 1024 * 1024;
// A 5xx, timeout, or dropped connection is retried; a missing or unusable detail is not.
const MAX_DETAIL_ATTEMPTS = 3;
const DETAIL_RETRY_DELAY_MS = 500;
// serve-sim lists a crash about 5 s after it happens, once ReportCrash has written the report,
// so stopping checks each device once more for occurrences the stream had not delivered yet.
const FINAL_PASS_TIMEOUT_MS = 10_000;
const SummarySchema = z.object({
id: z.string(),
appName: z.string().nullable().optional(),
procName: z.string().nullable().optional(),
occurrenceTimes: z.array(
z.object({
key: z.number().int().nonnegative(),
capturedAtMs: z.number().nullable().optional(),
rawPath: z.string().optional(),
})
),
});
const FrameSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('meta'), meta: z.object({ statusError: z.string().nullable() }) }),
z.object({ type: z.literal('list'), crashes: z.array(SummarySchema) }),
z.object({ type: z.enum(['crash', 'recurred']), record: SummarySchema }),
]);
const ListSchema = z.object({ crashes: z.array(SummarySchema) });
const DetailSchema = z.object({
record: z.object({ id: z.string() }),
occurrence: z.object({
key: z.number().int().nonnegative(),
incidentId: z.string().nullable().optional(),
}),
report: z.string().nullable(),
});
/** A detail that will not change on retry: mismatched, malformed, or over 8 MiB. */
class UnusableDetailError extends Error {}
type ServeSimServer = { udid: string; url: string; token?: string };
export type CollectedCrash = {
udid: string;
filePath: string;
size: number;
number: number;
processName?: string;
};
type FinishedCrashes = { outputDirectory: string | null; crashes: CollectedCrash[] };
type Device = {
// The latest registry entry; unset while the server is absent, so its return counts as new.
server?: ServeSimServer;
identity?: string;
// Occurrences saved or skipped; reconnects replay the retained list and must not retry them.
handled: Set<string>;
incidents: Set<string>;
bytesWritten: number;
reportsWritten: number;
limitReached: boolean;
failures: number;
stoppedRetrying: boolean;
warnedStatusError: boolean;
};
type Session = {
outputDirectory: string;
logger: bunyan;
maxBytes: number;
finalPassTimeoutMs: number;
controller: AbortController;
timer: NodeJS.Timeout;
polling: Promise<void>;
streams: Map<string, Promise<void>>;
devices: Map<string, Device>;
files: CollectedCrash[];
stopping?: Promise<void>;
finishing?: Promise<FinishedCrashes>;
};
let activeSession: Session | undefined;
export namespace ServeSimCrashesRecorder {
export async function startAsync({
logger,
stateDir = SERVE_SIM_STATE_DIR,
pollIntervalMs = 2_000,
maxBytes = MAX_BYTES_PER_DEVICE,
maxDurationMs = 30 * 60 * 1000,
finalPassTimeoutMs = FINAL_PASS_TIMEOUT_MS,
}: {
logger: bunyan;
stateDir?: string;
pollIntervalMs?: number;
maxBytes?: number;
maxDurationMs?: number;
finalPassTimeoutMs?: number;
}): Promise<void> {
if (activeSession) {
return;
}
const controller = new AbortController();
const session: Session = {
outputDirectory: await mkdtemp(path.join(os.tmpdir(), 'serve-sim-crashes-')),
logger,
maxBytes,
finalPassTimeoutMs,
controller,
timer: setTimeout(() => {
logger.warn(
'Simulator crash collection reached its duration limit; collected reports will be retained.'
);
controller.abort();
}, maxDurationMs),
polling: Promise.resolve(),
streams: new Map(),
devices: new Map(),
files: [],
};
session.timer.unref();
activeSession = session;
session.polling = (async () => {
while (!controller.signal.aborted) {
const servers = await readServeSimServersAsync(stateDir);
const present = new Set(servers.map(server => server.udid));
for (const [udid, device] of session.devices) {
if (!present.has(udid)) {
device.server = undefined;
device.identity = undefined;
}
}
for (const server of servers) {
if (controller.signal.aborted) {
break;
}
const device = getDevice(session, server.udid);
// Kept current while a stream runs, so the final pass reads the latest address.
device.server = server;
if (session.streams.has(server.udid)) {
continue;
}
const identity = JSON.stringify([server.url, server.token]);
if (device.identity !== identity) {
device.identity = identity;
device.failures = 0;
device.stoppedRetrying = false;
}
if (device.limitReached || device.stoppedRetrying) {
continue;
}
if (device.failures >= MAX_CONSECUTIVE_FAILURES) {
device.stoppedRetrying = true;
logger.warn(
`Stopped retrying simulator crash collection for ${server.udid} after ${MAX_CONSECUTIVE_FAILURES} failed connections; collected reports will be retained.`
);
continue;
}
device.failures += 1;
const done = streamServeSimCrashesAsync(session, server, device).finally(() =>
session.streams.delete(server.udid)
);
session.streams.set(server.udid, done);
}
await delay(pollIntervalMs, undefined, { signal: controller.signal }).catch(() => {});
}
})().catch(err => {
const error = err instanceof Error ? err : new Error(String(err));
Sentry.capture('serve-sim simulator crash poller failed', error);
logger.warn(
{ err: error },
'Could not collect simulator crashes; collected reports will be retained.'
);
controller.abort();
});
logger.info('Started collecting simulator crashes (up to 20 MiB per device and 30 minutes).');
}
/** Never rejects. */
export async function stopAsync(): Promise<void> {
const session = activeSession;
if (!session) {
return;
}
session.stopping ??= (async () => {
clearTimeout(session.timer);
session.controller.abort();
await session.polling;
await Promise.all(session.streams.values());
await collectRemainingCrashesAsync(session);
})();
await session.stopping;
}
export async function finishAsync(): Promise<FinishedCrashes> {
const session = activeSession;
if (!session || session.finishing) {
await session?.finishing;
return { outputDirectory: null, crashes: [] };
}
session.finishing = (async () => {
await stopAsync();
return { outputDirectory: session.outputDirectory, crashes: session.files };
})();
try {
return await session.finishing;
} finally {
if (activeSession === session) {
activeSession = undefined;
}
}
}
}
function getDevice(session: Session, udid: string): Device {
let device = session.devices.get(udid);
if (!device) {
device = {
handled: new Set(),
incidents: new Set(),
bytesWritten: 0,
reportsWritten: 0,
limitReached: false,
failures: 0,
stoppedRetrying: false,
warnedStatusError: false,
};
session.devices.set(udid, device);
}
return device;
}
async function streamServeSimCrashesAsync(
session: Session,
server: ServeSimServer,
device: Device
): Promise<void> {
const { logger } = session;
const signal = session.controller.signal;
const controller = new AbortController();
try {
const url = new URL('/crashes', server.url);
url.searchParams.set('device', server.udid);
const response = await fetch(url.toString(), {
redirect: 'error',
signal: AbortSignal.any([signal, controller.signal]),
headers: {
Accept: 'text/event-stream',
...(server.token ? { Authorization: `Bearer ${server.token}` } : {}),
},
});
if (
!response.ok ||
!response.body ||
!response.headers.get('content-type')?.includes('text/event-stream')
) {
throw new Error(`serve-sim /crashes responded ${response.status}`);
}
const decoder = new TextDecoder();
let buffer = '';
for await (const chunk of response.body) {
buffer += decoder.decode(chunk as Buffer, { stream: true });
let newline: number;
while ((newline = buffer.indexOf('\n')) !== -1) {
const line = buffer.slice(0, newline).replace(/\r$/, '');
buffer = buffer.slice(newline + 1);
if (line.length > MAX_FRAME_LENGTH) {
throw new Error('Crash frame exceeded limit');
}
if (!line.startsWith('data:')) {
continue;
}
const frame = FrameSchema.safeParse(JSON.parse(line.slice(5)));
if (!frame.success) {
continue;
}
if (frame.data.type === 'meta') {
if (frame.data.meta.statusError && !device.warnedStatusError) {
device.warnedStatusError = true;
logger.warn(
'serve-sim cannot watch crash reports; crash collection will resume when the watcher recovers.'
);
}
continue;
}
const summaries = frame.data.type === 'list' ? frame.data.crashes : [frame.data.record];
await saveOccurrencesAsync(session, server, device, summaries, { stop: signal });
if (signal.aborted || device.limitReached) {
return;
}
device.failures = 0;
}
if (buffer.length > MAX_FRAME_LENGTH) {
throw new Error('Crash frame exceeded limit');
}
}
} catch (err) {
if (!signal.aborted) {
logger.warn(
{ err },
`Simulator crash stream for ${server.udid} ended; collection will be retried.`
);
}
} finally {
controller.abort();
}
}
/** One look at each device's crash list, for occurrences the stream had not delivered. */
async function collectRemainingCrashesAsync(session: Session): Promise<void> {
const signal = AbortSignal.timeout(session.finalPassTimeoutMs);
await Promise.all(
[...session.devices.values()].map(async device => {
const { server } = device;
if (!server || device.limitReached) {
return;
}
try {
const url = new URL('/crashes', server.url);
url.searchParams.set('device', server.udid);
const response = await fetch(url.toString(), {
redirect: 'error',
signal,
headers: {
Accept: 'application/json',
...(server.token ? { Authorization: `Bearer ${server.token}` } : {}),
},
});
if (!response.ok || !response.headers.get('content-type')?.includes('application/json')) {
throw new Error(`serve-sim /crashes responded ${response.status}`);
}
const { crashes } = ListSchema.parse(await response.json());
await saveOccurrencesAsync(session, server, device, crashes, {
stop: signal,
deadline: signal,
});
} catch (err) {
session.logger.warn(
{ err },
`Could not check ${server.udid} for crashes before the session ended; collected reports will be retained.`
);
}
})
);
}
async function saveOccurrencesAsync(
session: Session,
server: ServeSimServer,
device: Device,
summaries: z.infer<typeof SummarySchema>[],
// `stop` ends the loop between occurrences; `deadline` also aborts a download in progress.
{ stop, deadline }: { stop: AbortSignal; deadline?: AbortSignal }
): Promise<void> {
const { logger } = session;
// Each caller returns once this is true, so the deadline warning is logged once per pass.
const stopped = (): boolean => {
if (deadline?.aborted) {
logger.warn(
`Stopped checking ${server.udid} for crashes at the end-of-session deadline; collected reports will be retained.`
);
}
return stop.aborted || !!deadline?.aborted;
};
for (const summary of summaries) {
for (const occurrence of summary.occurrenceTimes) {
if (device.limitReached || stopped()) {
return;
}
// Keys restart when serve-sim does; the capture time and report path tell such occurrences apart.
const key = JSON.stringify([
summary.id,
occurrence.key,
occurrence.capturedAtMs ?? null,
occurrence.rawPath ?? null,
]);
if (device.handled.has(key)) {
continue;
}
let detail: z.infer<typeof DetailSchema> | undefined;
try {
for (let attempt = 1; ; attempt++) {
try {
detail = await readCrashDetailAsync(server, summary.id, occurrence.key, deadline);
break;
} catch (err) {
if (err instanceof UnusableDetailError || attempt >= MAX_DETAIL_ATTEMPTS) {
throw err;
}
await delay(DETAIL_RETRY_DELAY_MS, undefined, { signal: stop });
}
}
} catch (err) {
// Stopping leaves the occurrence unhandled, so the final pass can still save it.
if (stopped()) {
return;
}
device.handled.add(key);
logger.warn(
{ err },
`Could not download crash occurrence ${occurrence.key} for ${server.udid}; skipping it.`
);
continue;
}
device.handled.add(key);
if (!detail) {
logger.warn(
`Crash occurrence ${occurrence.key} is no longer available for ${server.udid}; earlier reports will be retained.`
);
continue;
}
const { incidentId } = detail.occurrence;
if (incidentId && device.incidents.has(incidentId)) {
continue;
}
if (!detail.report) {
logger.warn(
`Crash occurrence ${occurrence.key} has no native report for ${server.udid}; skipping its artifact.`
);
continue;
}
const size = Buffer.byteLength(detail.report);
if (
device.bytesWritten + size > session.maxBytes ||
device.reportsWritten >= MAX_REPORTS_PER_DEVICE
) {
device.limitReached = true;
logger.warn(
`Simulator crash collection reached its limit for ${server.udid}; collected reports will be retained.`
);
return;
}
const number = device.reportsWritten + 1;
const filePath = path.join(session.outputDirectory, `${server.udid}-${number}.ips`);
try {
await writeFile(filePath, detail.report, { mode: 0o600, flag: 'wx' });
} catch (error) {
device.handled.delete(key);
await rm(filePath, { force: true }).catch(() => {});
throw error;
}
device.bytesWritten += size;
device.reportsWritten = number;
if (incidentId) {
device.incidents.add(incidentId);
}
const processName = summary.appName || summary.procName || undefined;
session.files.push({
udid: server.udid,
filePath,
size,
number,
...(processName ? { processName } : {}),
});
}
}
}
/** Resolves `undefined` when serve-sim no longer keeps the occurrence. */
async function readCrashDetailAsync(
server: ServeSimServer,
id: string,
key: number,
deadline?: AbortSignal
): Promise<z.infer<typeof DetailSchema> | undefined> {
const url = new URL(`/crashes/${encodeURIComponent(id)}`, server.url);
url.searchParams.set('device', server.udid);
url.searchParams.set('key', String(key));
const controller = new AbortController();
try {
const response = await fetch(url.toString(), {
redirect: 'error',
size: MAX_DETAIL_BYTES,
signal: AbortSignal.any([
controller.signal,
AbortSignal.timeout(5_000),
...(deadline ? [deadline] : []),
]),
...(server.token ? { headers: { Authorization: `Bearer ${server.token}` } } : {}),
});
if (response.status === 404) {
return undefined;
}
if (!response.ok) {
// Other 4xx responses will not change on a retry; 408, 429 and 5xx can.
const permanent = response.status < 500 && response.status !== 408 && response.status !== 429;
throw new (permanent ? UnusableDetailError : Error)(
`serve-sim crash detail responded ${response.status}`
);
}
const body = await response.json().catch(err => {
const type = (err as { type?: string }).type;
if (type === 'max-size') {
throw new UnusableDetailError('Crash detail exceeds 8 MiB');
}
if (type === 'invalid-json') {
throw new UnusableDetailError('Crash detail is not valid JSON');
}
throw err;
});
const detail = DetailSchema.safeParse(body);
if (!detail.success) {
throw new UnusableDetailError('Crash detail is not valid');
}
if (detail.data.record.id !== id || detail.data.occurrence.key !== key) {
throw new UnusableDetailError('Crash detail does not match the requested occurrence');
}
return detail.data;
} finally {
controller.abort();
}
}
@@ -0,0 +1,59 @@
import { formatBytes } from '@expo/eas-build-job';
import { type bunyan } from '@expo/logger';
import { CustomBuildContext } from '../../customBuildContext';
import { Sentry } from '../../sentry';
import { uploadDeviceRunSessionFileAsync } from './uploadDeviceRunSessionFile';
const NETWORK_CAPTURE_ARTIFACT_FILENAME = 'network-capture.har';
const MAX_NETWORK_CAPTURE_ARTIFACT_SIZE_BYTES = 500 * 1024 * 1024;
/** Never rejects; a failed upload is logged. */
export async function uploadServeSimNetworkCaptureFileAsync(
ctx: CustomBuildContext,
{
deviceRunSessionId,
udid,
filePath,
size,
part,
logger,
signal,
}: {
deviceRunSessionId: string;
udid: string;
filePath: string;
size: number;
part: number;
logger: bunyan;
signal?: AbortSignal;
}
): Promise<void> {
const label = part > 1 ? `, part ${part}` : '';
if (size > MAX_NETWORK_CAPTURE_ARTIFACT_SIZE_BYTES) {
logger.warn(
`Skipping network capture for ${udid}${label}: exceeds the ${formatBytes(MAX_NETWORK_CAPTURE_ARTIFACT_SIZE_BYTES)} upload limit.`
);
return;
}
try {
logger.info(`Uploading the network capture for ${udid}${label} (${formatBytes(size)}).`);
await uploadDeviceRunSessionFileAsync(ctx, {
filePath,
describe: () => ({
deviceRunSessionId,
artifactId: `network-capture-${udid}-${part}`,
name: `Network capture (${udid.slice(0, 8)}${label})`,
filename: NETWORK_CAPTURE_ARTIFACT_FILENAME,
kind: 'network-capture',
metadata: { __eas_type: 'network-capture', format: 'har', udid, part },
}),
attempts: 3,
signal,
});
} catch (err) {
const error = err instanceof Error ? err : new Error(String(err));
Sentry.capture('Could not upload the network capture', error, { level: 'warning' });
logger.warn({ err: error }, `Could not upload the network capture for ${udid}.`);
}
}
@@ -0,0 +1,472 @@
import { type bunyan } from '@expo/logger';
import { type BuildStepEnv } from '@expo/steps';
import { createReadStream } from 'node:fs';
import { mkdtemp, open, readdir, rename, rm, stat } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { createInterface } from 'node:readline';
import { setTimeout as delay } from 'node:timers/promises';
import { Sentry } from '../../sentry';
import {
PackageManager,
resolveConfiguredPackageManager,
resolvePackageExec,
} from '../../utils/packageManager';
import { createServeSimPackageSpec } from './deviceSessionHost';
import {
type DetachedProcessHandle,
omitNgrokAuthtoken,
spawnDetached,
} from './remoteDeviceRunSession';
import { SERVE_SIM_STATE_DIR, readServeSimServersAsync } from './serveSimMetricsRecorder';
const POLL_INTERVAL_MS = 2_000;
// While serve-sim runs, an exited follower (stream dropped, capture off) is replaced after this long;
// one that recorded nothing (usually capture off) waits longer, since it may stay off all session.
const FOLLOWER_RESTART_INTERVAL_MS = 10_000;
const IDLE_FOLLOWER_RESTART_INTERVAL_MS = 30_000;
// On stop the follower rebuilds the whole HAR from its entry log; a shorter --flush-ms would not
// shorten that last rebuild, so a large recording gets a longer grace before it is killed.
const FOLLOWER_STOP_GRACE_PERIOD_MS = 60_000;
// HARs holding requests, across the session.
const MAX_RECORDINGS = 20;
// Followers started for one serve-sim server; at the idle interval this covers about an hour.
const MAX_FOLLOWER_STARTS = 120;
const OUTPUT_TAIL_CHARS = 2_000;
type Follower = {
udid: string;
filePath: string;
handle: DetachedProcessHandle;
startedAt: number;
/** Set once the follower has exited and holds requests no earlier follower recorded. */
kept?: boolean;
};
type ServeSimNetworkCaptureSession = {
logger: bunyan;
stateDir: string;
pollIntervalMs: number;
restartIntervalMs: number;
idleRestartIntervalMs: number;
outputDirectory: string;
command: { command: string; args: string[] };
env: BuildStepEnv;
followers: Follower[];
current: Map<string, Follower>;
followerStarts: Map<string, number>;
stoppedRetrying: Set<string>;
warnedRecordingLimit: boolean;
fileCounts: Map<string, number>;
/** Per device, the requests of the exited followers that were kept. */
keptRequests: Map<string, Set<string>>;
pollingPromise: Promise<void>;
abortController: AbortController;
};
export type RecordedNetworkCapture = { udid: string; filePath: string; size: number };
let activeSession: ServeSimNetworkCaptureSession | null = null;
/** serve-sim deletes capture files when capture stops; a `capture har` follower keeps the HAR. */
export namespace ServeSimNetworkCaptureRecorder {
export async function startAsync({
logger,
env,
packageVersion,
stateDir = SERVE_SIM_STATE_DIR,
pollIntervalMs = POLL_INTERVAL_MS,
restartIntervalMs = FOLLOWER_RESTART_INTERVAL_MS,
idleRestartIntervalMs = IDLE_FOLLOWER_RESTART_INTERVAL_MS,
}: {
logger: bunyan;
env: BuildStepEnv;
packageVersion?: string;
stateDir?: string;
pollIntervalMs?: number;
restartIntervalMs?: number;
idleRestartIntervalMs?: number;
}): Promise<void> {
if (activeSession) {
logger.info('The serve-sim network capture recorder is already running.');
return;
}
const command = resolvePackageExec(resolveConfiguredPackageManager(env, PackageManager.NPM), [
createServeSimPackageSpec(packageVersion),
]);
const session: ServeSimNetworkCaptureSession = {
logger,
stateDir,
pollIntervalMs,
restartIntervalMs,
idleRestartIntervalMs,
outputDirectory: await mkdtemp(path.join(os.tmpdir(), 'serve-sim-network-capture-')),
command,
env: omitNgrokAuthtoken(env),
followers: [],
current: new Map(),
followerStarts: new Map(),
stoppedRetrying: new Set(),
warnedRecordingLimit: false,
fileCounts: new Map(),
keptRequests: new Map(),
pollingPromise: Promise.resolve(),
abortController: new AbortController(),
};
activeSession = session;
logger.info('Started watching serve-sim for network capture.');
session.pollingPromise = pollServeSimServersAsync(session).catch(err => {
const error = err instanceof Error ? err : new Error(String(err));
Sentry.capture('serve-sim network capture poller failed', error);
logger.warn({ err: error }, 'serve-sim network capture poller failed.');
});
}
/** Never rejects. */
export async function finishAsync({
logger,
}: {
logger: bunyan;
}): Promise<{ outputDirectory: string | null; captures: RecordedNetworkCapture[] }> {
const session = activeSession;
if (!session) {
logger.info('The serve-sim network capture recorder is not running.');
return { outputDirectory: null, captures: [] };
}
activeSession = null;
session.abortController.abort();
await session.pollingPromise;
// Stopped together, so the final HAR rebuilds share one grace period.
await Promise.all(
session.followers.map(follower =>
follower.handle.stopAsync().catch(err => {
logger.warn({ err }, `Could not stop the network capture follower for ${follower.udid}.`);
})
)
);
const captures: RecordedNetworkCapture[] = [];
const recorded = new Map<string, Set<string>>();
for (const follower of session.followers) {
try {
if (!(await rebuildHarAsync(follower, requestsFor(recorded, follower.udid)))) {
continue;
}
} catch (err) {
logger.warn(
{ err },
`Could not rebuild a network capture for ${follower.udid}; its HAR is kept as serve-sim wrote it.`
);
}
const size = await stat(follower.filePath).then(
stats => stats.size,
() => 0
);
if (size > 0) {
captures.push({ udid: follower.udid, filePath: follower.filePath, size });
}
}
for (const follower of session.current.values()) {
if (!captures.some(capture => capture.udid === follower.udid)) {
logger.info(
{ output: follower.handle.getOutput().slice(-OUTPUT_TAIL_CHARS) || '<empty>' },
`No network capture was recorded for ${follower.udid}.`
);
}
}
return { outputDirectory: session.outputDirectory, captures };
}
}
async function pollServeSimServersAsync(session: ServeSimNetworkCaptureSession): Promise<void> {
const { abortController } = session;
while (!abortController.signal.aborted) {
for (const server of await readServeSimServersAsync(session.stateDir)) {
// serve-sim's capture routes require a token, so `capture har` refuses a server without one.
if (!server.token) {
continue;
}
const key = `${server.udid}\n${server.url}\n${server.token}`;
try {
await ensureFollowerAsync(session, key, server.udid);
} catch (err) {
session.logger.warn(
{ err },
`Could not start the network capture follower for ${server.udid}; retrying.`
);
}
}
await delay(session.pollIntervalMs, undefined, { signal: abortController.signal }).catch(
() => {}
);
}
}
async function ensureFollowerAsync(
session: ServeSimNetworkCaptureSession,
key: string,
udid: string
): Promise<void> {
const previous = session.current.get(key);
if (previous) {
if (previous.handle.getExitError() === undefined) {
return;
}
const recorded = await hasEntriesAsync(previous);
const interval = recorded ? session.restartIntervalMs : session.idleRestartIntervalMs;
if (Date.now() - previous.startedAt < interval) {
return;
}
} else {
// serve-sim restarted with a new token; the old identity's follower is no longer current.
for (const [otherKey, other] of session.current) {
if (other.udid === udid) {
session.current.delete(otherKey);
}
}
}
// A new follower replays the requests serve-sim already holds, so an exited follower that recorded
// no new request holds no capture of its own and does not use a recording slot. Another server's
// current follower waits for its own restart, which reads its entry log.
const current = new Set(session.current.values());
for (const follower of [...session.followers]) {
if (
follower.kept ||
follower.handle.getExitError() === undefined ||
(follower !== previous && current.has(follower))
) {
continue;
}
const keptRequests = requestsFor(session.keptRequests, follower.udid);
const requests = await readRequestKeysAsync(entriesPathFor(follower));
if (requests.some(request => request === null || !keptRequests.has(request))) {
follower.kept = true;
for (const request of requests) {
if (request !== null) {
keptRequests.add(request);
}
}
} else {
session.followers.splice(session.followers.indexOf(follower), 1);
await removeFollowerFilesAsync(follower, session.logger);
}
}
if (session.followers.length >= MAX_RECORDINGS) {
if (!session.warnedRecordingLimit) {
session.warnedRecordingLimit = true;
session.logger.warn(
`Network capture reached its limit of ${MAX_RECORDINGS} recordings; recorded captures will be retained.`
);
}
return;
}
const starts = session.followerStarts.get(key) ?? 0;
if (starts >= MAX_FOLLOWER_STARTS) {
if (!session.stoppedRetrying.has(key)) {
session.stoppedRetrying.add(key);
session.logger.warn(
{ output: previous?.handle.getOutput().slice(-OUTPUT_TAIL_CHARS) || '<empty>' },
`Stopped retrying network capture for ${udid} after ${MAX_FOLLOWER_STARTS} attempts; recorded captures will be retained.`
);
}
return;
}
session.followerStarts.set(key, starts + 1);
const count = (session.fileCounts.get(udid) ?? 0) + 1;
session.fileCounts.set(udid, count);
const filePath = path.join(session.outputDirectory, `${udid}-${count}.har`);
if (!previous) {
session.logger.info(`Recording network capture for ${udid}.`);
}
const follower: Follower = {
udid,
filePath,
startedAt: Date.now(),
handle: spawnDetached({
command: session.command.command,
args: [...session.command.args, 'capture', 'har', '-o', filePath, '-d', udid],
env: session.env,
stopGracePeriodMs: FOLLOWER_STOP_GRACE_PERIOD_MS,
}),
};
session.followers.push(follower);
session.current.set(key, follower);
}
/** serve-sim writes an empty HAR when recording begins; requests go to `<stem>.entries.ndjson`. */
function entriesPathFor(follower: Follower): string {
return follower.filePath.replace(/\.har$/, '.entries.ndjson');
}
/** Removes the HAR and the working files serve-sim names after it, such as its entry log. */
async function removeFollowerFilesAsync(follower: Follower, logger: bunyan): Promise<void> {
const directory = path.dirname(follower.filePath);
const prefix = `${path.basename(follower.filePath, '.har')}.`;
try {
const names = (await readdir(directory)).filter(name => name.startsWith(prefix));
await Promise.all(names.map(name => rm(path.join(directory, name), { force: true })));
} catch (err) {
logger.warn({ err }, `Could not remove a replayed network capture for ${follower.udid}.`);
}
}
async function hasEntriesAsync(follower: Follower): Promise<boolean> {
return await stat(entriesPathFor(follower)).then(
stats => stats.size > 0,
() => false
);
}
function requestsFor(requests: Map<string, Set<string>>, udid: string): Set<string> {
let forDevice = requests.get(udid);
if (!forDevice) {
forDevice = new Set();
requests.set(udid, forDevice);
}
return forDevice;
}
type Entry = { _captureId?: unknown; _captureStartedAt?: unknown; startedDateTime?: unknown };
/**
* Reads an entry log line; null when it is not JSON, such as a line a killed follower cut off.
* Entries without a valid start time sort last.
*/
function parseEntry(line: string): { key: string | null; start: number } | null {
let entry: Entry;
try {
entry = JSON.parse(line);
} catch {
return null;
}
const start = Date.parse(String(entry?.startedDateTime));
return { key: requestKey(entry), start: Number.isNaN(start) ? Number.POSITIVE_INFINITY : start };
}
/**
* A request's identity, as serve-sim's `capture har` matches its replays: request ids restart in
* every capture session, so the request's start time tells them apart. null when serve-sim did not
* record an id, so the request cannot be matched.
*/
function requestKey(entry: Entry | null): string | null {
if (typeof entry?._captureId !== 'string') {
return null;
}
return entry._captureStartedAt !== undefined
? `${entry._captureId} ${entry._captureStartedAt}`
: `${entry._captureId} ${entry.startedDateTime}`;
}
/** Streams the entry log, so a large recording never has to fit in memory. */
async function forEachEntryAsync(
entriesPath: string,
onEntry: (line: string, offset: number) => void
): Promise<void> {
// A follower that never began recording leaves no entry log.
if (
!(await stat(entriesPath).then(
() => true,
() => false
))
) {
return;
}
const input = createReadStream(entriesPath, { encoding: 'utf8' });
const lines = createInterface({ input, crlfDelay: Infinity });
let offset = 0;
try {
for await (const line of lines) {
if (line) {
onEntry(line, offset);
}
offset += Buffer.byteLength(line) + 1;
}
} finally {
lines.close();
input.destroy();
}
}
async function readRequestKeysAsync(entriesPath: string): Promise<(string | null)[]> {
const keys: (string | null)[] = [];
await forEachEntryAsync(entriesPath, line => {
const entry = parseEntry(line);
if (entry) {
keys.push(entry.key);
}
});
return keys;
}
/**
* Rebuilds a stopped follower's HAR from its entry log, which a killed follower's HAR can lag,
* without the requests an earlier follower for the device recorded. Then adds its requests to
* `recorded`. Returns false when it holds no new request.
*/
async function rebuildHarAsync(follower: Follower, recorded: Set<string>): Promise<boolean> {
const entriesPath = entriesPathFor(follower);
const entries: { start: number; offset: number; length: number }[] = [];
const requests: string[] = [];
await forEachEntryAsync(entriesPath, (line, offset) => {
const entry = parseEntry(line);
if (!entry || (entry.key !== null && recorded.has(entry.key))) {
return;
}
if (entry.key !== null) {
requests.push(entry.key);
}
entries.push({ start: entry.start, offset, length: Buffer.byteLength(line) });
});
if (entries.length === 0) {
return false;
}
await writeHarAsync(follower.filePath, entriesPath, entries);
for (const request of requests) {
recorded.add(request);
}
return true;
}
const HAR_HEADER_BYTES = 4_096;
const HAR_ENTRIES_START = '"entries":[';
/** Rebuilds the HAR from the given entry log lines, in start order as serve-sim writes it. */
async function writeHarAsync(
harPath: string,
entriesPath: string,
entries: { start: number; offset: number; length: number }[]
): Promise<void> {
// serve-sim writes `{"log":{...,"entries":[` first; its version and creator are kept.
const har = await open(harPath, 'r');
let header: string;
try {
const buffer = Buffer.alloc(HAR_HEADER_BYTES);
const { bytesRead } = await har.read(buffer, 0, buffer.length, 0);
header = buffer.subarray(0, bytesRead).toString('utf8');
} finally {
await har.close();
}
const at = header.indexOf(HAR_ENTRIES_START);
if (at === -1) {
throw new Error('The HAR does not start like a serve-sim HAR.');
}
const tempPath = `${harPath}.rebuilt.tmp`;
const out = await open(tempPath, 'wx', 0o600);
const source = await open(entriesPath, 'r');
try {
await out.write(Buffer.from(header.slice(0, at + HAR_ENTRIES_START.length)));
const sorted = [...entries].sort((a, b) => a.start - b.start);
for (const [index, { offset, length }] of sorted.entries()) {
const line = Buffer.alloc(length);
await source.read(line, 0, length, offset);
await out.write(index > 0 ? Buffer.concat([Buffer.from(','), line]) : line);
}
await out.write(Buffer.from(']}}\n'));
} finally {
await source.close();
await out.close();
}
await rename(tempPath, harPath);
}
+1 -1
View File
@@ -21,5 +21,5 @@
}
]
},
"include": ["src/**/*"]
"include": ["src/**/*", "../../ts-declarations/xcode/index.d.ts"]
}
@@ -1,5 +1,9 @@
# create-eas-build-function
## 27.11.0
No changes in this release.
## 27.10.0
No changes in this release.
@@ -1,6 +1,6 @@
{
"name": "create-eas-build-function",
"version": "27.10.0",
"version": "27.11.0",
"description": "Create functions for use in EAS Build custom builds.",
"keywords": [
"expo",
@@ -35,7 +35,7 @@
"clean": "rimraf ./build/ \"*.tsbuildinfo\""
},
"dependencies": {
"@expo/steps": "27.10.0"
"@expo/steps": "27.11.0"
},
"devDependencies": {
"@expo/package-manager": "1.9.10",
+4
View File
@@ -1,5 +1,9 @@
# @expo/downloader
## 27.11.0
No changes in this release.
## 27.10.0
No changes in this release.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@expo/downloader",
"version": "27.10.0",
"version": "27.11.0",
"bugs": "https://github.com/expo/eas-cli/issues",
"license": "BUSL-1.1",
"author": "Expo <[email protected]>",
@@ -1,5 +1,9 @@
# eas-build-cache-provider
## 27.11.0
No changes in this release.
## 27.10.0
No changes in this release.
@@ -1,6 +1,6 @@
{
"name": "eas-build-cache-provider",
"version": "27.10.0",
"version": "27.11.0",
"description": "A build cache provider plugin for the Expo CLI",
"homepage": "https://github.com/expo/eas-cli",
"bugs": "https://github.com/expo/eas-cli/issues",
+7
View File
@@ -1,5 +1,12 @@
# @expo/eas-build-job
## 27.11.0
### Minor Changes
- Accept `issue_comment` as a `github.event_name` value in the workflow interpolation context. ([#4906](https://github.com/expo/eas-cli/pull/4906) by [@sswrk](https://github.com/sswrk))
- Support error occurrence events in Observe workflow context. ([#4860](https://github.com/expo/eas-cli/pull/4860) by [@AbbanMustafa](https://github.com/AbbanMustafa))
## 27.10.0
No changes in this release.
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@expo/eas-build-job",
"version": "27.10.0",
"version": "27.11.0",
"bugs": "https://github.com/expo/eas-cli/issues",
"license": "MIT",
"author": "Expo <[email protected]>",
@@ -25,9 +25,9 @@
"clean": "rimraf node_modules dist coverage \"*.tsbuildinfo\""
},
"dependencies": {
"@expo/logger": "27.10.0",
"@expo/logger": "27.11.0",
"@expo/results": "1.0.0",
"@expo/turtle-spawn": "27.10.0",
"@expo/turtle-spawn": "27.11.0",
"joi": "^17.13.9",
"semver": "^7.6.2",
"zod": "^4.6.7"
@@ -3,7 +3,14 @@ import { randomUUID } from 'crypto';
import Joi from 'joi';
import * as Android from '../android';
import { ArchiveSourceType, BuildMode, BuildTrigger, Platform, Workflow } from '../common';
import {
ArchiveSourceType,
BuildMode,
BuildTrigger,
NativeBuilder,
Platform,
Workflow,
} from '../common';
const joiOptions: Joi.ValidationOptions = {
stripUnknown: true,
@@ -22,6 +29,27 @@ const secrets = {
},
};
function createNativeJob(overrides: object = {}): Record<string, unknown> {
return {
mode: BuildMode.BUILD,
builder: NativeBuilder.GRADLE,
type: Workflow.GENERIC,
triggeredBy: BuildTrigger.GIT_BASED_INTEGRATION,
platform: Platform.ANDROID,
projectArchive: {
type: ArchiveSourceType.GIT,
gitCommitHash: '0123456789abcdef0123456789abcdef01234567',
gitRef: 'refs/heads/main',
},
projectRootDirectory: '.',
buildType: Android.BuildType.APK,
secrets,
initiatingUserId: randomUUID(),
appId: randomUUID(),
...overrides,
};
}
describe('Android.JobSchema', () => {
test('valid generic job', () => {
const genericJob = {
@@ -491,4 +519,122 @@ describe('Android.JobSchema', () => {
expect(value).toMatchObject(job);
expect(error).toBeFalsy();
});
test('returns a valid native job unchanged', () => {
const job = createNativeJob({
gradleCommand: ':app:assembleRelease',
hooks: { after_checkout: [{ run: 'echo Hello, world!' }] },
});
const { value, error } = Android.JobSchema.validate(job, joiOptions);
expect(error).toBeFalsy();
expect(value).toEqual(job);
});
test('returns a valid native job without credentials unchanged', () => {
const job = createNativeJob({ secrets: {} });
const { value, error } = Android.JobSchema.validate(job, joiOptions);
expect(error).toBeFalsy();
expect(value).toEqual(job);
});
test('native job requires buildType', () => {
const job = createNativeJob({ buildType: undefined });
const { error } = Android.JobSchema.validate(job, joiOptions);
expect(error?.message).toBe('"buildType" is required');
});
test('native job defaults mode to build', () => {
const job = createNativeJob({ mode: undefined });
const { value, error } = Android.JobSchema.validate(job, joiOptions);
expect(error).toBeFalsy();
expect(value.mode).toBe(BuildMode.BUILD);
});
test.each([BuildMode.RESIGN, BuildMode.CUSTOM, BuildMode.REPACK])(
'native job rejects mode %s',
mode => {
const job = createNativeJob({ mode });
const { error } = Android.JobSchema.validate(job, joiOptions);
expect(error?.message).toBe('"mode" must be [build]');
}
);
test('job without builder is not a native job', () => {
const job = createNativeJob({ builder: undefined, buildProfile: 'production' });
const { value, error } = Android.JobSchema.validate(job, joiOptions);
expect(error).toBeFalsy();
expect(value.buildProfile).toBe('production');
});
test('native job rejects a type other than generic', () => {
const job = createNativeJob({ type: Workflow.MANAGED });
const { error } = Android.JobSchema.validate(job, joiOptions);
expect(error?.message).toBe('"type" must be [generic]');
});
test.each([NativeBuilder.XCODE, 'unknown'])('native job rejects builder %s', builder => {
const job = createNativeJob({ builder });
const { error } = Android.JobSchema.validate(job, joiOptions);
expect(error?.message).toBe('"builder" must be [gradle]');
});
test.each([
['buildProfile', 'production'],
['updates', { channel: 'main' }],
['cache', { disabled: false }],
['developmentClient', true],
['version', { versionCode: '1' }],
['buildArtifactPaths', ['android/app/build/outputs/logs/*.txt']],
['applicationArchivePath', 'android/app/build/outputs/**/*.apk'],
['username', 'testuser'],
['customBuildConfig', { path: 'production.yml' }],
['steps', [{ id: 'step1', run: 'echo Hello, world!', shell: 'sh' }]],
['outputs', { version_code: '1' }],
['experimental', { prebuildCommand: 'echo Hello, world!' }],
['githubTriggerOptions', { autoSubmit: true }],
])('native job rejects %s', (field, fieldValue) => {
const job = createNativeJob({ [field]: fieldValue });
const { error } = Android.JobSchema.validate(job, joiOptions);
expect(error?.message).toBe(`"${field}" is not allowed`);
});
test('native job accepts only the job fields listed here', () => {
const { keys } = Android.JobSchema.describe().whens[0].then;
const acceptedFields = Object.keys(keys).filter(
field => keys[field].flags?.presence !== 'forbidden'
);
expect(new Set(acceptedFields)).toEqual(
new Set([
'mode',
'type',
'triggeredBy',
'projectArchive',
'platform',
'projectRootDirectory',
'secrets',
'builderEnvironment',
'gradleCommand',
'hooks',
'ssh',
'expoBuildUrl',
'loggerLevel',
'initiatingUserId',
'appId',
'environment',
'workflowInterpolationContext',
'builder',
'buildType',
])
);
});
});
@@ -922,6 +922,50 @@ describe('GitHub context event payload passthrough', () => {
expect(parsed.github?.event).toMatchObject(context.github.event);
});
it('accepts the issue_comment event with issue and comment fields', () => {
const context = {
after: {},
needs: {},
github: {
event_name: 'issue_comment',
sha: 'abc123',
ref: 'refs/heads/main',
ref_name: 'main',
ref_type: 'branch',
event: {
action: 'created',
issue: {
number: 123,
title: 'Issue title',
},
comment: {
id: 456,
body: 'Comment body',
},
},
},
workflow: {
id: 'workflow-id',
name: 'Workflow',
filename: 'workflow.yml',
url: 'https://expo.dev',
},
app: {
id: 'app-id',
slug: 'app-slug',
},
account: {
id: 'account-id',
name: 'account-name',
},
};
const parsed = StaticWorkflowInterpolationContextZ.parse(context);
expect(parsed.github?.event_name).toBe('issue_comment');
expect(parsed.github?.event).toMatchObject(context.github.event);
});
});
describe('fetchEasCliVersionsAsync', () => {
@@ -2,7 +2,14 @@ import { LoggerLevel } from '@expo/logger';
import { randomUUID } from 'crypto';
import Joi from 'joi';
import { ArchiveSourceType, BuildMode, Platform, Workflow } from '../common';
import {
ArchiveSourceType,
BuildMode,
BuildTrigger,
NativeBuilder,
Platform,
Workflow,
} from '../common';
import * as Ios from '../ios';
const joiOptions: Joi.ValidationOptions = {
@@ -21,6 +28,32 @@ const buildCredentials: Ios.BuildCredentials = {
},
};
function createNativeJob(overrides: object = {}): Record<string, unknown> {
return {
mode: BuildMode.BUILD,
builder: NativeBuilder.XCODE,
type: Workflow.GENERIC,
triggeredBy: BuildTrigger.GIT_BASED_INTEGRATION,
platform: Platform.IOS,
projectArchive: {
type: ArchiveSourceType.GIT,
gitCommitHash: '0123456789abcdef0123456789abcdef01234567',
gitRef: 'refs/heads/main',
},
projectRootDirectory: '.',
simulator: false,
secrets: {
credentialsByBundleIdentifier: {
'com.example.testapp': buildCredentials.testapp,
'com.example.testapp.widget': buildCredentials.testapp,
},
},
initiatingUserId: randomUUID(),
appId: randomUUID(),
...overrides,
};
}
describe('Ios.JobSchema', () => {
test('valid generic job', () => {
const genericJob = {
@@ -580,4 +613,186 @@ describe('Ios.JobSchema', () => {
expect(value.refreshAdHocProvisioningProfile).toBeUndefined();
expect(error).toBeFalsy();
});
test('returns a valid native job unchanged', () => {
const job = createNativeJob({
scheme: 'testapp',
buildConfiguration: 'Release',
projectFile: 'testapp.xcworkspace',
hooks: { after_checkout: [{ run: 'echo Hello, world!' }] },
});
const { value, error } = Ios.JobSchema.validate(job, joiOptions);
expect(error).toBeFalsy();
expect(value).toEqual(job);
});
test('returns a valid native simulator job without credentials unchanged', () => {
const job = createNativeJob({ simulator: true, secrets: {} });
const { value, error } = Ios.JobSchema.validate(job, joiOptions);
expect(error).toBeFalsy();
expect(value).toEqual(job);
});
test('native job requires simulator', () => {
const job = createNativeJob({ simulator: undefined });
const { error } = Ios.JobSchema.validate(job, joiOptions);
expect(error?.message).toBe('"simulator" is required');
});
test('native job defaults mode to build', () => {
const job = createNativeJob({ mode: undefined });
const { value, error } = Ios.JobSchema.validate(job, joiOptions);
expect(error).toBeFalsy();
expect(value.mode).toBe(BuildMode.BUILD);
});
test.each([BuildMode.RESIGN, BuildMode.CUSTOM, BuildMode.REPACK])(
'native job rejects mode %s',
mode => {
const job = createNativeJob({ mode });
const { error } = Ios.JobSchema.validate(job, joiOptions);
expect(error?.message).toBe('"mode" must be [build]');
}
);
test('job without builder is not a native job', () => {
const job = createNativeJob({ builder: undefined, buildProfile: 'production' });
const { value, error } = Ios.JobSchema.validate(job, joiOptions);
expect(error).toBeFalsy();
expect(value.buildProfile).toBe('production');
});
test.each([false, true])('native job requires secrets (simulator: %s)', simulator => {
const job = createNativeJob({ simulator, secrets: undefined });
const { error } = Ios.JobSchema.validate(job, joiOptions);
expect(error?.message).toBe('"secrets" is required');
});
test('native job requires credentialsByBundleIdentifier when it does not build for a simulator', () => {
const job = createNativeJob({ secrets: {} });
const { error } = Ios.JobSchema.validate(job, joiOptions);
expect(error?.message).toBe('"secrets.credentialsByBundleIdentifier" is required');
});
test('native job rejects an incomplete credentialsByBundleIdentifier entry', () => {
const job = createNativeJob({
secrets: {
credentialsByBundleIdentifier: {
'com.example.testapp': {
distributionCertificate: buildCredentials.testapp.distributionCertificate,
},
},
},
});
const { error } = Ios.JobSchema.validate(job, joiOptions);
expect(error?.message).toBe(
'"secrets.credentialsByBundleIdentifier.com.example.testapp.provisioningProfileBase64" is required'
);
});
test.each([false, true])(
'native job rejects an empty credentialsByBundleIdentifier (simulator: %s)',
simulator => {
const job = createNativeJob({ simulator, secrets: { credentialsByBundleIdentifier: {} } });
const { error } = Ios.JobSchema.validate(job, joiOptions);
expect(error?.message).toBe(
'"secrets.credentialsByBundleIdentifier" must have at least 1 key'
);
}
);
test('native job rejects secrets.buildCredentials', () => {
const job = createNativeJob({
secrets: {
buildCredentials,
credentialsByBundleIdentifier: { 'com.example.testapp': buildCredentials.testapp },
},
});
const { error } = Ios.JobSchema.validate(job, joiOptions);
expect(error?.message).toBe('"secrets.buildCredentials" is not allowed');
});
test('native job rejects a type other than generic', () => {
const job = createNativeJob({ type: Workflow.MANAGED });
const { error } = Ios.JobSchema.validate(job, joiOptions);
expect(error?.message).toBe('"type" must be [generic]');
});
test.each([NativeBuilder.GRADLE, 'unknown'])('native job rejects builder %s', builder => {
const job = createNativeJob({ builder });
const { error } = Ios.JobSchema.validate(job, joiOptions);
expect(error?.message).toBe('"builder" must be [xcode]');
});
test.each([
['buildProfile', 'production'],
['updates', { channel: 'main' }],
['cache', { disabled: false }],
['developmentClient', true],
['version', { buildNumber: '1' }],
['buildArtifactPaths', ['ios/build/*.log']],
['applicationArchivePath', 'ios/build/*.ipa'],
['username', 'testuser'],
['customBuildConfig', { path: 'production.yml' }],
['steps', [{ id: 'step1', run: 'echo Hello, world!', shell: 'sh' }]],
['outputs', { build_number: '1' }],
['experimental', { prebuildCommand: 'echo Hello, world!' }],
['githubTriggerOptions', { autoSubmit: true }],
[
'resign',
{ applicationArchiveSource: { type: ArchiveSourceType.URL, url: 'http://localhost:3000' } },
],
['refreshAdHocProvisioningProfile', true],
])('native job rejects %s', (field, fieldValue) => {
const job = createNativeJob({ [field]: fieldValue });
const { error } = Ios.JobSchema.validate(job, joiOptions);
expect(error?.message).toBe(`"${field}" is not allowed`);
});
test('native job accepts only the job fields listed here', () => {
const { keys } = Ios.JobSchema.describe().whens[0].then;
const acceptedFields = Object.keys(keys).filter(
field => keys[field].flags?.presence !== 'forbidden'
);
expect(new Set(acceptedFields)).toEqual(
new Set([
'mode',
'type',
'triggeredBy',
'projectArchive',
'platform',
'projectRootDirectory',
'builderEnvironment',
'scheme',
'buildConfiguration',
'hooks',
'ssh',
'expoBuildUrl',
'loggerLevel',
'initiatingUserId',
'appId',
'environment',
'workflowInterpolationContext',
'builder',
'simulator',
'secrets',
'projectFile',
])
);
});
});
@@ -1,3 +1,4 @@
import { NativeBuilder } from '../common';
import { Metadata, MetadataSchema } from '../metadata';
const validMetadata: Metadata = {
@@ -92,4 +93,29 @@ describe('MetadataSchema', () => {
'"credentialsSource" must be one of [local, remote]. "gitCommitHash" length must be 40 characters long. "gitCommitHash" must only contain hexadecimal characters. "gitCommitMessage" length must be less than or equal to 4096 characters long. "message" length must be less than or equal to 1024 characters long'
);
});
test('valid metadata with builder', () => {
const { value, error } = MetadataSchema.validate(
{ ...validMetadata, builder: NativeBuilder.GRADLE },
{
stripUnknown: true,
convert: true,
abortEarly: false,
}
);
expect(error).toBeFalsy();
expect(value.builder).toBe(NativeBuilder.GRADLE);
});
test('invalid builder', () => {
const { error } = MetadataSchema.validate(
{ ...validMetadata, builder: 'custom' },
{
stripUnknown: true,
convert: true,
abortEarly: false,
}
);
expect(error?.message).toEqual('"builder" must be one of [xcode, gradle]');
});
});
@@ -1,7 +1,7 @@
import { ArchiveSourceType, BuildTrigger, StaticWorkflowInterpolationContextZ } from '../common';
import { Generic } from '../generic';
function createContext() {
function createContext(eventType: 'new_error' | 'error_occurrence' = 'new_error') {
return {
after: {},
needs: {},
@@ -16,7 +16,7 @@ function createContext() {
observe: {
event: {
id: '123e4567-e89b-42d3-a456-426614174001',
type: 'new_error' as const,
type: eventType,
occurredAt: '2026-10-29T12:00:00.000Z',
appId: '123e4567-e89b-42d3-a456-426614174000',
fingerprint: { value: 'error-fingerprint', version: 'v1' },
@@ -31,23 +31,36 @@ function createContext() {
}
describe('Observe workflow context', () => {
it('preserves the event when validating a generic job', () => {
it.each(['new_error', 'error_occurrence'] as const)(
'preserves %s events when validating a generic job',
eventType => {
const context = createContext(eventType);
const job = {
projectArchive: { type: ArchiveSourceType.GIT, gitCommitHash: 'abc123', gitRef: null },
steps: [{ run: 'echo "${{ observe.event.exception.message }}"', shell: 'sh' }],
secrets: { robotAccessToken: 'token', environmentSecrets: [] },
expoDevUrl: context.workflow.url,
builderEnvironment: { image: 'ubuntu', env: {} },
triggeredBy: BuildTrigger.GIT_BASED_INTEGRATION,
appId: context.app.id,
initiatingUserId: '123e4567-e89b-42d3-a456-426614174002',
workflowInterpolationContext: context,
};
const parsed = Generic.JobZ.parse(job);
expect(parsed.workflowInterpolationContext).toEqual(context);
}
);
it('rejects unknown Observe event types', () => {
const context = createContext();
const job = {
projectArchive: { type: ArchiveSourceType.GIT, gitCommitHash: 'abc123', gitRef: null },
steps: [{ run: 'echo "${{ observe.event.exception.message }}"', shell: 'sh' }],
secrets: { robotAccessToken: 'token', environmentSecrets: [] },
expoDevUrl: context.workflow.url,
builderEnvironment: { image: 'ubuntu', env: {} },
triggeredBy: BuildTrigger.GIT_BASED_INTEGRATION,
appId: context.app.id,
initiatingUserId: '123e4567-e89b-42d3-a456-426614174002',
workflowInterpolationContext: context,
};
const parsed = Generic.JobZ.parse(job);
expect(parsed.workflowInterpolationContext).toEqual(context);
expect(
StaticWorkflowInterpolationContextZ.safeParse({
...context,
observe: { event: { ...context.observe.event, type: 'unknown' } },
}).success
).toBe(false);
});
it('accepts nullable event metadata and an omitted device OS', () => {
+20 -2
View File
@@ -17,6 +17,8 @@ import {
HooksSchema,
JobOutputs,
JobOutputsSchema,
NativeBuilder,
NativeJobForbiddenKeys,
Platform,
SshSettings,
SshSettingsSchema,
@@ -77,6 +79,7 @@ export interface BuildSecrets {
export interface Job {
mode: BuildMode;
builder?: NativeBuilder.GRADLE;
type: Workflow;
triggeredBy: BuildTrigger;
projectArchive: ArchiveSource;
@@ -142,7 +145,7 @@ const SecretsSchema = Joi.object({
robotAccessToken: Joi.string(),
});
export const JobSchema = Joi.object({
const BaseJobSchema = Joi.object({
mode: Joi.string()
.valid(BuildMode.BUILD, BuildMode.CUSTOM, BuildMode.REPACK)
.default(BuildMode.BUILD),
@@ -204,4 +207,19 @@ export const JobSchema = Joi.object({
workflowInterpolationContext: Joi.object().custom(workflowInterpolationContext =>
StaticWorkflowInterpolationContextZ.optional().parse(workflowInterpolationContext)
),
}).concat(CustomBuildConfigSchema);
});
const NonNativeJobSchema = BaseJobSchema.concat(CustomBuildConfigSchema);
const NativeJobSchema = BaseJobSchema.keys({
...NativeJobForbiddenKeys,
mode: Joi.string().valid(BuildMode.BUILD).default(BuildMode.BUILD),
type: Joi.string().valid(Workflow.GENERIC).required(),
builder: Joi.string().valid(NativeBuilder.GRADLE).required(),
}).fork('buildType', schema => schema.required());
export const JobSchema = Joi.object().when('.builder', {
is: Joi.exist(),
then: NativeJobSchema,
otherwise: NonNativeJobSchema,
});
+23 -2
View File
@@ -12,6 +12,11 @@ export enum BuildMode {
REPACK = 'repack',
}
export enum NativeBuilder {
XCODE = 'xcode',
GRADLE = 'gradle',
}
export enum Workflow {
GENERIC = 'generic',
MANAGED = 'managed',
@@ -194,7 +199,7 @@ export const CacheSchema = Joi.object({
const GitHubContextZ = z.object({
triggering_actor: z.string().optional(),
event_name: z.enum(['push', 'pull_request', 'workflow_dispatch', 'schedule']),
event_name: z.enum(['push', 'pull_request', 'workflow_dispatch', 'schedule', 'issue_comment']),
sha: z.string(),
ref: z.string(),
ref_name: z.string(),
@@ -347,7 +352,7 @@ const SentryContextZ = z.looseObject({
const ObserveContextZ = z.looseObject({
event: z.looseObject({
id: z.uuid(),
type: z.literal('new_error'),
type: z.enum(['new_error', 'error_occurrence']),
occurredAt: z.iso.datetime(),
appId: z.uuid(),
fingerprint: z.looseObject({
@@ -453,6 +458,22 @@ export const CustomBuildConfigSchema = Joi.object().when('.mode', {
}),
});
export const NativeJobForbiddenKeys = {
buildProfile: Joi.forbidden(),
updates: Joi.forbidden(),
cache: Joi.forbidden(),
developmentClient: Joi.forbidden(),
version: Joi.forbidden(),
buildArtifactPaths: Joi.forbidden(),
applicationArchivePath: Joi.forbidden(),
username: Joi.forbidden(),
customBuildConfig: Joi.forbidden(),
steps: Joi.forbidden(),
outputs: Joi.forbidden(),
experimental: Joi.forbidden(),
githubTriggerOptions: Joi.forbidden(),
};
export enum EasCliNpmTags {
STAGING = 'latest-eas-build-staging',
PRODUCTION = 'latest-eas-build',
+1
View File
@@ -14,6 +14,7 @@ export {
EnvironmentSecret,
EnvironmentSecretType,
Hooks,
NativeBuilder,
SshSettings,
Workflow,
Platform,
+41 -2
View File
@@ -17,6 +17,8 @@ import {
HooksSchema,
JobOutputs,
JobOutputsSchema,
NativeBuilder,
NativeJobForbiddenKeys,
Platform,
SshSettings,
SshSettingsSchema,
@@ -81,12 +83,14 @@ const BuilderEnvironmentSchema = Joi.object({
export interface BuildSecrets {
buildCredentials?: BuildCredentials;
credentialsByBundleIdentifier?: Record<string, TargetCredentials>;
environmentSecrets?: EnvironmentSecret[];
robotAccessToken?: string;
}
export interface Job {
mode: BuildMode;
builder?: NativeBuilder.XCODE;
type: Workflow;
triggeredBy: BuildTrigger;
projectArchive: ArchiveSource;
@@ -119,6 +123,7 @@ export interface Job {
scheme?: string;
buildConfiguration?: string;
projectFile?: string;
applicationArchivePath?: string;
username?: string;
@@ -158,7 +163,16 @@ const SecretsSchema = Joi.object({
robotAccessToken: Joi.string(),
});
export const JobSchema = Joi.object({
const CredentialsByBundleIdentifierSchema = Joi.object()
.pattern(Joi.string(), TargetCredentialsSchema)
.min(1);
const NativeSecretsSchema = SecretsSchema.keys({
buildCredentials: Joi.forbidden(),
credentialsByBundleIdentifier: CredentialsByBundleIdentifierSchema,
});
const BaseJobSchema = Joi.object({
mode: Joi.string()
.valid(...Object.values(BuildMode))
.default(BuildMode.BUILD),
@@ -242,4 +256,29 @@ export const JobSchema = Joi.object({
workflowInterpolationContext: Joi.object().custom(workflowInterpolationContext =>
StaticWorkflowInterpolationContextZ.optional().parse(workflowInterpolationContext)
),
}).concat(CustomBuildConfigSchema);
});
const NonNativeJobSchema = BaseJobSchema.concat(CustomBuildConfigSchema);
const NativeJobSchema = BaseJobSchema.keys({
...NativeJobForbiddenKeys,
resign: Joi.forbidden(),
refreshAdHocProvisioningProfile: Joi.forbidden(),
mode: Joi.string().valid(BuildMode.BUILD).default(BuildMode.BUILD),
type: Joi.string().valid(Workflow.GENERIC).required(),
builder: Joi.string().valid(NativeBuilder.XCODE).required(),
secrets: Joi.when('simulator', {
is: true,
then: NativeSecretsSchema.required(),
otherwise: NativeSecretsSchema.keys({
credentialsByBundleIdentifier: CredentialsByBundleIdentifierSchema.required(),
}).required(),
}),
projectFile: Joi.string(),
}).fork('simulator', schema => schema.required());
export const JobSchema = Joi.object().when('.builder', {
is: Joi.exist(),
then: NativeJobSchema,
otherwise: NonNativeJobSchema,
});
+4 -1
View File
@@ -1,6 +1,6 @@
import Joi from 'joi';
import { Workflow } from './common';
import { NativeBuilder, Workflow } from './common';
export type Metadata = {
/**
@@ -174,6 +174,8 @@ export type Metadata = {
* EAS env vars environment chosen for the job
*/
environment?: string;
builder?: NativeBuilder;
};
export const MetadataSchema = Joi.object({
@@ -208,6 +210,7 @@ export const MetadataSchema = Joi.object({
selectedImage: Joi.string(),
customNodeVersion: Joi.string(),
environment: Joi.string(),
builder: Joi.string().valid(...Object.values(NativeBuilder)),
});
export function sanitizeMetadata(metadata: object): Metadata {
+7
View File
@@ -1,5 +1,12 @@
# eas-cli
## 27.11.0
### Patch Changes
- Detect Factory Droid, Grok Bot, Claude Cowork, and Muse in EAS CLI telemetry. ([#4912](https://github.com/expo/eas-cli/pull/4912) by [@davidmokos](https://github.com/davidmokos))
- Mark the default device for each platform in `eas simulator:devices` and include `isDefault` in JSON output. ([#4895](https://github.com/expo/eas-cli/pull/4895) by [@gwdp](https://github.com/gwdp))
## 27.10.0
### Minor Changes
+149 -149
View File
File diff suppressed because it is too large. Load diff
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "eas-cli",
"version": "27.10.0",
"version": "27.11.0",
"description": "EAS command line tool",
"keywords": [
"cli",
@@ -48,12 +48,12 @@
"@expo/code-signing-certificates": "0.0.5",
"@expo/config": "55.0.10",
"@expo/config-plugins": "55.0.7",
"@expo/eas-build-job": "27.10.0",
"@expo/eas-json": "27.10.0",
"@expo/eas-build-job": "27.11.0",
"@expo/eas-json": "27.11.0",
"@expo/env": "^1.0.0",
"@expo/experimentation": "0.0.5",
"@expo/json-file": "8.3.3",
"@expo/logger": "27.10.0",
"@expo/logger": "27.11.0",
"@expo/multipart-body-parser": "2.0.0",
"@expo/osascript": "2.1.4",
"@expo/package-manager": "1.9.10",
@@ -65,7 +65,7 @@
"@expo/results": "1.0.0",
"@expo/rudder-sdk-node": "1.1.1",
"@expo/spawn-async": "1.7.2",
"@expo/steps": "27.10.0",
"@expo/steps": "27.11.0",
"@expo/timeago.js": "1.0.0",
"@oclif/core": "^4.8.3",
"@oclif/plugin-autocomplete": "^3.2.40",
@@ -73,7 +73,7 @@
"@sentry/node": "7.77.0",
"@urql/core": "4.0.11",
"@urql/exchange-retry": "1.2.0",
"agent-cli-detector": "0.1.7",
"agent-cli-detector": "0.1.8",
"ajv": "8.20.0",
"ajv-formats": "2.1.1",
"better-opn": "3.0.2",
+4
View File
@@ -1,5 +1,9 @@
# @expo/eas-json
## 27.11.0
No changes in this release.
## 27.10.0
No changes in this release.
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@expo/eas-json",
"version": "27.10.0",
"version": "27.11.0",
"description": "A library for interacting with eas.json",
"homepage": "https://github.com/expo/eas-cli",
"bugs": "https://github.com/expo/eas-cli/issues",
@@ -32,7 +32,7 @@
},
"dependencies": {
"@babel/code-frame": "7.23.5",
"@expo/eas-build-job": "27.10.0",
"@expo/eas-build-job": "27.11.0",
"chalk": "4.1.2",
"env-string": "1.0.1",
"fs-extra": "11.2.0",
+4
View File
@@ -1,5 +1,9 @@
# eas-cli-local-build-plugin
## 27.11.0
No changes in this release.
## 27.10.0
No changes in this release.
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "eas-cli-local-build-plugin",
"version": "27.10.0",
"version": "27.11.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,12 +26,12 @@
"clean": "rimraf node_modules dist coverage \"*.tsbuildinfo\""
},
"dependencies": {
"@expo/build-tools": "27.10.0",
"@expo/build-tools": "27.11.0",
"@expo/bunyan": "^4.0.1",
"@expo/eas-build-job": "27.10.0",
"@expo/logger": "27.10.0",
"@expo/eas-build-job": "27.11.0",
"@expo/logger": "27.11.0",
"@expo/spawn-async": "^1.7.2",
"@expo/turtle-spawn": "27.10.0",
"@expo/turtle-spawn": "27.11.0",
"chalk": "4.1.2",
"env-paths": "^2.2.1",
"fs-extra": "^11.2.0",
+4
View File
@@ -1,5 +1,9 @@
# @expo/logger
## 27.11.0
No changes in this release.
## 27.10.0
No changes in this release.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@expo/logger",
"version": "27.10.0",
"version": "27.11.0",
"bugs": "https://github.com/expo/eas-cli/issues",
"license": "BUSL-1.1",
"author": "Expo <[email protected]>",
+4
View File
@@ -1,5 +1,9 @@
# @expo/simulator-launcher
## 27.11.0
No changes in this release.
## 27.10.0
No changes in this release.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@expo/simulator-launcher",
"version": "27.10.0",
"version": "27.11.0",
"description": "Launch and claim Simulator sessions on EAS workers",
"bugs": "https://github.com/expo/eas-cli/issues",
"license": "BUSL-1.1",
+4
View File
@@ -1,5 +1,9 @@
# @expo/steps
## 27.11.0
No changes in this release.
## 27.10.0
No changes in this release.
Loaded 100 of 110 files, more files were not shown because too many files have changed in this diff. Show more