mirror of
https://github.com/expo/eas-cli.git
synced 2026-11-23 16:00:26 -10:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f208266373 | ||
|
|
a7e76a6cb5 | ||
|
|
fb96dc6b0f | ||
|
|
5fe8c311d7 | ||
|
|
6936b4f4e6 | ||
|
|
346cc030d8 | ||
|
|
8b683079c6 | ||
|
|
22f1fae8ec | ||
|
|
7abd3fe05a |
No files matched your search
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'@expo/build-tools': patch
|
||||
---
|
||||
|
||||
Send an `Idempotency-Key` header when creating device run session and sandbox artifact upload sessions, reuse it when an upload is retried, and stop retrying an upload that EAS rejects.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'eas-cli': patch
|
||||
---
|
||||
|
||||
Stop selecting the deprecated `Build.logFiles`, `Build.queuePosition`, `Build.initialQueuePosition`, `Build.estimatedWaitTimeLeftSeconds` and `AndroidSubmissionConfig.applicationIdentifier` GraphQL fields.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'@expo/build-tools': patch
|
||||
---
|
||||
|
||||
Report an iOS Simulator app install that fails with "Requires a Newer Version of iOS" as the user error `EAS_INSTALL_APPLICATION_REQUIRES_NEWER_IOS`, with a message that asks for a Simulator device whose iOS version meets the app's minimum, or a lower iOS deployment target. Other install failures still report `SERVER_ERROR`.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/eas-build-job': minor
|
||||
---
|
||||
|
||||
Add the native job schema for Android, with the `builder` field.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/eas-build-job': minor
|
||||
---
|
||||
|
||||
Add `builder` to the build metadata.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/eas-build-job': minor
|
||||
---
|
||||
|
||||
Add the `NativeBuilder` enum.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/build-tools': none
|
||||
---
|
||||
|
||||
Add the step function that signs and builds a native iOS project with fastlane gym.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/eas-build-job': minor
|
||||
---
|
||||
|
||||
Add the native job schema for iOS: `builder`, `projectFile`, and `secrets.credentialsByBundleIdentifier`.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/build-tools': none
|
||||
---
|
||||
|
||||
Add the step function that verifies the artifact of a native iOS build.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/build-tools': none
|
||||
---
|
||||
|
||||
Extract the custom build project preparation into `prepareProjectForStepsAsync`.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'eas-cli': minor
|
||||
---
|
||||
|
||||
Add `eas project:icon:unset`, and make `eas project:icon:set` use the icon from the app config when no path is given.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'eas-cli': minor
|
||||
---
|
||||
|
||||
Show the display name, slug and icon in `eas project:info`, and describe how `eas project:icon:set` processes the image.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'eas-cli': minor
|
||||
---
|
||||
|
||||
Add `eas project:name:set` to set the project display name shown on the EAS dashboard.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'@expo/build-tools': patch
|
||||
---
|
||||
|
||||
Send the reason when the worker stops a Simulator session: `idle_timeout` after the idle timeout, and `max_duration` when the session reaches its maximum duration, which now also stops the session through the worker stop route. A canceled build step sends no stop.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'eas-cli': patch
|
||||
---
|
||||
|
||||
Fix the log URL of `eas workflow:view` for a project that has a display name.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/build-tools': minor
|
||||
---
|
||||
|
||||
Build a native iOS project with Xcode when the build job carries `builder: xcode`.
|
||||
@@ -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"
|
||||
},
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Job, Metadata } from '@expo/eas-build-job';
|
||||
import { bunyan } from '@expo/logger';
|
||||
import {
|
||||
BuildRuntimePlatform,
|
||||
@@ -75,6 +76,20 @@ export function createStepContextMock({
|
||||
});
|
||||
}
|
||||
|
||||
export function createTestBuildContext<TJob extends Job>(
|
||||
job: TJob,
|
||||
metadata?: Metadata
|
||||
): BuildContext<TJob> {
|
||||
return new BuildContext(job, {
|
||||
env: { __API_SERVER_URL: 'http://api.expo.test' },
|
||||
logBuffer: { getLogs: () => [], getPhaseLogs: () => [] },
|
||||
logger: createMockLogger(),
|
||||
uploadArtifact: jest.fn(),
|
||||
workingdir: '/workingdir',
|
||||
metadata,
|
||||
});
|
||||
}
|
||||
|
||||
export function createCustomBuildContextMock(): CustomBuildContext {
|
||||
const ctx = new BuildContext(createTestIosJob({}), {
|
||||
env: {
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
BuildMode,
|
||||
BuildTrigger,
|
||||
Ios,
|
||||
NativeBuilder,
|
||||
Platform,
|
||||
Workflow,
|
||||
} from '@expo/eas-build-job';
|
||||
@@ -92,3 +93,31 @@ export function createTestIosJob({
|
||||
workflowInterpolationContext,
|
||||
};
|
||||
}
|
||||
|
||||
export function createTestXcodeJob(overrides: Record<string, unknown> = {}): Ios.Job {
|
||||
return {
|
||||
mode: BuildMode.BUILD,
|
||||
builder: NativeBuilder.XCODE,
|
||||
platform: Platform.IOS,
|
||||
triggeredBy: BuildTrigger.GIT_BASED_INTEGRATION,
|
||||
type: Workflow.GENERIC,
|
||||
projectArchive: {
|
||||
type: ArchiveSourceType.GIT,
|
||||
gitCommitHash: '0123456789abcdef0123456789abcdef01234567',
|
||||
gitRef: 'refs/heads/main',
|
||||
},
|
||||
projectRootDirectory: '.',
|
||||
simulator: false,
|
||||
secrets: {
|
||||
credentialsByBundleIdentifier: {
|
||||
'dev.expo.nativeapp': {
|
||||
provisioningProfileBase64: 'cHJvZmlsZQ==',
|
||||
distributionCertificate: { dataBase64: 'Y2VydGlmaWNhdGU=', password: '' },
|
||||
},
|
||||
},
|
||||
},
|
||||
appId: randomUUID(),
|
||||
initiatingUserId: randomUUID(),
|
||||
...overrides,
|
||||
} as Ios.Job;
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { BuildMode, Ios, Metadata } from '@expo/eas-build-job';
|
||||
import { vol } from 'memfs';
|
||||
|
||||
import { createTestBuildContext } from '../../__tests__/utils/context';
|
||||
import { createTestIosJob, createTestXcodeJob } from '../../__tests__/utils/job';
|
||||
import { prepareProjectSourcesAsync } from '../../common/projectSources';
|
||||
import { runBuilderWithHooksAsync } from '../common';
|
||||
import { runCustomBuildAsync } from '../custom';
|
||||
import iosBuilder from '../ios';
|
||||
|
||||
jest.mock('../common', () => ({ runBuilderWithHooksAsync: jest.fn(async () => ({})) }));
|
||||
jest.mock('../custom', () => ({ runCustomBuildAsync: jest.fn(async () => ({})) }));
|
||||
jest.mock('../../common/projectSources');
|
||||
jest.mock('../../ios/xcodeBuildLogs');
|
||||
jest.mock('../../utils/prepareBuildExecutable', () => ({ prepareExecutableAsync: jest.fn() }));
|
||||
|
||||
const METADATA = { appIdentifier: 'dev.expo.nativeapp' } as Metadata;
|
||||
|
||||
afterEach(() => {
|
||||
vol.reset();
|
||||
});
|
||||
|
||||
describe(iosBuilder, () => {
|
||||
it.each([
|
||||
['an unknown builder', { builder: 'unknown' }, '"builder" must be [xcode]'],
|
||||
['a builder and the custom mode', { mode: BuildMode.CUSTOM }, '"mode" must be [build]'],
|
||||
['a builder and the resign mode', { mode: BuildMode.RESIGN }, '"mode" must be [build]'],
|
||||
['a builder and the repack mode', { mode: BuildMode.REPACK }, '"mode" must be [build]'],
|
||||
])(
|
||||
'fails a job with %s in the validation of the Xcode runner',
|
||||
async (_description, overrides, expectedMessage) => {
|
||||
await expect(
|
||||
iosBuilder(createTestBuildContext(createTestXcodeJob(overrides), METADATA))
|
||||
).rejects.toMatchObject({
|
||||
trackingCode: 'NATIVE_INVALID_JOB',
|
||||
message: expect.stringContaining(expectedMessage),
|
||||
});
|
||||
expect(runCustomBuildAsync).not.toHaveBeenCalled();
|
||||
expect(runBuilderWithHooksAsync).not.toHaveBeenCalled();
|
||||
expect(prepareProjectSourcesAsync).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
|
||||
it('runs a valid job with the Xcode builder through the Xcode steps', async () => {
|
||||
jest.mocked(prepareProjectSourcesAsync).mockImplementation(async () => {
|
||||
vol.mkdirSync('/workingdir/env', { recursive: true });
|
||||
vol.fromJSON({ 'README.md': '' }, '/workingdir/temporary-custom-build');
|
||||
return { handled: true };
|
||||
});
|
||||
const ctx = createTestBuildContext(
|
||||
createTestXcodeJob({ simulator: true, secrets: {} }),
|
||||
METADATA
|
||||
);
|
||||
|
||||
await expect(iosBuilder(ctx)).rejects.toMatchObject({
|
||||
errorCode: 'NATIVE_XCODE_PROJECT_FILE_NOT_FOUND',
|
||||
});
|
||||
expect(runBuilderWithHooksAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('routes a job without a builder by its mode', async () => {
|
||||
await iosBuilder(createTestBuildContext(createTestIosJob(), METADATA));
|
||||
expect(runBuilderWithHooksAsync).toHaveBeenCalledTimes(1);
|
||||
|
||||
await iosBuilder(
|
||||
createTestBuildContext({ ...createTestIosJob(), mode: BuildMode.CUSTOM }, METADATA)
|
||||
);
|
||||
expect(runCustomBuildAsync).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,177 @@
|
||||
import { BuildMode, Ios, Metadata } from '@expo/eas-build-job';
|
||||
import { BuildStepGlobalContext } from '@expo/steps';
|
||||
import { vol } from 'memfs';
|
||||
|
||||
import { createTestBuildContext } from '../../__tests__/utils/context';
|
||||
import { createTestXcodeJob } from '../../__tests__/utils/job';
|
||||
import { prepareProjectSourcesAsync } from '../../common/projectSources';
|
||||
import { CustomBuildContext } from '../../customBuildContext';
|
||||
import { findAndUploadXcodeBuildLogsAsync } from '../../ios/xcodeBuildLogs';
|
||||
import { createXcodeWorkflowAsync, runXcodeBuildAsync, validateXcodeJob } from '../xcode';
|
||||
|
||||
jest.mock('../../common/projectSources');
|
||||
jest.mock('../../ios/xcodeBuildLogs');
|
||||
|
||||
const METADATA = { appIdentifier: 'dev.expo.nativeapp' } as Metadata;
|
||||
|
||||
async function createWorkflowAsync(
|
||||
job: Ios.Job,
|
||||
metadata?: Metadata
|
||||
): ReturnType<typeof createXcodeWorkflowAsync> {
|
||||
const customBuildCtx = new CustomBuildContext(createTestBuildContext(job, metadata));
|
||||
return await createXcodeWorkflowAsync(
|
||||
new BuildStepGlobalContext(customBuildCtx, false),
|
||||
customBuildCtx
|
||||
);
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vol.reset();
|
||||
});
|
||||
|
||||
describe(validateXcodeJob, () => {
|
||||
it('accepts a signed job with an app identifier, and keys the schema does not know', () => {
|
||||
expect(() =>
|
||||
validateXcodeJob(createTestXcodeJob({ keyFromANewerServer: true }), METADATA)
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it('accepts a simulator job without an app identifier', () => {
|
||||
expect(() =>
|
||||
validateXcodeJob(createTestXcodeJob({ simulator: true, secrets: {} }), undefined)
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['an unknown builder', { builder: 'unknown' }, '"builder" must be [xcode]'],
|
||||
['a mode other than build', { mode: BuildMode.CUSTOM }, '"mode" must be [build]'],
|
||||
['a field native jobs do not read', { buildProfile: 'production' }, '"buildProfile"'],
|
||||
['a value of another type', { simulator: 'false' }, '"simulator" must be a boolean'],
|
||||
['no credentials for a device build', { secrets: {} }, 'credentialsByBundleIdentifier'],
|
||||
])('rejects a job with %s', (_description, overrides, expectedMessage) => {
|
||||
expect(() => validateXcodeJob(createTestXcodeJob(overrides), METADATA)).toThrow(
|
||||
expect.objectContaining({
|
||||
trackingCode: 'NATIVE_INVALID_JOB',
|
||||
message: expect.stringContaining(expectedMessage),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects a signed job without an app identifier', () => {
|
||||
expect(() => validateXcodeJob(createTestXcodeJob(), undefined)).toThrow(
|
||||
expect.objectContaining({
|
||||
trackingCode: 'NATIVE_INVALID_JOB',
|
||||
message: expect.stringContaining('app identifier'),
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe(createXcodeWorkflowAsync, () => {
|
||||
it('builds a valid workflow from the public and the private functions', async () => {
|
||||
const workflow = await createWorkflowAsync(createTestXcodeJob(), METADATA);
|
||||
|
||||
expect(workflow.buildSteps.map(step => step.__metricsId)).toEqual([
|
||||
'eas/checkout',
|
||||
'eas/install_native_pods',
|
||||
'eas/detect_native_xcode',
|
||||
'eas/build_native_ios',
|
||||
'eas/verify_native_ios',
|
||||
'eas/update_resolved_version',
|
||||
'eas/upload_artifact',
|
||||
]);
|
||||
});
|
||||
|
||||
it('passes the values known from the job and the metadata to detection and verification', async () => {
|
||||
const workflow = await createWorkflowAsync(
|
||||
createTestXcodeJob({
|
||||
projectFile: 'App.xcworkspace',
|
||||
scheme: 'App',
|
||||
buildConfiguration: 'Staging',
|
||||
}),
|
||||
METADATA
|
||||
);
|
||||
|
||||
const rawInputsByMetricsId = Object.fromEntries(
|
||||
workflow.buildSteps.map(step => [
|
||||
step.__metricsId,
|
||||
Object.fromEntries((step.inputs ?? []).map(input => [input.id, input.rawValue])),
|
||||
])
|
||||
);
|
||||
expect(rawInputsByMetricsId['eas/detect_native_xcode']).toEqual({
|
||||
project_file: 'App.xcworkspace',
|
||||
scheme: 'App',
|
||||
build_configuration: 'Staging',
|
||||
expected_identifier: 'dev.expo.nativeapp',
|
||||
});
|
||||
expect(rawInputsByMetricsId['eas/verify_native_ios']).toMatchObject({
|
||||
expected_identifier: 'dev.expo.nativeapp',
|
||||
});
|
||||
});
|
||||
|
||||
it('runs the after_checkout hook of the job after the checkout step', async () => {
|
||||
const workflow = await createWorkflowAsync(
|
||||
createTestXcodeJob({ hooks: { after_checkout: [{ run: 'git submodule update --init' }] } }),
|
||||
METADATA
|
||||
);
|
||||
|
||||
const checkoutStep = workflow.buildSteps.find(step => step.__metricsId === 'eas/checkout')!;
|
||||
expect(workflow.hooksByAnchorStep.get(checkoutStep)).toMatchObject({
|
||||
anchor: 'checkout',
|
||||
before: [],
|
||||
after: [expect.anything()],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe(runXcodeBuildAsync, () => {
|
||||
it('validates the job before it prepares the project', async () => {
|
||||
const ctx = createTestBuildContext(createTestXcodeJob({ builder: 'unknown' }), METADATA);
|
||||
|
||||
await expect(runXcodeBuildAsync(ctx)).rejects.toMatchObject({
|
||||
trackingCode: 'NATIVE_INVALID_JOB',
|
||||
});
|
||||
expect(prepareProjectSourcesAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('logs each reason when the hooks of the job make the workflow invalid', async () => {
|
||||
vol.mkdirSync('/workingdir/env', { recursive: true });
|
||||
const ctx = createTestBuildContext(
|
||||
createTestXcodeJob({
|
||||
simulator: true,
|
||||
secrets: {},
|
||||
hooks: {
|
||||
after_checkout: [
|
||||
{ id: 'same', run: 'echo first' },
|
||||
{ id: 'same', run: 'echo second' },
|
||||
],
|
||||
},
|
||||
}),
|
||||
undefined
|
||||
);
|
||||
|
||||
await expect(runXcodeBuildAsync(ctx)).rejects.toThrow('Build workflow is invalid.');
|
||||
expect(ctx.logger.error).toHaveBeenCalledWith({
|
||||
err: expect.objectContaining({ message: 'Duplicated step IDs: "same"' }),
|
||||
});
|
||||
});
|
||||
|
||||
it('runs the steps, uploads the Xcode logs once and attaches the artifacts to a failure', async () => {
|
||||
jest.mocked(prepareProjectSourcesAsync).mockImplementation(async () => {
|
||||
vol.mkdirSync('/workingdir/env', { recursive: true });
|
||||
vol.fromJSON({ 'README.md': '' }, '/workingdir/temporary-custom-build');
|
||||
return { handled: true };
|
||||
});
|
||||
const ctx = createTestBuildContext(
|
||||
createTestXcodeJob({ simulator: true, secrets: {} }),
|
||||
undefined
|
||||
);
|
||||
|
||||
await expect(runXcodeBuildAsync(ctx)).rejects.toMatchObject({
|
||||
errorCode: 'NATIVE_XCODE_PROJECT_FILE_NOT_FOUND',
|
||||
artifacts: ctx.artifacts,
|
||||
});
|
||||
expect(vol.existsSync('/workingdir/build/README.md')).toBe(true);
|
||||
expect(findAndUploadXcodeBuildLogsAsync).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -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
|
||||
|
||||
@@ -6,6 +6,7 @@ import nullthrows from 'nullthrows';
|
||||
|
||||
import { runBuilderWithHooksAsync } from './common';
|
||||
import { runCustomBuildAsync } from './custom';
|
||||
import { runXcodeBuildAsync } from './xcode';
|
||||
import { eagerBundleAsync, shouldUseEagerBundle } from '../common/eagerBundle';
|
||||
import { prebuildAsync } from '../common/prebuild';
|
||||
import { JobHooksRef, setupAsync } from '../common/setup';
|
||||
@@ -48,6 +49,9 @@ const INSTALL_PODS_KILL_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
|
||||
class InstallPodsTimeoutError extends Error {}
|
||||
|
||||
export default async function iosBuilder(ctx: BuildContext<Ios.Job>): Promise<Artifacts> {
|
||||
if (ctx.job.builder !== undefined) {
|
||||
return await runXcodeBuildAsync(ctx);
|
||||
}
|
||||
if (ctx.job.mode === BuildMode.BUILD) {
|
||||
await prepareExecutableAsync(ctx);
|
||||
return await runBuilderWithHooksAsync(ctx, buildAsync);
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { Ios, Metadata, Step, SystemError } from '@expo/eas-build-job';
|
||||
import {
|
||||
BuildStepGlobalContext,
|
||||
BuildWorkflow,
|
||||
StepsConfigParser,
|
||||
createLocalCompositeFunctionLoader,
|
||||
errors,
|
||||
} from '@expo/steps';
|
||||
import path from 'node:path';
|
||||
|
||||
import { prepareProjectForStepsAsync } from './prepareProjectForSteps';
|
||||
import { Artifacts, BuildContext } from '../context';
|
||||
import { CustomBuildContext } from '../customBuildContext';
|
||||
import { findAndUploadXcodeBuildLogsAsync } from '../ios/xcodeBuildLogs';
|
||||
import { getEasFunctions } from '../steps/easFunctions';
|
||||
import { createBuildNativeIosBuildFunction } from '../steps/functions/native/xcode/buildNativeIos';
|
||||
import { createDetectNativeXcodeBuildFunction } from '../steps/functions/native/xcode/detectNativeXcode';
|
||||
import { createInstallNativePodsBuildFunction } from '../steps/functions/native/xcode/installNativePods';
|
||||
import { createVerifyNativeIosBuildFunction } from '../steps/functions/native/xcode/verifyNativeIos';
|
||||
|
||||
export async function runXcodeBuildAsync(ctx: BuildContext<Ios.Job>): Promise<Artifacts> {
|
||||
validateXcodeJob(ctx.job, ctx.metadata);
|
||||
|
||||
const customBuildCtx = new CustomBuildContext(ctx);
|
||||
await prepareProjectForStepsAsync(ctx, customBuildCtx.projectSourceDirectory);
|
||||
const globalContext = new BuildStepGlobalContext(customBuildCtx, /* skipCleanup */ false);
|
||||
let workflow: BuildWorkflow;
|
||||
try {
|
||||
workflow = await createXcodeWorkflowAsync(globalContext, customBuildCtx);
|
||||
} catch (parseError) {
|
||||
if (parseError instanceof errors.BuildWorkflowError) {
|
||||
for (const err of parseError.errors) {
|
||||
ctx.logger.error({ err });
|
||||
}
|
||||
}
|
||||
throw parseError;
|
||||
}
|
||||
try {
|
||||
await workflow.executeAsync();
|
||||
} catch (err: any) {
|
||||
err.artifacts = ctx.artifacts;
|
||||
throw err;
|
||||
} finally {
|
||||
await findAndUploadXcodeBuildLogsAsync(ctx, { logger: ctx.logger });
|
||||
await customBuildCtx.drainPendingMetricUploads();
|
||||
}
|
||||
return ctx.artifacts;
|
||||
}
|
||||
|
||||
export function validateXcodeJob(job: Ios.Job, metadata: Metadata | undefined): void {
|
||||
const { error } = Ios.JobSchema.validate(job, {
|
||||
allowUnknown: true,
|
||||
convert: false,
|
||||
abortEarly: false,
|
||||
});
|
||||
if (error) {
|
||||
throw new SystemError(
|
||||
`EAS created an Xcode build job that is not valid: ${error.message}. Your project did not cause this. Run the build again, and contact Expo support if it keeps failing.`,
|
||||
{ trackingCode: 'NATIVE_INVALID_JOB' }
|
||||
);
|
||||
}
|
||||
if (!job.simulator && !metadata?.appIdentifier) {
|
||||
throw new SystemError(
|
||||
'EAS created an Xcode build job for devices without the app identifier that the signed app must have. Your project did not cause this. Run the build again, and contact Expo support if it keeps failing.',
|
||||
{ trackingCode: 'NATIVE_INVALID_JOB' }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function createXcodeWorkflowAsync(
|
||||
globalContext: BuildStepGlobalContext,
|
||||
customBuildCtx: CustomBuildContext<Ios.Job>
|
||||
): Promise<BuildWorkflow> {
|
||||
const { job, metadata } = customBuildCtx;
|
||||
const steps: Step[] = [
|
||||
{ uses: 'eas/checkout' },
|
||||
{ uses: 'eas/install_native_pods' },
|
||||
{
|
||||
id: 'detect_native_xcode',
|
||||
uses: 'eas/detect_native_xcode',
|
||||
with: {
|
||||
project_file: job.projectFile,
|
||||
scheme: job.scheme,
|
||||
build_configuration: job.buildConfiguration,
|
||||
expected_identifier: metadata?.appIdentifier,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'build_native_ios',
|
||||
uses: 'eas/build_native_ios',
|
||||
with: {
|
||||
project_file: '${{ steps.detect_native_xcode.outputs.project_file }}',
|
||||
scheme: '${{ steps.detect_native_xcode.outputs.scheme }}',
|
||||
build_configuration: '${{ steps.detect_native_xcode.outputs.build_configuration }}',
|
||||
xcodeproj_path: '${{ steps.detect_native_xcode.outputs.xcodeproj_path }}',
|
||||
targets: '${{ steps.detect_native_xcode.outputs.targets }}',
|
||||
},
|
||||
},
|
||||
{
|
||||
uses: 'eas/verify_native_ios',
|
||||
with: {
|
||||
archive_path: '${{ steps.build_native_ios.outputs.archive_path }}',
|
||||
expected_identifier: metadata?.appIdentifier,
|
||||
},
|
||||
},
|
||||
{
|
||||
uses: 'eas/update_resolved_version',
|
||||
with: { application_archive_path: '${{ steps.build_native_ios.outputs.archive_path }}' },
|
||||
},
|
||||
{
|
||||
uses: 'eas/upload_artifact',
|
||||
with: {
|
||||
type: 'application-archive',
|
||||
path: '${{ steps.build_native_ios.outputs.archive_path }}',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
return await new StepsConfigParser(globalContext, {
|
||||
steps,
|
||||
hooks: job.hooks,
|
||||
externalFunctions: [
|
||||
...getEasFunctions(customBuildCtx),
|
||||
createInstallNativePodsBuildFunction(),
|
||||
createDetectNativeXcodeBuildFunction(),
|
||||
createBuildNativeIosBuildFunction(),
|
||||
createVerifyNativeIosBuildFunction(),
|
||||
],
|
||||
loadCompositeFunction: createLocalCompositeFunctionLoader(
|
||||
path.join(customBuildCtx.projectSourceDirectory, job.projectRootDirectory ?? '.'),
|
||||
{ logger: customBuildCtx.logger }
|
||||
),
|
||||
}).parseAsync();
|
||||
}
|
||||
@@ -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, {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
+440
@@ -0,0 +1,440 @@
|
||||
import { vol } from 'memfs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
|
||||
import { createGlobalContextMock } from '../../../../../__tests__/utils/context';
|
||||
import IosCredentialsManager from '../../../../utils/ios/credentials/manager';
|
||||
import { DistributionType } from '../../../../utils/ios/credentials/provisioningProfile';
|
||||
import { runFastlaneGym } from '../../../../utils/ios/fastlane';
|
||||
import { readBuildSettingsByTargetNameAsync } from '../../../../utils/ios/xcodeProject/buildSettings';
|
||||
import {
|
||||
assertSigningBuildSettingsAreEffective,
|
||||
writeSigningBuildSettingsAsync,
|
||||
} from '../../../../utils/ios/xcodeProject/signing';
|
||||
import { createBuildNativeIosBuildFunction } from '../buildNativeIos';
|
||||
|
||||
jest.mock('../../../../utils/ios/credentials/manager');
|
||||
jest.mock('../../../../utils/ios/fastlane');
|
||||
jest.mock('../../../../utils/ios/xcodeProject/buildSettings');
|
||||
jest.mock('../../../../utils/ios/xcodeProject/signing');
|
||||
|
||||
const projectDirectory = '/project';
|
||||
const TARGETS = [
|
||||
{ id: 'APP', name: 'NativeApp', bundleIdentifier: 'dev.expo.nativeapp' },
|
||||
{ id: 'WIDGET', name: 'Widget', bundleIdentifier: 'dev.expo.nativeapp.widget' },
|
||||
];
|
||||
const DISTRIBUTION_CERTIFICATE = { dataBase64: 'Y2VydGlmaWNhdGU=', password: '' };
|
||||
const APP_CREDENTIALS = {
|
||||
provisioningProfileBase64: 'YXBw',
|
||||
distributionCertificate: DISTRIBUTION_CERTIFICATE,
|
||||
};
|
||||
const WIDGET_CREDENTIALS = {
|
||||
provisioningProfileBase64: 'd2lkZ2V0',
|
||||
distributionCertificate: DISTRIBUTION_CERTIFICATE,
|
||||
};
|
||||
|
||||
function infoPlist(bundleIdentifier: string): string {
|
||||
return `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<plist version="1.0"><dict><key>CFBundleIdentifier</key><string>${bundleIdentifier}</string></dict></plist>`;
|
||||
}
|
||||
|
||||
function createBuildStep({
|
||||
job,
|
||||
projectFile = '/project/NativeApp.xcodeproj',
|
||||
targets = TARGETS,
|
||||
}: {
|
||||
job: Record<string, unknown>;
|
||||
projectFile?: string;
|
||||
targets?: typeof TARGETS;
|
||||
}): ReturnType<
|
||||
ReturnType<typeof createBuildNativeIosBuildFunction>['createBuildStepFromFunctionCall']
|
||||
> {
|
||||
const globalCtx = createGlobalContextMock({
|
||||
projectTargetDirectory: projectDirectory,
|
||||
staticContextContent: { job },
|
||||
});
|
||||
return createBuildNativeIosBuildFunction().createBuildStepFromFunctionCall(globalCtx, {
|
||||
callInputs: {
|
||||
project_file: projectFile,
|
||||
scheme: 'NativeApp',
|
||||
build_configuration: 'Release',
|
||||
xcodeproj_path: '/project/NativeApp.xcodeproj',
|
||||
targets,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function mockGymProducing(relativePaths: Record<string, string>): { gymfile: () => string } {
|
||||
let gymfileDirectory = '';
|
||||
jest.mocked(runFastlaneGym).mockImplementation(async options => {
|
||||
gymfileDirectory = options.gymfileDirectory!;
|
||||
vol.fromJSON(relativePaths, gymfileDirectory);
|
||||
});
|
||||
return {
|
||||
gymfile: () => vol.readFileSync(path.join(gymfileDirectory, 'Gymfile'), 'utf-8') as string,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vol.fromJSON({ [path.join(os.tmpdir(), 'placeholder')]: '', '/project/placeholder': '' });
|
||||
jest.mocked(readBuildSettingsByTargetNameAsync).mockResolvedValue({ NativeApp: {}, Widget: {} });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vol.reset();
|
||||
});
|
||||
|
||||
describe(createBuildNativeIosBuildFunction, () => {
|
||||
it('signs every detected target with the credentials of its bundle identifier and archives', async () => {
|
||||
jest.mocked(IosCredentialsManager.prototype.prepare).mockResolvedValue({
|
||||
keychainPath: '/keychains/build.keychain',
|
||||
distributionType: DistributionType.APP_STORE,
|
||||
teamId: 'ABCDE12345',
|
||||
targetProvisioningProfiles: {
|
||||
NativeApp: { name: 'App Profile', uuid: 'app-uuid', teamId: 'ABCDE12345' },
|
||||
Widget: { name: 'Widget Profile', uuid: 'widget-uuid', teamId: 'ABCDE12345' },
|
||||
},
|
||||
} as any);
|
||||
const gym = mockGymProducing({ 'output/NativeApp.ipa': '' });
|
||||
const step = createBuildStep({
|
||||
job: {
|
||||
simulator: false,
|
||||
secrets: {
|
||||
credentialsByBundleIdentifier: {
|
||||
'dev.expo.nativeapp.widget': WIDGET_CREDENTIALS,
|
||||
'dev.expo.nativeapp': APP_CREDENTIALS,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(IosCredentialsManager).toHaveBeenCalledWith({
|
||||
NativeApp: APP_CREDENTIALS,
|
||||
Widget: WIDGET_CREDENTIALS,
|
||||
});
|
||||
const targetSignings = [
|
||||
{
|
||||
target: TARGETS[0],
|
||||
buildSettings: {
|
||||
PROVISIONING_PROFILE_SPECIFIER: 'App Profile',
|
||||
DEVELOPMENT_TEAM: 'ABCDE12345',
|
||||
CODE_SIGN_IDENTITY: 'iPhone Distribution',
|
||||
CODE_SIGN_STYLE: 'Manual',
|
||||
},
|
||||
},
|
||||
{
|
||||
target: TARGETS[1],
|
||||
buildSettings: {
|
||||
PROVISIONING_PROFILE_SPECIFIER: 'Widget Profile',
|
||||
DEVELOPMENT_TEAM: 'ABCDE12345',
|
||||
CODE_SIGN_IDENTITY: 'iPhone Distribution',
|
||||
CODE_SIGN_STYLE: 'Manual',
|
||||
},
|
||||
},
|
||||
];
|
||||
expect(writeSigningBuildSettingsAsync).toHaveBeenCalledWith({
|
||||
xcodeprojPath: '/project/NativeApp.xcodeproj',
|
||||
buildConfiguration: 'Release',
|
||||
targetSignings,
|
||||
});
|
||||
expect(readBuildSettingsByTargetNameAsync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
xcodeprojPath: '/project/NativeApp.xcodeproj',
|
||||
targetNames: ['NativeApp', 'Widget'],
|
||||
buildConfiguration: 'Release',
|
||||
})
|
||||
);
|
||||
expect(assertSigningBuildSettingsAreEffective).toHaveBeenCalledWith({
|
||||
buildConfiguration: 'Release',
|
||||
targetSignings,
|
||||
effectiveBuildSettingsByTargetName: { NativeApp: {}, Widget: {} },
|
||||
});
|
||||
const gymfile = gym.gymfile();
|
||||
expect(gymfile).toContain('project("/project/NativeApp.xcodeproj")');
|
||||
expect(gymfile).toContain('xcargs("-skipPackagePluginValidation -skipMacroValidation")');
|
||||
expect(gymfile).toContain('scheme("NativeApp")');
|
||||
expect(gymfile).toContain('configuration("Release")');
|
||||
expect(gymfile).toContain('method: "app-store"');
|
||||
expect(gymfile).toContain('"dev.expo.nativeapp" => "app-uuid"');
|
||||
expect(gymfile).toContain('"dev.expo.nativeapp.widget" => "widget-uuid"');
|
||||
expect(gymfile).toContain('--keychain /keychains/build.keychain');
|
||||
expect(step.outputById.archive_path.value).toMatch(
|
||||
/native-ios-build-[^/]+\/output\/NativeApp\.ipa$/
|
||||
);
|
||||
expect(path.isAbsolute(step.outputById.archive_path.value as string)).toBe(true);
|
||||
});
|
||||
|
||||
it('uses the common name of the certificate as the identity for a development profile', async () => {
|
||||
jest.mocked(IosCredentialsManager.prototype.prepare).mockResolvedValue({
|
||||
keychainPath: '/keychains/build.keychain',
|
||||
distributionType: DistributionType.DEVELOPMENT,
|
||||
teamId: 'ABCDE12345',
|
||||
targetProvisioningProfiles: {
|
||||
NativeApp: {
|
||||
name: 'Development Profile',
|
||||
uuid: 'app-uuid',
|
||||
teamId: 'ABCDE12345',
|
||||
certificateCommonName: 'Apple Development: Example (ABCDE12345)',
|
||||
},
|
||||
},
|
||||
} as any);
|
||||
mockGymProducing({ 'output/NativeApp.ipa': '' });
|
||||
const step = createBuildStep({
|
||||
job: {
|
||||
simulator: false,
|
||||
secrets: { credentialsByBundleIdentifier: { 'dev.expo.nativeapp': APP_CREDENTIALS } },
|
||||
},
|
||||
targets: [TARGETS[0]],
|
||||
});
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(
|
||||
jest.mocked(writeSigningBuildSettingsAsync).mock.calls[0][0].targetSignings[0].buildSettings
|
||||
.CODE_SIGN_IDENTITY
|
||||
).toBe('Apple Development: Example (ABCDE12345)');
|
||||
});
|
||||
|
||||
it('builds for the simulator without credentials and returns the app with the bundle identifier', async () => {
|
||||
const products = 'derived-data/Build/Products/Release-iphonesimulator';
|
||||
const gym = mockGymProducing({
|
||||
[`${products}/Clip.app/Info.plist`]: infoPlist('dev.expo.nativeapp.clip'),
|
||||
[`${products}/NativeApp.app/Info.plist`]: infoPlist('dev.expo.nativeapp'),
|
||||
});
|
||||
const step = createBuildStep({
|
||||
job: { simulator: true, secrets: {} },
|
||||
projectFile: '/project/NativeApp.xcworkspace',
|
||||
targets: [TARGETS[0]],
|
||||
});
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(IosCredentialsManager).not.toHaveBeenCalled();
|
||||
expect(writeSigningBuildSettingsAsync).not.toHaveBeenCalled();
|
||||
const gymfile = gym.gymfile();
|
||||
expect(gymfile).toContain('workspace("/project/NativeApp.xcworkspace")');
|
||||
expect(gymfile).toContain('destination("generic/platform=iOS Simulator")');
|
||||
expect(gymfile).toContain('xcargs("-skipPackagePluginValidation -skipMacroValidation")');
|
||||
expect(gymfile).not.toContain('export_options');
|
||||
expect(step.outputById.archive_path.value).toMatch(/Release-iphonesimulator\/NativeApp\.app$/);
|
||||
expect(runFastlaneGym).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
workingDir: projectDirectory,
|
||||
gymfileDirectory: expect.stringContaining('native-ios-build-'),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('fails before it prepares credentials when a target has none', async () => {
|
||||
const step = createBuildStep({
|
||||
job: {
|
||||
simulator: false,
|
||||
secrets: { credentialsByBundleIdentifier: { 'dev.expo.nativeapp': APP_CREDENTIALS } },
|
||||
},
|
||||
});
|
||||
|
||||
await expect(step.executeAsync()).rejects.toMatchObject({
|
||||
errorCode: 'NATIVE_XCODE_MISSING_CREDENTIALS',
|
||||
message: expect.stringContaining(
|
||||
'no credentials for "dev.expo.nativeapp.widget" (target "Widget")'
|
||||
),
|
||||
});
|
||||
expect(IosCredentialsManager).not.toHaveBeenCalled();
|
||||
expect(runFastlaneGym).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('fails with a user error that points to the logs when the Xcode build fails', async () => {
|
||||
const gymError = new Error('fastlane exited with non-zero code: 1');
|
||||
jest.mocked(runFastlaneGym).mockRejectedValue(gymError);
|
||||
const step = createBuildStep({ job: { simulator: true }, targets: [TARGETS[0]] });
|
||||
|
||||
await expect(step.executeAsync()).rejects.toMatchObject({
|
||||
errorCode: 'NATIVE_XCODE_BUILD_FAILED',
|
||||
message: expect.stringContaining('The errors are in the "Build with Xcode" step.'),
|
||||
cause: gymError,
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects a targets input that is not the list the detection step produces', async () => {
|
||||
const step = createBuildStep({
|
||||
job: { simulator: true },
|
||||
targets: [{ id: 'APP', name: 'NativeApp' }] as any,
|
||||
});
|
||||
|
||||
await expect(step.executeAsync()).rejects.toThrow(/bundleIdentifier/);
|
||||
expect(runFastlaneGym).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('fails when the build produced no archive', async () => {
|
||||
mockGymProducing({ 'output/placeholder': '' });
|
||||
jest.mocked(IosCredentialsManager.prototype.prepare).mockResolvedValue({
|
||||
keychainPath: '/keychains/build.keychain',
|
||||
distributionType: DistributionType.AD_HOC,
|
||||
teamId: 'ABCDE12345',
|
||||
targetProvisioningProfiles: {
|
||||
NativeApp: { name: 'App Profile', uuid: 'app-uuid', teamId: 'ABCDE12345' },
|
||||
},
|
||||
} as any);
|
||||
const step = createBuildStep({
|
||||
job: {
|
||||
simulator: false,
|
||||
secrets: { credentialsByBundleIdentifier: { 'dev.expo.nativeapp': APP_CREDENTIALS } },
|
||||
},
|
||||
targets: [TARGETS[0]],
|
||||
});
|
||||
|
||||
await expect(step.executeAsync()).rejects.toMatchObject({
|
||||
errorCode: 'NATIVE_XCODE_NO_BUILD_OUTPUT',
|
||||
});
|
||||
});
|
||||
|
||||
describe('the iCloud container environment of the export', () => {
|
||||
function entitlementsWithEnvironment(environment: string): string {
|
||||
return `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<plist version="1.0"><dict><key>com.apple.developer.icloud-container-environment</key><string>${environment}</string></dict></plist>`;
|
||||
}
|
||||
const ENTITLEMENTS_WITHOUT_ENVIRONMENT = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<plist version="1.0"><dict><key>aps-environment</key><string>production</string></dict></plist>`;
|
||||
|
||||
async function exportAsync({
|
||||
applicationBuildSettings,
|
||||
widgetBuildSettings = {},
|
||||
files = {},
|
||||
}: {
|
||||
applicationBuildSettings: Record<string, string>;
|
||||
widgetBuildSettings?: Record<string, string>;
|
||||
files?: Record<string, string>;
|
||||
}): Promise<{ gymfile: string; warn: jest.Mock }> {
|
||||
jest.mocked(IosCredentialsManager.prototype.prepare).mockResolvedValue({
|
||||
keychainPath: '/keychains/build.keychain',
|
||||
distributionType: DistributionType.AD_HOC,
|
||||
teamId: 'ABCDE12345',
|
||||
targetProvisioningProfiles: {
|
||||
NativeApp: { name: 'App Profile', uuid: 'app-uuid', teamId: 'ABCDE12345' },
|
||||
Widget: { name: 'Widget Profile', uuid: 'widget-uuid', teamId: 'ABCDE12345' },
|
||||
},
|
||||
} as any);
|
||||
jest
|
||||
.mocked(readBuildSettingsByTargetNameAsync)
|
||||
.mockResolvedValue({ NativeApp: applicationBuildSettings, Widget: widgetBuildSettings });
|
||||
vol.fromJSON(files);
|
||||
const gym = mockGymProducing({ 'output/NativeApp.ipa': '' });
|
||||
const step = createBuildStep({
|
||||
job: {
|
||||
simulator: false,
|
||||
secrets: {
|
||||
credentialsByBundleIdentifier: {
|
||||
'dev.expo.nativeapp': APP_CREDENTIALS,
|
||||
'dev.expo.nativeapp.widget': WIDGET_CREDENTIALS,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
return { gymfile: gym.gymfile(), warn: jest.mocked(step.ctx.logger.warn) };
|
||||
}
|
||||
|
||||
it.each([
|
||||
[
|
||||
'a path relative to the source root',
|
||||
{ SRCROOT: '/project/app', CODE_SIGN_ENTITLEMENTS: 'NativeApp/NativeApp.entitlements' },
|
||||
'/project/app/NativeApp/NativeApp.entitlements',
|
||||
],
|
||||
[
|
||||
'an absolute path',
|
||||
{ SRCROOT: '/project/app', CODE_SIGN_ENTITLEMENTS: '/project/Shared/App.entitlements' },
|
||||
'/project/Shared/App.entitlements',
|
||||
],
|
||||
])(
|
||||
'passes the value of the entitlements file of the application target, given as %s',
|
||||
async (_description, applicationBuildSettings, entitlementsPath) => {
|
||||
const { gymfile, warn } = await exportAsync({
|
||||
applicationBuildSettings,
|
||||
files: { [entitlementsPath]: entitlementsWithEnvironment('Development') },
|
||||
});
|
||||
|
||||
expect(gymfile).toContain('iCloudContainerEnvironment: "Development"');
|
||||
expect(warn).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
|
||||
it.each([
|
||||
['the target has no entitlements file', { SRCROOT: '/project' }, {}],
|
||||
[
|
||||
'the entitlements file does not name an environment',
|
||||
{ SRCROOT: '/project', CODE_SIGN_ENTITLEMENTS: 'NativeApp.entitlements' },
|
||||
{ '/project/NativeApp.entitlements': ENTITLEMENTS_WITHOUT_ENVIRONMENT },
|
||||
],
|
||||
[
|
||||
'the environment in the entitlements file is empty',
|
||||
{ SRCROOT: '/project', CODE_SIGN_ENTITLEMENTS: 'NativeApp.entitlements' },
|
||||
{ '/project/NativeApp.entitlements': entitlementsWithEnvironment('') },
|
||||
],
|
||||
])('passes no value and does not warn when %s', async (_description, settings, files) => {
|
||||
const { gymfile, warn } = await exportAsync({ applicationBuildSettings: settings, files });
|
||||
|
||||
expect(gymfile).not.toContain('iCloudContainerEnvironment');
|
||||
expect(warn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['uses the value of the application target', 'NativeApp.entitlements', true],
|
||||
['passes no value when only another target names one', undefined, false],
|
||||
])(
|
||||
'reads the application target only: %s',
|
||||
async (_description, applicationEntitlements, isEnvironmentExpected) => {
|
||||
const { gymfile } = await exportAsync({
|
||||
applicationBuildSettings: {
|
||||
SRCROOT: '/project',
|
||||
...(applicationEntitlements && { CODE_SIGN_ENTITLEMENTS: applicationEntitlements }),
|
||||
},
|
||||
widgetBuildSettings: {
|
||||
SRCROOT: '/project',
|
||||
CODE_SIGN_ENTITLEMENTS: 'Widget.entitlements',
|
||||
},
|
||||
files: {
|
||||
'/project/NativeApp.entitlements': entitlementsWithEnvironment('Development'),
|
||||
'/project/Widget.entitlements': entitlementsWithEnvironment('Production'),
|
||||
},
|
||||
});
|
||||
|
||||
expect(gymfile).not.toContain('"Production"');
|
||||
expect(gymfile.includes('iCloudContainerEnvironment: "Development"')).toBe(
|
||||
isEnvironmentExpected
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
it.each([
|
||||
['is missing', {}],
|
||||
['is not a property list', { '/project/App.entitlements': 'not a property list' }],
|
||||
[
|
||||
'holds null in place of a dictionary',
|
||||
{ '/project/App.entitlements': '<plist version="1.0"><null/></plist>' },
|
||||
],
|
||||
])(
|
||||
'warns and exports without a value when the entitlements file %s',
|
||||
async (_description, files) => {
|
||||
const { gymfile, warn } = await exportAsync({
|
||||
applicationBuildSettings: {
|
||||
SRCROOT: '/project',
|
||||
CODE_SIGN_ENTITLEMENTS: 'App.entitlements',
|
||||
},
|
||||
files,
|
||||
});
|
||||
|
||||
expect(gymfile).not.toContain('iCloudContainerEnvironment');
|
||||
expect(warn).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.stringContaining(
|
||||
'could not read the entitlements file "/project/App.entitlements"'
|
||||
)
|
||||
);
|
||||
}
|
||||
);
|
||||
});
|
||||
});
|
||||
+288
@@ -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\./),
|
||||
});
|
||||
});
|
||||
});
|
||||
+43
@@ -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();
|
||||
});
|
||||
});
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
jest.unmock('fs');
|
||||
jest.unmock('node:fs');
|
||||
jest.unmock('fs/promises');
|
||||
jest.unmock('node:fs/promises');
|
||||
|
||||
import { createGlobalContextMock } from '../../../../../__tests__/utils/context';
|
||||
import { createVerifyNativeIosBuildFunction } from '../verifyNativeIos';
|
||||
|
||||
const IPA_PATH = path.join(__dirname, '../../../__tests__/fixtures/SmallestAppExample.ipa');
|
||||
const IPA_BUNDLE_IDENTIFIER = 'dev.expo.SmallestAppExample';
|
||||
|
||||
async function writeAppAsync(bundleIdentifier: string, platformName: string): Promise<string> {
|
||||
const directory = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'verify-native-ios-'));
|
||||
const appPath = path.join(directory, 'NativeApp.app');
|
||||
await fs.promises.mkdir(appPath);
|
||||
await fs.promises.writeFile(
|
||||
path.join(appPath, 'Info.plist'),
|
||||
`<?xml version="1.0" encoding="UTF-8"?>
|
||||
<plist version="1.0"><dict>
|
||||
<key>CFBundleIdentifier</key><string>${bundleIdentifier}</string>
|
||||
<key>DTPlatformName</key><string>${platformName}</string>
|
||||
</dict></plist>`
|
||||
);
|
||||
return appPath;
|
||||
}
|
||||
|
||||
async function verifyAsync({
|
||||
simulator,
|
||||
archivePath,
|
||||
expectedIdentifier,
|
||||
}: {
|
||||
simulator: boolean;
|
||||
archivePath: string;
|
||||
expectedIdentifier?: string;
|
||||
}): Promise<void> {
|
||||
const globalCtx = createGlobalContextMock({ staticContextContent: { job: { simulator } } });
|
||||
await createVerifyNativeIosBuildFunction()
|
||||
.createBuildStepFromFunctionCall(globalCtx, {
|
||||
callInputs: { archive_path: archivePath, expected_identifier: expectedIdentifier },
|
||||
})
|
||||
.executeAsync();
|
||||
}
|
||||
|
||||
describe(createVerifyNativeIosBuildFunction, () => {
|
||||
it('accepts an IPA for devices with the expected identifier', async () => {
|
||||
await expect(
|
||||
verifyAsync({
|
||||
simulator: false,
|
||||
archivePath: IPA_PATH,
|
||||
expectedIdentifier: IPA_BUNDLE_IDENTIFIER,
|
||||
})
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('accepts a simulator app with the expected identifier', async () => {
|
||||
await expect(
|
||||
verifyAsync({
|
||||
simulator: true,
|
||||
archivePath: await writeAppAsync('dev.expo.nativeapp', 'iphonesimulator'),
|
||||
expectedIdentifier: 'dev.expo.nativeapp',
|
||||
})
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('accepts an artifact when no identifier is expected', async () => {
|
||||
await expect(verifyAsync({ simulator: false, archivePath: IPA_PATH })).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('fails when the identifier of the artifact differs', async () => {
|
||||
await expect(
|
||||
verifyAsync({ simulator: false, archivePath: IPA_PATH, expectedIdentifier: 'dev.expo.other' })
|
||||
).rejects.toMatchObject({
|
||||
errorCode: 'NATIVE_XCODE_ARTIFACT_IDENTIFIER_MISMATCH',
|
||||
message: expect.stringMatching(/"dev\.expo\.SmallestAppExample".*"dev\.expo\.other"/),
|
||||
});
|
||||
});
|
||||
|
||||
it('fails when a simulator build produced an artifact for devices', async () => {
|
||||
await expect(verifyAsync({ simulator: true, archivePath: IPA_PATH })).rejects.toMatchObject({
|
||||
errorCode: 'NATIVE_XCODE_ARTIFACT_PLATFORM_MISMATCH',
|
||||
});
|
||||
});
|
||||
|
||||
it('fails when a device build produced an artifact for the simulator', async () => {
|
||||
await expect(
|
||||
verifyAsync({
|
||||
simulator: false,
|
||||
archivePath: await writeAppAsync('dev.expo.nativeapp', 'iphonesimulator'),
|
||||
})
|
||||
).rejects.toMatchObject({
|
||||
errorCode: 'NATIVE_XCODE_ARTIFACT_PLATFORM_MISMATCH',
|
||||
message: expect.stringContaining('"iphonesimulator"'),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,339 @@
|
||||
import { Ios, UserError } from '@expo/eas-build-job';
|
||||
import {
|
||||
BuildFunction,
|
||||
BuildStepContext,
|
||||
BuildStepEnv,
|
||||
BuildStepInput,
|
||||
BuildStepInputValueTypeName,
|
||||
BuildStepOutput,
|
||||
} from '@expo/steps';
|
||||
import { templateString } from '@expo/template-file';
|
||||
import fg from 'fast-glob';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { GymfileArchiveTemplate } from '../../../../templates/GymfileArchive';
|
||||
import { GymfileSimulatorTemplate } from '../../../../templates/GymfileSimulator';
|
||||
import IosCredentialsManager from '../../../utils/ios/credentials/manager';
|
||||
import { DistributionType } from '../../../utils/ios/credentials/provisioningProfile';
|
||||
import { runFastlaneGym } from '../../../utils/ios/fastlane';
|
||||
import { readBuildSettingsByTargetNameAsync } from '../../../utils/ios/xcodeProject/buildSettings';
|
||||
import { XcodeTargetWithBundleIdentifier } from '../../../utils/ios/xcodeProject/pbxproj';
|
||||
import { isWorkspace } from '../../../utils/ios/xcodeProject/projectFile';
|
||||
import {
|
||||
assertSigningBuildSettingsAreEffective,
|
||||
writeSigningBuildSettingsAsync,
|
||||
} from '../../../utils/ios/xcodeProject/signing';
|
||||
import { parseInfoPlistBuffer } from '../../readIpaInfo';
|
||||
|
||||
const STEP_NAME = 'Build with Xcode';
|
||||
|
||||
interface ExportOptions {
|
||||
keychainPath: string;
|
||||
distributionType: DistributionType;
|
||||
provisioningProfileUuidByBundleIdentifier: Record<string, string>;
|
||||
iCloudContainerEnvironment?: string;
|
||||
}
|
||||
|
||||
export function createBuildNativeIosBuildFunction(): BuildFunction {
|
||||
return new BuildFunction({
|
||||
namespace: 'eas',
|
||||
id: 'build_native_ios',
|
||||
name: STEP_NAME,
|
||||
__metricsId: 'eas/build_native_ios',
|
||||
inputProviders: [
|
||||
BuildStepInput.createProvider({
|
||||
id: 'project_file',
|
||||
required: true,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
}),
|
||||
BuildStepInput.createProvider({
|
||||
id: 'scheme',
|
||||
required: true,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
}),
|
||||
BuildStepInput.createProvider({
|
||||
id: 'build_configuration',
|
||||
required: true,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
}),
|
||||
BuildStepInput.createProvider({
|
||||
id: 'xcodeproj_path',
|
||||
required: true,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
}),
|
||||
BuildStepInput.createProvider({
|
||||
id: 'targets',
|
||||
required: true,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.JSON,
|
||||
}),
|
||||
],
|
||||
outputProviders: [BuildStepOutput.createProvider({ id: 'archive_path', required: true })],
|
||||
fn: async (stepsCtx, { inputs, outputs, env }) => {
|
||||
const job = stepsCtx.global.staticContext.job as Ios.Job;
|
||||
const projectFilePath = inputs.project_file.value as string;
|
||||
const scheme = inputs.scheme.value as string;
|
||||
const buildConfiguration = inputs.build_configuration.value as string;
|
||||
const targets: XcodeTargetWithBundleIdentifier[] = z
|
||||
.array(z.object({ id: z.string(), name: z.string(), bundleIdentifier: z.string() }))
|
||||
.parse(inputs.targets.value);
|
||||
const [applicationTarget] = targets;
|
||||
|
||||
const exportOptions = job.simulator
|
||||
? undefined
|
||||
: await configureSigningAsync(stepsCtx, {
|
||||
credentialsByBundleIdentifier: job.secrets?.credentialsByBundleIdentifier ?? {},
|
||||
targets,
|
||||
xcodeprojPath: inputs.xcodeproj_path.value as string,
|
||||
buildConfiguration,
|
||||
env,
|
||||
});
|
||||
|
||||
const buildDirectory = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'native-ios-build-'));
|
||||
const derivedDataPath = path.join(buildDirectory, 'derived-data');
|
||||
const outputDirectory = path.join(buildDirectory, 'output');
|
||||
await fs.promises.writeFile(
|
||||
path.join(buildDirectory, 'Gymfile'),
|
||||
createGymfile({
|
||||
projectFilePath,
|
||||
scheme,
|
||||
buildConfiguration,
|
||||
derivedDataPath,
|
||||
outputDirectory,
|
||||
resultBundlePath: path.join(buildDirectory, 'build.xcresult'),
|
||||
logsDirectory: stepsCtx.global.buildLogsDirectory,
|
||||
exportOptions,
|
||||
})
|
||||
);
|
||||
await fs.promises.mkdir(stepsCtx.global.buildLogsDirectory, { recursive: true });
|
||||
try {
|
||||
await runFastlaneGym({
|
||||
workingDir: stepsCtx.workingDirectory,
|
||||
gymfileDirectory: buildDirectory,
|
||||
logger: stepsCtx.logger,
|
||||
buildLogsDirectory: stepsCtx.global.buildLogsDirectory,
|
||||
env,
|
||||
});
|
||||
} catch (err) {
|
||||
throw new UserError(
|
||||
'NATIVE_XCODE_BUILD_FAILED',
|
||||
`The Xcode build failed. The errors are in the "${STEP_NAME}" step. Refer to "Xcode Logs" below for additional, more detailed logs.`,
|
||||
{ cause: err }
|
||||
);
|
||||
}
|
||||
|
||||
const archivePath = job.simulator
|
||||
? await findSimulatorAppAsync(derivedDataPath, applicationTarget.bundleIdentifier)
|
||||
: (await fg('*.ipa', { cwd: outputDirectory, absolute: true }))[0];
|
||||
if (!archivePath) {
|
||||
throw new UserError(
|
||||
'NATIVE_XCODE_NO_BUILD_OUTPUT',
|
||||
job.simulator
|
||||
? `The build finished, but EAS found no ".app" with the bundle identifier "${applicationTarget.bundleIdentifier}" in "${derivedDataPath}/Build/Products". Check in the Xcode logs which products the scheme "${scheme}" built.`
|
||||
: `The build finished, but EAS found no ".ipa" in "${outputDirectory}". Check the Xcode logs for an export error.`
|
||||
);
|
||||
}
|
||||
outputs.archive_path.set(archivePath);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function configureSigningAsync(
|
||||
{ logger }: BuildStepContext,
|
||||
{
|
||||
credentialsByBundleIdentifier,
|
||||
targets,
|
||||
xcodeprojPath,
|
||||
buildConfiguration,
|
||||
env,
|
||||
}: {
|
||||
credentialsByBundleIdentifier: Record<string, Ios.TargetCredentials>;
|
||||
targets: XcodeTargetWithBundleIdentifier[];
|
||||
xcodeprojPath: string;
|
||||
buildConfiguration: string;
|
||||
env: BuildStepEnv;
|
||||
}
|
||||
): Promise<ExportOptions> {
|
||||
const targetsWithoutCredentials = targets.filter(
|
||||
({ bundleIdentifier }) => !credentialsByBundleIdentifier[bundleIdentifier]
|
||||
);
|
||||
if (targetsWithoutCredentials.length > 0) {
|
||||
throw new UserError(
|
||||
'NATIVE_XCODE_MISSING_CREDENTIALS',
|
||||
`The build job has no credentials for ${targetsWithoutCredentials
|
||||
.map(({ name, bundleIdentifier }) => `"${bundleIdentifier}" (target "${name}")`)
|
||||
.join(
|
||||
', '
|
||||
)}. EAS signs the application target and every target it depends on that needs a provisioning profile, and each one needs credentials for its bundle identifier. Add each bundle identifier with a distribution certificate and a provisioning profile on the Credentials page of the project on expo.dev, then run the build again.`
|
||||
);
|
||||
}
|
||||
|
||||
const credentialsByTargetName = Object.fromEntries(
|
||||
targets.map(({ name, bundleIdentifier }) => [
|
||||
name,
|
||||
credentialsByBundleIdentifier[bundleIdentifier],
|
||||
])
|
||||
);
|
||||
const { keychainPath, distributionType, targetProvisioningProfiles } =
|
||||
await new IosCredentialsManager(credentialsByTargetName).prepare(logger);
|
||||
|
||||
const targetSignings = targets.map(target => {
|
||||
const profile = targetProvisioningProfiles[target.name];
|
||||
logger.info(
|
||||
`Assigning provisioning profile '${profile.name}' (Apple Team ID: ${profile.teamId}) to target '${target.name}'`
|
||||
);
|
||||
return {
|
||||
target,
|
||||
buildSettings: {
|
||||
PROVISIONING_PROFILE_SPECIFIER: profile.name,
|
||||
DEVELOPMENT_TEAM: profile.teamId,
|
||||
CODE_SIGN_IDENTITY:
|
||||
distributionType === DistributionType.DEVELOPMENT
|
||||
? profile.certificateCommonName
|
||||
: 'iPhone Distribution',
|
||||
CODE_SIGN_STYLE: 'Manual',
|
||||
},
|
||||
};
|
||||
});
|
||||
await writeSigningBuildSettingsAsync({ xcodeprojPath, buildConfiguration, targetSignings });
|
||||
const effectiveBuildSettingsByTargetName = await readBuildSettingsByTargetNameAsync({
|
||||
xcodeprojPath,
|
||||
targetNames: targets.map(({ name }) => name),
|
||||
buildConfiguration,
|
||||
env,
|
||||
logger,
|
||||
});
|
||||
assertSigningBuildSettingsAreEffective({
|
||||
buildConfiguration,
|
||||
targetSignings,
|
||||
effectiveBuildSettingsByTargetName,
|
||||
});
|
||||
|
||||
const [applicationTarget] = targets;
|
||||
const iCloudContainerEnvironment = await readICloudContainerEnvironmentAsync(logger, {
|
||||
targetName: applicationTarget.name,
|
||||
buildSettings: effectiveBuildSettingsByTargetName[applicationTarget.name],
|
||||
});
|
||||
|
||||
return {
|
||||
keychainPath,
|
||||
distributionType,
|
||||
provisioningProfileUuidByBundleIdentifier: Object.fromEntries(
|
||||
targets.map(({ name, bundleIdentifier }) => [
|
||||
bundleIdentifier,
|
||||
targetProvisioningProfiles[name].uuid,
|
||||
])
|
||||
),
|
||||
iCloudContainerEnvironment,
|
||||
};
|
||||
}
|
||||
|
||||
async function readICloudContainerEnvironmentAsync(
|
||||
logger: BuildStepContext['logger'],
|
||||
{ targetName, buildSettings }: { targetName: string; buildSettings: Record<string, string> }
|
||||
): Promise<string | undefined> {
|
||||
if (!buildSettings.CODE_SIGN_ENTITLEMENTS) {
|
||||
return undefined;
|
||||
}
|
||||
const entitlementsPath = path.resolve(
|
||||
buildSettings.SRCROOT,
|
||||
buildSettings.CODE_SIGN_ENTITLEMENTS
|
||||
);
|
||||
let environment: unknown;
|
||||
try {
|
||||
const entitlements = parseInfoPlistBuffer(await fs.promises.readFile(entitlementsPath));
|
||||
environment = entitlements['com.apple.developer.icloud-container-environment'];
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
{ err },
|
||||
`EAS could not read the entitlements file "${entitlementsPath}" of the target "${targetName}", so the export does not set an iCloud container environment. If the app uses CloudKit, check that CODE_SIGN_ENTITLEMENTS points to a property list file in the repository.`
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
if (typeof environment !== 'string' || environment === '') {
|
||||
return undefined;
|
||||
}
|
||||
logger.info(
|
||||
`Exporting with the iCloud container environment "${environment}" from "${path.basename(entitlementsPath)}".`
|
||||
);
|
||||
return environment;
|
||||
}
|
||||
|
||||
function createGymfile({
|
||||
projectFilePath,
|
||||
scheme,
|
||||
buildConfiguration,
|
||||
derivedDataPath,
|
||||
outputDirectory,
|
||||
resultBundlePath,
|
||||
logsDirectory,
|
||||
exportOptions,
|
||||
}: {
|
||||
projectFilePath: string;
|
||||
scheme: string;
|
||||
buildConfiguration: string;
|
||||
derivedDataPath: string;
|
||||
outputDirectory: string;
|
||||
resultBundlePath: string;
|
||||
logsDirectory: string;
|
||||
exportOptions?: ExportOptions;
|
||||
}): string {
|
||||
const sharedVars = {
|
||||
SCHEME: scheme,
|
||||
SCHEME_BUILD_CONFIGURATION: buildConfiguration,
|
||||
DERIVED_DATA_PATH: derivedDataPath,
|
||||
RESULT_BUNDLE_PATH: resultBundlePath,
|
||||
CLEAN: 'false',
|
||||
LOGS_DIRECTORY: logsDirectory,
|
||||
};
|
||||
return [
|
||||
`${isWorkspace(projectFilePath) ? 'workspace' : 'project'}(${JSON.stringify(projectFilePath)})`,
|
||||
// xcodebuild refuses Swift package plugins and macros until someone approves them in the Xcode UI.
|
||||
'xcargs("-skipPackagePluginValidation -skipMacroValidation")',
|
||||
exportOptions
|
||||
? templateString({
|
||||
input: GymfileArchiveTemplate,
|
||||
vars: {
|
||||
...sharedVars,
|
||||
OUTPUT_DIRECTORY: outputDirectory,
|
||||
KEYCHAIN_PATH: exportOptions.keychainPath,
|
||||
EXPORT_METHOD: exportOptions.distributionType,
|
||||
PROFILES: Object.entries(exportOptions.provisioningProfileUuidByBundleIdentifier).map(
|
||||
([bundleIdentifier, uuid]) => ({ BUNDLE_ID: bundleIdentifier, UUID: uuid })
|
||||
),
|
||||
ICLOUD_CONTAINER_ENVIRONMENT: exportOptions.iCloudContainerEnvironment,
|
||||
},
|
||||
mustache: false,
|
||||
})
|
||||
: templateString({
|
||||
input: GymfileSimulatorTemplate,
|
||||
vars: {
|
||||
...sharedVars,
|
||||
SCHEME_SIMULATOR_DESTINATION: 'generic/platform=iOS Simulator',
|
||||
},
|
||||
mustache: false,
|
||||
}),
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
async function findSimulatorAppAsync(
|
||||
derivedDataPath: string,
|
||||
bundleIdentifier: string
|
||||
): Promise<string | undefined> {
|
||||
const appPaths = await fg('Build/Products/*-iphonesimulator/*.app', {
|
||||
cwd: derivedDataPath,
|
||||
onlyDirectories: true,
|
||||
absolute: true,
|
||||
});
|
||||
for (const appPath of appPaths) {
|
||||
const infoPlist = parseInfoPlistBuffer(
|
||||
await fs.promises.readFile(path.join(appPath, 'Info.plist'))
|
||||
);
|
||||
if (infoPlist.CFBundleIdentifier === bundleIdentifier) {
|
||||
return appPath;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -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);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { Ios, UserError } from '@expo/eas-build-job';
|
||||
import { BuildFunction, BuildStepInput, BuildStepInputValueTypeName } from '@expo/steps';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { parseInfoPlistBuffer, readIpaInfoAsync } from '../../readIpaInfo';
|
||||
|
||||
export function createVerifyNativeIosBuildFunction(): BuildFunction {
|
||||
return new BuildFunction({
|
||||
namespace: 'eas',
|
||||
id: 'verify_native_ios',
|
||||
name: 'Verify the build artifact',
|
||||
__metricsId: 'eas/verify_native_ios',
|
||||
inputProviders: [
|
||||
BuildStepInput.createProvider({
|
||||
id: 'archive_path',
|
||||
required: true,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
}),
|
||||
BuildStepInput.createProvider({
|
||||
id: 'expected_identifier',
|
||||
required: false,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
}),
|
||||
],
|
||||
fn: async (stepsCtx, { inputs }) => {
|
||||
const job = stepsCtx.global.staticContext.job as Ios.Job;
|
||||
const archivePath = inputs.archive_path.value as string;
|
||||
const expectedIdentifier = inputs.expected_identifier.value as string | undefined;
|
||||
const expectedPlatformName = job.simulator ? 'iphonesimulator' : 'iphoneos';
|
||||
|
||||
const { bundleIdentifier, platformName } = await readArtifactInfoAsync(archivePath);
|
||||
if (platformName !== expectedPlatformName) {
|
||||
throw new UserError(
|
||||
'NATIVE_XCODE_ARTIFACT_PLATFORM_MISMATCH',
|
||||
`The build artifact "${path.basename(archivePath)}" was built for "${platformName}", but this build is for ${
|
||||
job.simulator ? 'the iOS simulator' : 'iOS devices'
|
||||
} and needs "${expectedPlatformName}". Check that the scheme builds an iOS app.`
|
||||
);
|
||||
}
|
||||
if (expectedIdentifier && bundleIdentifier !== expectedIdentifier) {
|
||||
throw new UserError(
|
||||
'NATIVE_XCODE_ARTIFACT_IDENTIFIER_MISMATCH',
|
||||
`The build artifact "${path.basename(archivePath)}" has the bundle identifier "${bundleIdentifier}", but "app_identifier" is "${expectedIdentifier}". Set "app_identifier" to "${bundleIdentifier}", or set "xcode_scheme" and "xcode_configuration" to the ones that build "${expectedIdentifier}".`
|
||||
);
|
||||
}
|
||||
stepsCtx.logger.info(
|
||||
`Verified "${path.basename(archivePath)}": ${bundleIdentifier}, built for ${platformName}.`
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function readArtifactInfoAsync(
|
||||
archivePath: string
|
||||
): Promise<{ bundleIdentifier: unknown; platformName: unknown }> {
|
||||
if ((await fs.promises.stat(archivePath)).isDirectory()) {
|
||||
const infoPlist = parseInfoPlistBuffer(
|
||||
await fs.promises.readFile(path.join(archivePath, 'Info.plist'))
|
||||
);
|
||||
return {
|
||||
bundleIdentifier: infoPlist.CFBundleIdentifier,
|
||||
platformName: infoPlist.DTPlatformName,
|
||||
};
|
||||
}
|
||||
const { bundleIdentifier, dtPlatformName } = await readIpaInfoAsync(archivePath);
|
||||
return { bundleIdentifier, platformName: dtPlatformName };
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
BuildStepInputValueTypeName,
|
||||
BuildStepOutput,
|
||||
} from '@expo/steps';
|
||||
import path from 'path';
|
||||
|
||||
import { runFastlaneGym } from '../utils/ios/fastlane';
|
||||
import { BuildStatusText, BuildStepOutputName } from '../utils/slackMessageDynamicFields';
|
||||
@@ -39,6 +40,7 @@ export function runFastlaneFunction(): BuildFunction {
|
||||
try {
|
||||
await runFastlaneGym({
|
||||
workingDir: stepCtx.workingDirectory,
|
||||
gymfileDirectory: path.join(stepCtx.workingDirectory, 'ios'),
|
||||
env,
|
||||
logger: stepCtx.logger,
|
||||
buildLogsDirectory: stepCtx.global.buildLogsDirectory,
|
||||
|
||||
@@ -5,20 +5,14 @@ import timers from 'node:timers/promises';
|
||||
|
||||
import { CustomBuildContext } from '../../../customBuildContext';
|
||||
import { Sentry } from '../../../sentry';
|
||||
import {
|
||||
DeviceRunSessionArtifactRejectedError,
|
||||
uploadDeviceRunSessionArtifactAsync,
|
||||
} from '../deviceRunSessionArtifacts';
|
||||
import { uploadDeviceRunSessionArtifactAsync } from '../deviceRunSessionArtifacts';
|
||||
import {
|
||||
listAgentDeviceArtifactsAsync,
|
||||
pollAgentDeviceArtifactsForUploadAsync,
|
||||
uploadAgentDeviceArtifactAsync,
|
||||
} from '../agentDeviceArtifacts';
|
||||
|
||||
jest.mock('../deviceRunSessionArtifacts', () => ({
|
||||
...jest.requireActual('../deviceRunSessionArtifacts'),
|
||||
uploadDeviceRunSessionArtifactAsync: jest.fn(),
|
||||
}));
|
||||
jest.mock('../deviceRunSessionArtifacts');
|
||||
jest.mock('../../../sentry');
|
||||
jest.mock('node-fetch');
|
||||
|
||||
@@ -38,16 +32,6 @@ async function flushPromisesAsync(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForUploadCallsAsync(count: number): Promise<void> {
|
||||
for (
|
||||
let i = 0;
|
||||
i < 100 && jest.mocked(uploadDeviceRunSessionArtifactAsync).mock.calls.length < count;
|
||||
i++
|
||||
) {
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
}
|
||||
}
|
||||
|
||||
function createLoggerMock(): bunyan {
|
||||
return {
|
||||
info: jest.fn(),
|
||||
@@ -179,7 +163,6 @@ describe(uploadAgentDeviceArtifactAsync, () => {
|
||||
deviceRunSessionId: 'drs-id',
|
||||
daemonUrl: 'http://127.0.0.1:1234',
|
||||
daemonToken: 'daemon-token',
|
||||
request: { idempotencyKey: 'idempotency-key' },
|
||||
logger,
|
||||
artifact: {
|
||||
id: 'artifact-id',
|
||||
@@ -199,7 +182,6 @@ describe(uploadAgentDeviceArtifactAsync, () => {
|
||||
kind: 'agent-device-test-report',
|
||||
size: data.length,
|
||||
openStream: expect.any(Function),
|
||||
idempotencyKey: 'idempotency-key',
|
||||
});
|
||||
});
|
||||
|
||||
@@ -219,7 +201,6 @@ describe(uploadAgentDeviceArtifactAsync, () => {
|
||||
deviceRunSessionId: 'drs-id',
|
||||
daemonUrl: 'http://127.0.0.1:1234',
|
||||
daemonToken: 'daemon-token',
|
||||
request: { idempotencyKey: 'idempotency-key' },
|
||||
logger,
|
||||
artifact: {
|
||||
id: 'artifact-id',
|
||||
@@ -255,7 +236,6 @@ describe(uploadAgentDeviceArtifactAsync, () => {
|
||||
deviceRunSessionId: 'drs-id',
|
||||
daemonUrl: 'http://127.0.0.1:1234',
|
||||
daemonToken: 'daemon-token',
|
||||
request: { idempotencyKey: 'idempotency-key' },
|
||||
logger,
|
||||
artifact: {
|
||||
id: 'artifact-id',
|
||||
@@ -296,7 +276,6 @@ describe(uploadAgentDeviceArtifactAsync, () => {
|
||||
deviceRunSessionId: 'drs-id',
|
||||
daemonUrl: 'http://127.0.0.1:1234',
|
||||
daemonToken: 'daemon-token',
|
||||
request: { idempotencyKey: 'idempotency-key' },
|
||||
logger,
|
||||
artifact: { id: 'artifact-id', artifactType: 'screenshot', filename: 'shot.png' },
|
||||
});
|
||||
@@ -326,7 +305,6 @@ describe(uploadAgentDeviceArtifactAsync, () => {
|
||||
deviceRunSessionId: 'drs-id',
|
||||
daemonUrl: 'http://127.0.0.1:1234',
|
||||
daemonToken: 'daemon-token',
|
||||
request: { idempotencyKey: 'idempotency-key' },
|
||||
logger: createLoggerMock(),
|
||||
artifact: { id: 'artifact-id', artifactType: 'screen-recording', filename: 'session.mp4' },
|
||||
});
|
||||
@@ -649,7 +627,7 @@ describe(pollAgentDeviceArtifactsForUploadAsync, () => {
|
||||
expect(Sentry.capture).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('retries an artifact with its first idempotency key and gives each artifact its own key', async () => {
|
||||
it('retries an artifact after a failed upload', async () => {
|
||||
const data = Buffer.from('artifact-data');
|
||||
const logger = createLoggerMock();
|
||||
const ctx = {} as unknown as CustomBuildContext;
|
||||
@@ -657,24 +635,18 @@ describe(pollAgentDeviceArtifactsForUploadAsync, () => {
|
||||
id: 'artifact-id',
|
||||
filename: 'report.json',
|
||||
};
|
||||
const otherArtifact = {
|
||||
id: 'other-artifact-id',
|
||||
filename: 'other.json',
|
||||
};
|
||||
const listResponse = () =>
|
||||
new Response(JSON.stringify({ artifacts: [artifact, otherArtifact] }));
|
||||
const listResponse = () => new Response(JSON.stringify({ artifacts: [artifact] }));
|
||||
|
||||
jest
|
||||
.mocked(fetch)
|
||||
.mockResolvedValueOnce(listResponse())
|
||||
.mockResolvedValueOnce(new Response(Readable.from([data])))
|
||||
.mockResolvedValueOnce(new Response(Readable.from([data])))
|
||||
.mockResolvedValueOnce(listResponse())
|
||||
.mockResolvedValueOnce(new Response(Readable.from([data])));
|
||||
jest
|
||||
.mocked(uploadDeviceRunSessionArtifactAsync)
|
||||
.mockRejectedValueOnce(new Error('upload failed'))
|
||||
.mockImplementation(async (_ctx, { openStream }) => {
|
||||
.mockImplementationOnce(async (_ctx, { openStream }) => {
|
||||
await readStreamAsync(openStream());
|
||||
});
|
||||
|
||||
@@ -686,98 +658,12 @@ describe(pollAgentDeviceArtifactsForUploadAsync, () => {
|
||||
});
|
||||
|
||||
await flushPromisesAsync();
|
||||
expect(jest.mocked(uploadDeviceRunSessionArtifactAsync)).toHaveBeenCalledTimes(2);
|
||||
|
||||
await jest.advanceTimersByTimeAsync(5_000);
|
||||
await flushPromisesAsync();
|
||||
|
||||
const calls = jest
|
||||
.mocked(uploadDeviceRunSessionArtifactAsync)
|
||||
.mock.calls.map(([, { artifactId, idempotencyKey }]) => ({ artifactId, idempotencyKey }));
|
||||
expect(calls.map(call => call.artifactId)).toEqual([
|
||||
'artifact-id',
|
||||
'other-artifact-id',
|
||||
'artifact-id',
|
||||
]);
|
||||
expect(calls[0].idempotencyKey).toEqual(expect.any(String));
|
||||
expect(calls[2].idempotencyKey).toBe(calls[0].idempotencyKey);
|
||||
expect(calls[1].idempotencyKey).not.toBe(calls[0].idempotencyKey);
|
||||
});
|
||||
|
||||
it('does not retry an artifact that EAS rejects', async () => {
|
||||
const data = Buffer.from('artifact-data');
|
||||
const logger = createLoggerMock();
|
||||
const ctx = {} as unknown as CustomBuildContext;
|
||||
const listResponse = () =>
|
||||
new Response(JSON.stringify({ artifacts: [{ id: 'artifact-id', filename: 'report.json' }] }));
|
||||
|
||||
jest
|
||||
.mocked(fetch)
|
||||
.mockResolvedValueOnce(listResponse())
|
||||
.mockResolvedValueOnce(new Response(Readable.from([data])))
|
||||
.mockResolvedValueOnce(listResponse());
|
||||
jest
|
||||
.mocked(uploadDeviceRunSessionArtifactAsync)
|
||||
.mockRejectedValueOnce(new DeviceRunSessionArtifactRejectedError('Rejected.'));
|
||||
|
||||
void pollAgentDeviceArtifactsForUploadAsync(ctx, {
|
||||
deviceRunSessionId: 'drs-id',
|
||||
daemonUrl: 'http://127.0.0.1:1234',
|
||||
daemonToken: 'daemon-token',
|
||||
logger,
|
||||
});
|
||||
|
||||
await flushPromisesAsync();
|
||||
await jest.advanceTimersByTimeAsync(5_000);
|
||||
await flushPromisesAsync();
|
||||
|
||||
expect(jest.mocked(fetch)).toHaveBeenCalledTimes(3);
|
||||
expect(jest.mocked(uploadDeviceRunSessionArtifactAsync)).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('sends the first metadata again when it retries an artifact', async () => {
|
||||
const png = Buffer.from(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aF9sAAAAASUVORK5CYII=',
|
||||
'base64'
|
||||
);
|
||||
const logger = createLoggerMock();
|
||||
const ctx = {} as unknown as CustomBuildContext;
|
||||
const listResponse = () =>
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
artifacts: [{ id: 'artifact-id', artifactType: 'screenshot', filename: 'shot.png' }],
|
||||
})
|
||||
);
|
||||
|
||||
jest
|
||||
.mocked(fetch)
|
||||
.mockResolvedValueOnce(listResponse())
|
||||
.mockResolvedValueOnce(new Response(Readable.from([Buffer.from('not-an-image')])))
|
||||
.mockResolvedValueOnce(listResponse())
|
||||
.mockResolvedValueOnce(new Response(Readable.from([png])));
|
||||
jest
|
||||
.mocked(uploadDeviceRunSessionArtifactAsync)
|
||||
.mockRejectedValueOnce(new Error('upload failed'))
|
||||
.mockImplementation(async (_ctx, { openStream }) => {
|
||||
await readStreamAsync(openStream());
|
||||
});
|
||||
|
||||
void pollAgentDeviceArtifactsForUploadAsync(ctx, {
|
||||
deviceRunSessionId: 'drs-id',
|
||||
daemonUrl: 'http://127.0.0.1:1234',
|
||||
daemonToken: 'daemon-token',
|
||||
logger,
|
||||
});
|
||||
|
||||
await waitForUploadCallsAsync(1);
|
||||
await jest.advanceTimersByTimeAsync(5_000);
|
||||
await waitForUploadCallsAsync(2);
|
||||
await flushPromisesAsync();
|
||||
|
||||
expect(
|
||||
jest
|
||||
.mocked(uploadDeviceRunSessionArtifactAsync)
|
||||
.mock.calls.map(([, { metadata }]) => metadata)
|
||||
).toEqual([{ source: 'agent-device' }, { source: 'agent-device' }]);
|
||||
expect(jest.mocked(uploadDeviceRunSessionArtifactAsync)).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('stops polling when the daemon does not expose artifact inventory', async () => {
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
import { SystemError } from '@expo/eas-build-job';
|
||||
import fetch from 'node-fetch';
|
||||
import { Readable } from 'node:stream';
|
||||
|
||||
import { CustomBuildContext } from '../../../customBuildContext';
|
||||
import { turtleFetch } from '../../../utils/turtleFetch';
|
||||
import {
|
||||
DeviceRunSessionArtifactRejectedError,
|
||||
uploadDeviceRunSessionArtifactAsync,
|
||||
} from '../deviceRunSessionArtifacts';
|
||||
import { uploadDeviceRunSessionArtifactAsync } from '../deviceRunSessionArtifacts';
|
||||
import { DEVICE_RUN_SESSION_TOKEN_HEADER } from '../deviceRunSessionWorkerApi';
|
||||
|
||||
jest.mock('node-fetch');
|
||||
@@ -17,26 +13,13 @@ const { Response } = jest.requireActual('node-fetch') as typeof import('node-fet
|
||||
|
||||
const TOKEN = 'device-run-session-token-value';
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): InstanceType<typeof Response> {
|
||||
function jsonResponse(body: unknown): InstanceType<typeof Response> {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
|
||||
const uploadSessionResponse = () =>
|
||||
jsonResponse({ data: { uploadSession: { url: 'https://uploads.expo.test/a', headers: {} } } });
|
||||
|
||||
const artifact = {
|
||||
deviceRunSessionId: 'drs-id',
|
||||
artifactId: 'artifact-id',
|
||||
name: 'Screenshot',
|
||||
filename: 'screenshot.png',
|
||||
kind: 'screenshot',
|
||||
size: 0,
|
||||
openStream: () => Readable.from([]),
|
||||
};
|
||||
|
||||
function createCtx(): CustomBuildContext {
|
||||
return {
|
||||
env: { EAS_DEVICE_RUN_SESSION_TOKEN: TOKEN },
|
||||
@@ -77,17 +60,13 @@ describe(uploadDeviceRunSessionArtifactAsync, () => {
|
||||
metadata: { firstFrameRecordAt: 'test-time' },
|
||||
size: reportedSize,
|
||||
openStream: () => stream,
|
||||
idempotencyKey: 'idempotency-key',
|
||||
});
|
||||
|
||||
expect(jest.mocked(turtleFetch)).toHaveBeenCalledWith(
|
||||
'https://api.expo.test/v2/device-run-session-worker/artifact-upload-sessions',
|
||||
'POST',
|
||||
expect.objectContaining({
|
||||
headers: {
|
||||
[DEVICE_RUN_SESSION_TOKEN_HEADER]: TOKEN,
|
||||
'Idempotency-Key': 'idempotency-key',
|
||||
},
|
||||
headers: { [DEVICE_RUN_SESSION_TOKEN_HEADER]: TOKEN },
|
||||
json: {
|
||||
name: 'Artifact report.json (artifact-id)',
|
||||
filename: 'report.json',
|
||||
@@ -137,84 +116,4 @@ describe(uploadDeviceRunSessionArtifactAsync, () => {
|
||||
expect(allocationSignal).toBeInstanceOf(AbortSignal);
|
||||
expect(allocationSignal?.aborted).toBe(true);
|
||||
});
|
||||
|
||||
it('sends a new idempotency key for each upload without one', async () => {
|
||||
jest
|
||||
.mocked(turtleFetch)
|
||||
.mockResolvedValueOnce(uploadSessionResponse())
|
||||
.mockResolvedValueOnce(uploadSessionResponse());
|
||||
jest.mocked(fetch).mockResolvedValue(new Response('', { status: 200 }));
|
||||
|
||||
await uploadDeviceRunSessionArtifactAsync(createCtx(), artifact);
|
||||
await uploadDeviceRunSessionArtifactAsync(createCtx(), artifact);
|
||||
|
||||
const [first, second] = jest
|
||||
.mocked(turtleFetch)
|
||||
.mock.calls.map(
|
||||
([, , options]) => (options.headers as Record<string, string>)['Idempotency-Key']
|
||||
);
|
||||
expect(first).toEqual(expect.any(String));
|
||||
expect(second).toEqual(expect.any(String));
|
||||
expect(second).not.toBe(first);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
status: 409,
|
||||
code: 'ARTIFACT_NAME_CONFLICT',
|
||||
message:
|
||||
'Device run session already has an artifact named "Screenshot". Use a different name for this artifact.',
|
||||
},
|
||||
{
|
||||
status: 400,
|
||||
code: 'VALIDATION_ERROR',
|
||||
message: 'Device run session backing job run has finished.',
|
||||
},
|
||||
{
|
||||
status: 403,
|
||||
code: 'UNAUTHORIZED',
|
||||
message:
|
||||
'You are not authorized to create artifact upload sessions for this device run session.',
|
||||
},
|
||||
{ status: 409, code: 'OTHER_CONFLICT', message: 'Failed.' },
|
||||
])(
|
||||
'reports HTTP $status $code as a rejected upload session',
|
||||
async ({ status, code, message }) => {
|
||||
jest
|
||||
.mocked(turtleFetch)
|
||||
.mockResolvedValueOnce(jsonResponse({ errors: [{ code, message }] }, status));
|
||||
|
||||
await expect(
|
||||
uploadDeviceRunSessionArtifactAsync(createCtx(), artifact)
|
||||
).rejects.toBeInstanceOf(DeviceRunSessionArtifactRejectedError);
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
|
||||
it.each([
|
||||
{
|
||||
description: 'HTTP 429',
|
||||
respond: async () => jsonResponse({ errors: [{ message: 'Too many requests.' }] }, 429),
|
||||
},
|
||||
{
|
||||
description: 'HTTP 500',
|
||||
respond: async () =>
|
||||
jsonResponse({ errors: [{ code: 'UNEXPECTED_ERROR', message: 'Failed.' }] }, 500),
|
||||
},
|
||||
{
|
||||
description: 'no response',
|
||||
respond: async () => {
|
||||
throw new Error('socket hang up');
|
||||
},
|
||||
},
|
||||
])('does not report $description as a rejected upload session', async ({ respond }) => {
|
||||
jest.mocked(turtleFetch).mockImplementationOnce(respond);
|
||||
|
||||
const error = await uploadDeviceRunSessionArtifactAsync(createCtx(), artifact).catch(
|
||||
(err: unknown) => err
|
||||
);
|
||||
|
||||
expect(error).toBeInstanceOf(SystemError);
|
||||
expect(error).not.toBeInstanceOf(DeviceRunSessionArtifactRejectedError);
|
||||
});
|
||||
});
|
||||
@@ -7,21 +7,14 @@ import path from 'node:path';
|
||||
|
||||
import type { CustomBuildContext } from '../../../customBuildContext';
|
||||
import { Sentry } from '../../../sentry';
|
||||
import {
|
||||
type ArtifactUploadRequest,
|
||||
DeviceRunSessionArtifactRejectedError,
|
||||
uploadDeviceRunSessionArtifactAsync,
|
||||
} from '../deviceRunSessionArtifacts';
|
||||
import { uploadDeviceRunSessionArtifactAsync } from '../deviceRunSessionArtifacts';
|
||||
import { createScreenshotMetadataAsync } from '../deviceRunSessionScreenshotMetadata';
|
||||
import {
|
||||
startDeviceRunSessionScreenshotsAsync,
|
||||
uploadDeviceRunSessionScreenshotsAsync,
|
||||
} from '../deviceRunSessionScreenshots';
|
||||
|
||||
jest.mock('../deviceRunSessionArtifacts', () => ({
|
||||
...jest.requireActual('../deviceRunSessionArtifacts'),
|
||||
uploadDeviceRunSessionArtifactAsync: jest.fn(),
|
||||
}));
|
||||
jest.mock('../deviceRunSessionArtifacts');
|
||||
jest.mock('../deviceRunSessionScreenshotMetadata');
|
||||
jest.mock('../../../sentry');
|
||||
const ctx = {} as CustomBuildContext;
|
||||
@@ -29,10 +22,7 @@ const logger = { info: jest.fn(), warn: jest.fn() } as unknown as bunyan;
|
||||
const options = { deviceRunSessionId: 'session-id', logger };
|
||||
let directory: string;
|
||||
let uploaded: Buffer[];
|
||||
let failedUploads: Map<
|
||||
string,
|
||||
{ attempts: number; lastError: Error; request: ArtifactUploadRequest }
|
||||
>;
|
||||
let failedUploads: Map<string, { attempts: number; lastError: Error }>;
|
||||
|
||||
beforeEach(async () => {
|
||||
jest.clearAllMocks();
|
||||
@@ -101,11 +91,7 @@ it('uploads captures that never failed first, oldest first, before retrying fail
|
||||
for (const name of [newer, failed, older]) {
|
||||
await writeFile(path.join(directory, name), name);
|
||||
}
|
||||
failedUploads.set(failed, {
|
||||
attempts: 1,
|
||||
lastError: new Error('stalled'),
|
||||
request: { idempotencyKey: 'failed-key' },
|
||||
});
|
||||
failedUploads.set(failed, { attempts: 1, lastError: new Error('stalled') });
|
||||
await flush();
|
||||
expect(
|
||||
jest
|
||||
@@ -138,57 +124,6 @@ it('keeps failed uploads and retries the same artifact ID, logging the failed at
|
||||
expect(Sentry.capture).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('retries a screenshot with its first idempotency key and gives each screenshot its own key', async () => {
|
||||
const first = 'screenshot-2026-09-24T08-45-00-000Z-aaaaaaaaaaaa.png';
|
||||
const second = 'screenshot-2026-09-24T08-45-30-000Z-bbbbbbbbbbbb.png';
|
||||
await writeFile(path.join(directory, first), 'png');
|
||||
await writeFile(path.join(directory, second), 'png');
|
||||
jest.mocked(uploadDeviceRunSessionArtifactAsync).mockRejectedValueOnce(new Error('offline'));
|
||||
await flush();
|
||||
await flush();
|
||||
const calls = jest
|
||||
.mocked(uploadDeviceRunSessionArtifactAsync)
|
||||
.mock.calls.map(([, { artifactId, idempotencyKey }]) => ({ artifactId, idempotencyKey }));
|
||||
expect(calls.map(call => call.artifactId)).toEqual(
|
||||
[first, second, first].map(name => name.slice(0, -4))
|
||||
);
|
||||
expect(calls[0].idempotencyKey).toEqual(expect.any(String));
|
||||
expect(calls[2].idempotencyKey).toBe(calls[0].idempotencyKey);
|
||||
expect(calls[1].idempotencyKey).not.toBe(calls[0].idempotencyKey);
|
||||
});
|
||||
|
||||
it('keeps a screenshot that EAS rejects without retrying it', async () => {
|
||||
const filename = 'screenshot-2026-09-24T08-45-59-123Z-ffffffffffff.png';
|
||||
await writeFile(path.join(directory, filename), 'png');
|
||||
jest
|
||||
.mocked(uploadDeviceRunSessionArtifactAsync)
|
||||
.mockRejectedValueOnce(new DeviceRunSessionArtifactRejectedError('Rejected.'));
|
||||
await flush();
|
||||
await flush();
|
||||
expect(uploadDeviceRunSessionArtifactAsync).toHaveBeenCalledTimes(1);
|
||||
expect(await readdir(directory)).toEqual([filename]);
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ attempt: 1 }),
|
||||
'EAS rejected the preview screenshot upload. Not retrying it.'
|
||||
);
|
||||
});
|
||||
|
||||
it('sends the first metadata again when it retries a screenshot', async () => {
|
||||
const filename = 'screenshot-2026-09-24T08-45-59-123Z-ffffffffffff.png';
|
||||
await writeFile(path.join(directory, filename), 'png');
|
||||
jest.mocked(createScreenshotMetadataAsync).mockResolvedValueOnce({ source: 'manual' });
|
||||
jest.mocked(uploadDeviceRunSessionArtifactAsync).mockRejectedValueOnce(new Error('offline'));
|
||||
await flush();
|
||||
await flush();
|
||||
expect(
|
||||
jest.mocked(uploadDeviceRunSessionArtifactAsync).mock.calls.map(([, { metadata }]) => metadata)
|
||||
).toEqual([
|
||||
{ __eas_type: 'screenshot', source: 'manual' },
|
||||
{ __eas_type: 'screenshot', source: 'manual' },
|
||||
]);
|
||||
expect(createScreenshotMetadataAsync).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('uploads atomic captures immediately, including a capture arriving during another upload', async () => {
|
||||
jest.useFakeTimers();
|
||||
const collector = await startDeviceRunSessionScreenshotsAsync(ctx, options);
|
||||
@@ -309,7 +244,6 @@ it('warns for the first three attempts and every tenth after, without reporting
|
||||
expect(failedUploads.get(filename)).toEqual({
|
||||
attempts: 12,
|
||||
lastError: expect.objectContaining({ message: 'offline' }),
|
||||
request: expect.objectContaining({ idempotencyKey: expect.any(String) }),
|
||||
});
|
||||
expect(Sentry.capture).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
+1
-4
@@ -210,10 +210,7 @@ it('keeps the signed upload URL out of the error when the upload connection drop
|
||||
handle = request => request.socket.destroy();
|
||||
const filename = 'screenshot-2026-09-24T08-45-59-123Z-a1b2c3d4e5f6.png';
|
||||
await writeFile(path.join(directory, filename), 'png');
|
||||
const failedUploads = new Map<
|
||||
string,
|
||||
{ attempts: number; lastError: Error; request: { idempotencyKey: string } }
|
||||
>();
|
||||
const failedUploads = new Map<string, { attempts: number; lastError: Error }>();
|
||||
const logger = { info: jest.fn(), warn: jest.fn() } as unknown as bunyan;
|
||||
await uploadDeviceRunSessionScreenshotsAsync(ctx, {
|
||||
directory,
|
||||
|
||||
@@ -136,15 +136,6 @@ describe(DeviceRunSessionWorkerApi, () => {
|
||||
data: { id: 'drs-id', status: 'stopped' },
|
||||
expected: { id: 'drs-id', status: 'stopped' },
|
||||
},
|
||||
{
|
||||
name: 'stopAsync with a reason',
|
||||
call: (api: DeviceRunSessionWorkerApi) => api.stopAsync({ reason: 'max_duration' }),
|
||||
method: 'POST',
|
||||
route: 'stop',
|
||||
json: { reason: 'max_duration' },
|
||||
data: { id: 'drs-id', status: 'stopped' },
|
||||
expected: { id: 'drs-id', status: 'stopped' },
|
||||
},
|
||||
{
|
||||
name: 'createArtifactUploadSessionAsync',
|
||||
call: (api: DeviceRunSessionWorkerApi) =>
|
||||
@@ -154,11 +145,9 @@ describe(DeviceRunSessionWorkerApi, () => {
|
||||
kind: 'screenshot',
|
||||
size: 12,
|
||||
metadata: { __eas_type: 'screenshot' },
|
||||
idempotencyKey: 'idempotency-key',
|
||||
}),
|
||||
method: 'POST',
|
||||
route: 'artifact-upload-sessions',
|
||||
headers: { 'Idempotency-Key': 'idempotency-key' },
|
||||
json: {
|
||||
name: 'Screenshot',
|
||||
filename: 'screenshot.png',
|
||||
@@ -239,7 +228,7 @@ describe(DeviceRunSessionWorkerApi, () => {
|
||||
},
|
||||
])(
|
||||
'$name calls $method /v2/device-run-session-worker/$route with the session token header',
|
||||
async ({ call, method, route, headers, json, data, expected }) => {
|
||||
async ({ call, method, route, json, data, expected }) => {
|
||||
jest.mocked(turtleFetch).mockResolvedValueOnce(jsonResponse({ data }));
|
||||
|
||||
await expect(call(createApi())).resolves.toEqual(expected);
|
||||
@@ -248,7 +237,7 @@ describe(DeviceRunSessionWorkerApi, () => {
|
||||
const [url, calledMethod, options] = jest.mocked(turtleFetch).mock.calls[0];
|
||||
expect(url).toBe(`https://api.expo.test/v2/device-run-session-worker/${route}`);
|
||||
expect(calledMethod).toBe(method);
|
||||
expect(options.headers).toEqual({ ...headers, [DEVICE_RUN_SESSION_TOKEN_HEADER]: TOKEN });
|
||||
expect(options.headers).toEqual({ [DEVICE_RUN_SESSION_TOKEN_HEADER]: TOKEN });
|
||||
expect(options.json).toEqual(json);
|
||||
expect(options).toEqual(expect.objectContaining({ retries: 0, shouldThrowOnNotOk: false }));
|
||||
}
|
||||
|
||||
-4
@@ -330,10 +330,6 @@ describe('with a device run session token', () => {
|
||||
});
|
||||
|
||||
expectWorkerApiCall('artifact-upload-sessions', 'POST', {
|
||||
headers: {
|
||||
[DEVICE_RUN_SESSION_TOKEN_HEADER]: TOKEN,
|
||||
'Idempotency-Key': expect.any(String),
|
||||
},
|
||||
json: {
|
||||
name: 'Report',
|
||||
filename: 'report.json',
|
||||
|
||||
@@ -190,14 +190,6 @@ function workerApiCallCount(route: string): number {
|
||||
.mock.calls.filter(([url]) => url === `${DEVICE_RUN_SESSION_WORKER_URL}${route}`).length;
|
||||
}
|
||||
|
||||
/** The JSON body of each stop request the worker sent. */
|
||||
function stopRequestBodies(): unknown[] {
|
||||
return jest
|
||||
.mocked(turtleFetch)
|
||||
.mock.calls.filter(([url]) => url === `${DEVICE_RUN_SESSION_WORKER_URL}stop`)
|
||||
.map(([, , options]) => (options as { json?: unknown } | undefined)?.json);
|
||||
}
|
||||
|
||||
/**
|
||||
* Serves session status polls from `results` in order, and idle stops, through the device run
|
||||
* session worker API.
|
||||
@@ -1880,7 +1872,7 @@ describe(waitForDeviceRunSessionStoppedAsync, () => {
|
||||
expect(jest.mocked(turtleFetch)).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('stops the session with max_duration when the maximum duration elapses', async () => {
|
||||
it('returns normally when the maximum duration elapses', async () => {
|
||||
const ctx = createStatusCtxMock([{ status: 'in-progress' }]);
|
||||
const logger = createLoggerMock();
|
||||
const waitPromise = waitForDeviceRunSessionStoppedAsync({
|
||||
@@ -1899,43 +1891,9 @@ describe(waitForDeviceRunSessionStoppedAsync, () => {
|
||||
expect(logger.info).toHaveBeenCalledWith(
|
||||
'Device run session drs-id reached its maximum duration.'
|
||||
);
|
||||
expect(stopRequestBodies()).toEqual([{ reason: 'max_duration' }]);
|
||||
expect(clearTimeoutCallback).toHaveBeenCalledWith(durationTimeout);
|
||||
});
|
||||
|
||||
it('stops with max_duration when the maximum duration interrupts a status poll', async () => {
|
||||
const ctx = createStatusCtxMock([{ error: new Error('The operation was aborted.') }]);
|
||||
const waitPromise = waitForDeviceRunSessionStoppedAsync({
|
||||
ctx,
|
||||
deviceRunSessionId: 'drs-id',
|
||||
logger: createLoggerMock(),
|
||||
maxDurationSeconds: 1,
|
||||
});
|
||||
|
||||
jest.mocked(setTimeoutCallback).mock.calls[0][0]();
|
||||
await waitPromise;
|
||||
|
||||
expect(stopRequestBodies()).toEqual([{ reason: 'max_duration' }]);
|
||||
});
|
||||
|
||||
it('does not stop the session when the build step is canceled', async () => {
|
||||
const ctx = createStatusCtxMock([{ status: 'in-progress' }]);
|
||||
const abortController = new AbortController();
|
||||
const waitPromise = waitForDeviceRunSessionStoppedAsync({
|
||||
ctx,
|
||||
deviceRunSessionId: 'drs-id',
|
||||
logger: createLoggerMock(),
|
||||
maxDurationSeconds: 1,
|
||||
signal: abortController.signal,
|
||||
});
|
||||
|
||||
abortController.abort();
|
||||
jest.mocked(setTimeoutCallback).mock.calls[0][0]();
|
||||
await waitPromise;
|
||||
|
||||
expect(workerApiCallCount('stop')).toBe(0);
|
||||
});
|
||||
|
||||
it('clears the duration timeout when the session stops first', async () => {
|
||||
await waitForDeviceRunSessionStoppedAsync({
|
||||
ctx: createStatusCtxMock([{ status: 'stopped' }]),
|
||||
@@ -2124,7 +2082,6 @@ describe(waitForDeviceRunSessionStoppedAsync, () => {
|
||||
// One minute at the 5-second poll interval is 12 status polls.
|
||||
expect(workerApiCallCount('session')).toBe(12);
|
||||
expect(workerApiCallCount('stop')).toBe(1);
|
||||
expect(stopRequestBodies()).toEqual([{ reason: 'idle_timeout' }]);
|
||||
expect(logger.info).toHaveBeenCalledWith(
|
||||
'Device run session drs-id had no activity for 1 minute(s) (max idle time). Stopping the session.'
|
||||
);
|
||||
@@ -2214,9 +2171,9 @@ describe(waitForDeviceRunSessionStoppedAsync, () => {
|
||||
'Could not mark device run session drs-id as stopped. The session job ends anyway.'
|
||||
);
|
||||
expect(jest.mocked(Sentry).capture).toHaveBeenCalledWith(
|
||||
'Could not mark device run session as stopped',
|
||||
'Could not mark idle device run session as stopped',
|
||||
expect.any(Error),
|
||||
{ level: 'warning', extras: { deviceRunSessionId: 'drs-id', reason: 'idle_timeout' } }
|
||||
{ level: 'warning', extras: { deviceRunSessionId: 'drs-id' } }
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -23,7 +23,7 @@ import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { inspect } from 'node:util';
|
||||
|
||||
import { SandboxArtifactUploadManager, startSandboxArtifactUploadAsync } from '../sandboxArtifacts';
|
||||
import { SandboxWorkerApi } from '../sandboxWorkerApi';
|
||||
import { type SandboxWorkerApi } from '../sandboxWorkerApi';
|
||||
import { WorkerApiError } from '../workerApi';
|
||||
|
||||
const { AbortError, FetchError, Response } = jest.requireActual(
|
||||
@@ -46,7 +46,7 @@ describe('sandbox artifact uploads', () => {
|
||||
createArtifactUploadSessionAsync: jest.Mock;
|
||||
finalizeArtifactAsync: jest.Mock;
|
||||
};
|
||||
let logger: { info: jest.Mock; warn: jest.Mock; error: jest.Mock };
|
||||
let logger: { info: jest.Mock; error: jest.Mock };
|
||||
let uploadArtifactAsync: (options: {
|
||||
filePath: string;
|
||||
name: string;
|
||||
@@ -62,7 +62,7 @@ describe('sandbox artifact uploads', () => {
|
||||
createArtifactUploadSessionAsync: jest.fn(),
|
||||
finalizeArtifactAsync: jest.fn(),
|
||||
};
|
||||
logger = { info: jest.fn(), warn: jest.fn(), error: jest.fn() };
|
||||
logger = { info: jest.fn(), error: jest.fn() };
|
||||
uploadArtifactAsync = async options =>
|
||||
await startSandboxArtifactUploadAsync({
|
||||
workerApi: workerApi as unknown as SandboxWorkerApi,
|
||||
@@ -218,28 +218,13 @@ describe('sandbox artifact uploads', () => {
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
status: 409,
|
||||
code: 'ARTIFACT_NAME_CONFLICT',
|
||||
apiMessage:
|
||||
'Sandbox already has an artifact named "Crash log". Use a different name for this artifact.',
|
||||
},
|
||||
{
|
||||
status: 400,
|
||||
code: 'VALIDATION_ERROR',
|
||||
apiMessage:
|
||||
'Sandbox is stopped, so it cannot upload artifacts. Upload artifacts while the sandbox is running.',
|
||||
},
|
||||
{
|
||||
status: 403,
|
||||
code: 'UNAUTHORIZED',
|
||||
apiMessage:
|
||||
'You are not authorized to upload artifacts for this sandbox. Only the user who created the sandbox can upload its artifacts.',
|
||||
},
|
||||
{ status: 400, code: 'VALIDATION_ERROR' },
|
||||
{ status: 403, code: 'UNAUTHORIZED' },
|
||||
])(
|
||||
'rejects a $code upload session error as a bad request with the API message',
|
||||
async ({ status, code, apiMessage }) => {
|
||||
const message = `POST /v2/sandbox-worker/artifact-upload-sessions failed with status ${status}: ${apiMessage}`;
|
||||
async ({ status, code }) => {
|
||||
const message =
|
||||
'POST /v2/sandbox-worker/artifact-upload-sessions failed with status 400: Sandbox already has an artifact named "Crash log". Use a different name for this artifact.';
|
||||
workerApi.createArtifactUploadSessionAsync.mockRejectedValueOnce(
|
||||
new WorkerApiError(message, status, undefined, code)
|
||||
);
|
||||
@@ -261,7 +246,6 @@ describe('sandbox artifact uploads', () => {
|
||||
it.each([
|
||||
{ status: 500, code: 'UNEXPECTED_ERROR' },
|
||||
{ status: 401, code: 'AUTHENTICATION_ERROR' },
|
||||
{ status: 409, code: 'OTHER_CONFLICT' },
|
||||
])('rethrows a $code upload session error unchanged', async ({ status, code }) => {
|
||||
const error = new WorkerApiError('Request failed.', status, undefined, code);
|
||||
workerApi.createArtifactUploadSessionAsync.mockRejectedValueOnce(error);
|
||||
@@ -403,117 +387,6 @@ describe('sandbox artifact uploads', () => {
|
||||
await manager.stoppedPromise;
|
||||
});
|
||||
|
||||
describe('with the sandbox worker API', () => {
|
||||
const uploadSessionsUrl = 'https://api.expo.test/v2/sandbox-worker/artifact-upload-sessions';
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
it('retries a failed upload session request with the same idempotency key', async () => {
|
||||
jest.useFakeTimers({ doNotFake: ['nextTick', 'setImmediate', 'queueMicrotask'] });
|
||||
jest
|
||||
.mocked(fetch)
|
||||
.mockResolvedValueOnce(new Response('unavailable', { status: 503 }))
|
||||
.mockResolvedValueOnce(jsonResponse({ data: createdSession }))
|
||||
.mockResolvedValueOnce(new Response('', { status: 200 }))
|
||||
.mockResolvedValueOnce(
|
||||
jsonResponse({ data: { id: ARTIFACT_ID, downloadUrl: DOWNLOAD_URL } })
|
||||
);
|
||||
|
||||
const uploadPromise = uploadWithWorkerApiAsync();
|
||||
while (uploadSessionRequests().length === 0) {
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
}
|
||||
await jest.advanceTimersByTimeAsync(1000);
|
||||
const upload = await uploadPromise;
|
||||
|
||||
await expect(upload.completed).resolves.toEqual({
|
||||
status: 'uploaded',
|
||||
downloadUrl: DOWNLOAD_URL,
|
||||
});
|
||||
const keys = uploadSessionRequests().map(
|
||||
([, init]) => (init?.headers as Record<string, string>)['Idempotency-Key']
|
||||
);
|
||||
expect(keys).toEqual([expect.any(String), keys[0]]);
|
||||
});
|
||||
|
||||
it('stops creating the upload session after 25 seconds, before the MCP relay timeout', async () => {
|
||||
jest.useFakeTimers({ doNotFake: ['nextTick', 'setImmediate', 'queueMicrotask'] });
|
||||
jest.mocked(fetch).mockImplementation(
|
||||
async (_url, init) =>
|
||||
await new Promise((_resolve, reject) => {
|
||||
const timer = setTimeout(
|
||||
() => reject(new FetchError('network timeout', 'request-timeout')),
|
||||
init?.timeout
|
||||
);
|
||||
init?.signal?.addEventListener('abort', () => {
|
||||
clearTimeout(timer);
|
||||
reject(new AbortError('The user aborted a request.'));
|
||||
});
|
||||
})
|
||||
);
|
||||
const manager = new SandboxArtifactUploadManager({
|
||||
workerApi: new SandboxWorkerApi('https://api.expo.test/v2/', 'sandbox-worker-token'),
|
||||
logger: logger as unknown as bunyan,
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
|
||||
const assertion = expect(
|
||||
manager.startAsync({ filePath, name: 'Crash log', yieldTimeMs: 30_000 })
|
||||
).rejects.toThrow(
|
||||
'Could not create an upload session for sandbox artifact "Crash log" within 25 seconds.'
|
||||
);
|
||||
while (uploadSessionRequests().length === 0) {
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
}
|
||||
await jest.advanceTimersByTimeAsync(25_000);
|
||||
await assertion;
|
||||
|
||||
const keys = uploadSessionRequests().map(
|
||||
([, init]) => (init?.headers as Record<string, string>)['Idempotency-Key']
|
||||
);
|
||||
expect(keys).toEqual([expect.any(String), keys[0], keys[0]]);
|
||||
});
|
||||
|
||||
it('does not retry an artifact name conflict', async () => {
|
||||
const apiMessage =
|
||||
'Sandbox already has an artifact named "Crash log". Use a different name for this artifact.';
|
||||
jest
|
||||
.mocked(fetch)
|
||||
.mockResolvedValueOnce(
|
||||
jsonResponse({ errors: [{ code: 'ARTIFACT_NAME_CONFLICT', message: apiMessage }] }, 409)
|
||||
);
|
||||
|
||||
await expect(uploadWithWorkerApiAsync()).rejects.toMatchObject({
|
||||
code: SandboxDaemonErrorCode.BAD_REQUEST,
|
||||
message: `POST /v2/sandbox-worker/artifact-upload-sessions failed with status 409: ${apiMessage}`,
|
||||
});
|
||||
expect(fetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
async function uploadWithWorkerApiAsync(): ReturnType<typeof startSandboxArtifactUploadAsync> {
|
||||
return await startSandboxArtifactUploadAsync({
|
||||
workerApi: new SandboxWorkerApi('https://api.expo.test/v2/', 'sandbox-worker-token'),
|
||||
logger: logger as unknown as bunyan,
|
||||
filePath,
|
||||
name: 'Crash log',
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
}
|
||||
|
||||
function uploadSessionRequests(): Parameters<typeof fetch>[] {
|
||||
return jest.mocked(fetch).mock.calls.filter(([url]) => url === uploadSessionsUrl);
|
||||
}
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): InstanceType<typeof Response> {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
function createManager(signal: AbortSignal): SandboxArtifactUploadManager {
|
||||
return new SandboxArtifactUploadManager({
|
||||
workerApi: workerApi as unknown as SandboxWorkerApi,
|
||||
|
||||
@@ -85,7 +85,6 @@ describe(SandboxWorkerApi, () => {
|
||||
call: (api: SandboxWorkerApi) =>
|
||||
api.createArtifactUploadSessionAsync({ name: 'Crash log', filename: 'crash.log', size: 5 }),
|
||||
route: 'artifact-upload-sessions',
|
||||
headers: { 'Idempotency-Key': expect.any(String) },
|
||||
json: { name: 'Crash log', filename: 'crash.log', size: 5 },
|
||||
data: {
|
||||
artifact: { id: ARTIFACT_ID },
|
||||
@@ -106,7 +105,7 @@ describe(SandboxWorkerApi, () => {
|
||||
},
|
||||
])(
|
||||
'$name calls POST /v2/sandbox-worker/$route with the sandbox worker token header',
|
||||
async ({ call, route, headers, json, data, expected }) => {
|
||||
async ({ call, route, json, data, expected }) => {
|
||||
jest.mocked(turtleFetch).mockResolvedValueOnce(jsonResponse({ data }));
|
||||
|
||||
await expect(call(new SandboxWorkerApi(BASE_URL, TOKEN))).resolves.toEqual(expected);
|
||||
@@ -114,35 +113,11 @@ describe(SandboxWorkerApi, () => {
|
||||
const [url, method, options] = jest.mocked(turtleFetch).mock.calls[0];
|
||||
expect(url).toBe(`https://api.expo.test/v2/sandbox-worker/${route}`);
|
||||
expect(method).toBe('POST');
|
||||
expect(options.headers).toEqual({ ...headers, 'expo-sandbox-worker-token': TOKEN });
|
||||
expect(options.headers).toEqual({ 'expo-sandbox-worker-token': TOKEN });
|
||||
expect(options.json).toEqual(json);
|
||||
}
|
||||
);
|
||||
|
||||
it('sends a new idempotency key for each artifact upload session', async () => {
|
||||
jest.mocked(turtleFetch).mockImplementation(async () =>
|
||||
jsonResponse({
|
||||
data: {
|
||||
artifact: { id: ARTIFACT_ID },
|
||||
uploadSession: { url: 'https://uploads.expo.test/a', headers: {} },
|
||||
},
|
||||
})
|
||||
);
|
||||
const api = new SandboxWorkerApi(BASE_URL, TOKEN);
|
||||
|
||||
await api.createArtifactUploadSessionAsync({ name: 'A', filename: 'a.log', size: 1 });
|
||||
await api.createArtifactUploadSessionAsync({ name: 'B', filename: 'b.log', size: 1 });
|
||||
|
||||
const [first, second] = jest
|
||||
.mocked(turtleFetch)
|
||||
.mock.calls.map(
|
||||
([, , options]) => (options.headers as Record<string, string>)['Idempotency-Key']
|
||||
);
|
||||
expect(first).toEqual(expect.any(String));
|
||||
expect(second).toEqual(expect.any(String));
|
||||
expect(second).not.toBe(first);
|
||||
});
|
||||
|
||||
it('escapes the artifact ID in the finalize route', async () => {
|
||||
jest
|
||||
.mocked(turtleFetch)
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { ExpoError, SystemError, UserError } from '@expo/eas-build-job';
|
||||
import { once } from 'node:events';
|
||||
import {
|
||||
access,
|
||||
@@ -102,49 +101,6 @@ it.each([
|
||||
expect(attempts).toBe(1);
|
||||
});
|
||||
|
||||
// Shaped like `xcrun simctl install` output for an app whose minimum iOS version is above the Simulator runtime.
|
||||
const NEWER_IOS_REQUIRED_STDERR = [
|
||||
'An error was encountered processing the command (domain=IXUserPresentableErrorDomain):',
|
||||
'Requires a Newer Version of iOS',
|
||||
'“Example” requires a newer version of iOS.',
|
||||
].join('\n');
|
||||
|
||||
async function rejectActionAsync(action: string, stderr: string): Promise<ExpoError> {
|
||||
server.on('connection', socket => {
|
||||
socket.send(JSON.stringify({ ready: true }));
|
||||
socket.on('message', () => socket.send(JSON.stringify({ id: 1, exitCode: 1, stderr })));
|
||||
});
|
||||
const error = await runServeSimActionAsync({ ...request(), action }).catch(err => err);
|
||||
expect(error).toBeInstanceOf(ExpoError);
|
||||
return error;
|
||||
}
|
||||
|
||||
it('classifies an app install that requires a newer iOS version as a user error', async () => {
|
||||
const error = await rejectActionAsync('app.install', NEWER_IOS_REQUIRED_STDERR);
|
||||
expect(error).toBeInstanceOf(UserError);
|
||||
expect(error.toExternalExpoError()).toMatchObject({
|
||||
errorCode: 'EAS_INSTALL_APPLICATION_REQUIRES_NEWER_IOS',
|
||||
message: expect.stringContaining('Choose an iOS Simulator device whose iOS version meets'),
|
||||
});
|
||||
expect((error.cause as Error).message).toContain('Requires a Newer Version of iOS');
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
'app.install',
|
||||
'An error was encountered processing the command (domain=IXUserPresentableErrorDomain):\nThis app could not be installed at this time.',
|
||||
],
|
||||
['app.install', 'install refused'],
|
||||
['app.launch', NEWER_IOS_REQUIRED_STDERR],
|
||||
])('keeps other %s failures as server errors', async (action, stderr) => {
|
||||
const error = await rejectActionAsync(action, stderr);
|
||||
expect(error).toBeInstanceOf(SystemError);
|
||||
expect(error.toExternalExpoError()).toMatchObject({
|
||||
errorCode: 'SERVER_ERROR',
|
||||
message: `serve-sim ${action} failed: ${stderr}`,
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects a connection that closes before its action finishes', async () => {
|
||||
server.on('connection', socket => socket.close());
|
||||
await expect(runServeSimActionAsync(request())).rejects.toThrow('closed before completion');
|
||||
|
||||
@@ -192,29 +192,6 @@ describe('worker API retries', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('sends the same idempotency key on every attempt', async () => {
|
||||
jest
|
||||
.mocked(turtleFetch)
|
||||
.mockRejectedValueOnce(new Error('socket hang up'))
|
||||
.mockResolvedValueOnce(new Response('unavailable', { status: 503 }))
|
||||
.mockResolvedValueOnce(jsonResponse({ data: { id: 'thing-id' } }));
|
||||
const assertion = expect(
|
||||
new WorkerApi(BASE_URL, AUTH).requestAsync('POST', 'things', ThingSchema, {
|
||||
json: {},
|
||||
idempotencyKey: 'idempotency-key',
|
||||
retries: 3,
|
||||
})
|
||||
).resolves.toEqual({ id: 'thing-id' });
|
||||
await jest.runAllTimersAsync();
|
||||
await assertion;
|
||||
expect(jest.mocked(turtleFetch).mock.calls.map(([, , options]) => options.headers)).toEqual(
|
||||
Array.from({ length: 3 }, () => ({
|
||||
'expo-test-worker-token': 'test-worker-token-value',
|
||||
'Idempotency-Key': 'idempotency-key',
|
||||
}))
|
||||
);
|
||||
});
|
||||
|
||||
it('recovers from a network failure', async () => {
|
||||
jest
|
||||
.mocked(turtleFetch)
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { SystemError, formatBytes } from '@expo/eas-build-job';
|
||||
import { type bunyan } from '@expo/logger';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { createReadStream, createWriteStream } from 'node:fs';
|
||||
import { mkdtemp, rm, stat } from 'node:fs/promises';
|
||||
import fetch from 'node-fetch';
|
||||
@@ -12,11 +11,7 @@ import { z } from 'zod';
|
||||
|
||||
import { CustomBuildContext } from '../../customBuildContext';
|
||||
import { Sentry } from '../../sentry';
|
||||
import {
|
||||
type ArtifactUploadRequest,
|
||||
DeviceRunSessionArtifactRejectedError,
|
||||
uploadDeviceRunSessionArtifactAsync,
|
||||
} from './deviceRunSessionArtifacts';
|
||||
import { uploadDeviceRunSessionArtifactAsync } from './deviceRunSessionArtifacts';
|
||||
import { createScreenshotMetadataAsync } from './deviceRunSessionScreenshotMetadata';
|
||||
|
||||
const AGENT_DEVICE_ARTIFACT_UPLOAD_POLL_INTERVAL_MS = 5_000;
|
||||
@@ -63,8 +58,7 @@ export async function pollAgentDeviceArtifactsForUploadAsync(
|
||||
}
|
||||
): Promise<void> {
|
||||
logger.info('Started polling agent-device daemon for artifacts.');
|
||||
const finishedArtifactIds = new Set<string>();
|
||||
const uploadRequests = new Map<string, ArtifactUploadRequest>();
|
||||
const uploadedArtifactIds = new Set<string>();
|
||||
let listArtifactsErrorCount = 0;
|
||||
|
||||
// Ending normal polling must not cancel a transfer that the session already produced.
|
||||
@@ -98,31 +92,23 @@ export async function pollAgentDeviceArtifactsForUploadAsync(
|
||||
});
|
||||
listArtifactsErrorCount = 0;
|
||||
for (const artifact of artifacts) {
|
||||
if (finishedArtifactIds.has(artifact.id)) {
|
||||
if (uploadedArtifactIds.has(artifact.id)) {
|
||||
continue;
|
||||
}
|
||||
const request = uploadRequests.get(artifact.id) ?? { idempotencyKey: randomUUID() };
|
||||
uploadRequests.set(artifact.id, request);
|
||||
try {
|
||||
await uploadAgentDeviceArtifactAsync(ctx, {
|
||||
deviceRunSessionId,
|
||||
daemonUrl,
|
||||
daemonToken,
|
||||
artifact,
|
||||
request,
|
||||
logger,
|
||||
signal: transferSignal,
|
||||
...(transferSignal ? { signal: transferSignal } : {}),
|
||||
});
|
||||
finishedArtifactIds.add(artifact.id);
|
||||
uploadRequests.delete(artifact.id);
|
||||
uploadedArtifactIds.add(artifact.id);
|
||||
} catch (err) {
|
||||
if (transferSignal?.aborted) {
|
||||
return;
|
||||
}
|
||||
if (err instanceof DeviceRunSessionArtifactRejectedError) {
|
||||
finishedArtifactIds.add(artifact.id);
|
||||
uploadRequests.delete(artifact.id);
|
||||
}
|
||||
const error = err instanceof Error ? err : new Error(String(err));
|
||||
Sentry.capture('Could not upload agent-device remote session artifact', error);
|
||||
logger.warn({ err: error }, 'Could not upload agent-device remote session artifact.');
|
||||
@@ -206,7 +192,6 @@ export async function uploadAgentDeviceArtifactAsync(
|
||||
daemonUrl,
|
||||
daemonToken,
|
||||
artifact,
|
||||
request,
|
||||
logger,
|
||||
signal,
|
||||
}: {
|
||||
@@ -214,7 +199,6 @@ export async function uploadAgentDeviceArtifactAsync(
|
||||
daemonUrl: string;
|
||||
daemonToken: string;
|
||||
artifact: AgentDeviceArtifact;
|
||||
request: ArtifactUploadRequest;
|
||||
logger: bunyan;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
@@ -235,7 +219,7 @@ export async function uploadAgentDeviceArtifactAsync(
|
||||
const display = artifact.displayRotation
|
||||
? { displayRotation: artifact.displayRotation }
|
||||
: undefined;
|
||||
request.metadata ??=
|
||||
const metadata =
|
||||
artifact.artifactType === 'screenshot'
|
||||
? await createScreenshotMetadataAsync(temporaryArtifactPath, {
|
||||
source: 'agent-device',
|
||||
@@ -250,10 +234,9 @@ export async function uploadAgentDeviceArtifactAsync(
|
||||
name: `${artifact.filename} (${artifact.id})`,
|
||||
filename: artifact.filename,
|
||||
kind: artifact.artifactType ?? undefined,
|
||||
...(request.metadata ? { metadata: request.metadata } : {}),
|
||||
...(metadata ? { metadata } : {}),
|
||||
size,
|
||||
openStream: () => createReadStream(temporaryArtifactPath),
|
||||
idempotencyKey: request.idempotencyKey,
|
||||
...(signal ? { signal } : {}),
|
||||
});
|
||||
} finally {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { SystemError } from '@expo/eas-build-job';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import type { Readable } from 'node:stream';
|
||||
|
||||
import { CustomBuildContext } from '../../customBuildContext';
|
||||
@@ -11,7 +10,6 @@ import {
|
||||
} from '../../storage/uploadWithSignedUrl';
|
||||
import { withDeviceRunSessionTimeoutAsync } from './deviceRunSessionTimeout';
|
||||
import { requireDeviceRunSessionWorkerApi } from './deviceRunSessionWorkerApi';
|
||||
import { WorkerApiError } from './workerApi';
|
||||
|
||||
export type ArtifactMetadata = {
|
||||
deviceRunSessionId: string;
|
||||
@@ -23,30 +21,18 @@ export type ArtifactMetadata = {
|
||||
size: number;
|
||||
};
|
||||
|
||||
export type ArtifactUploadRequest = {
|
||||
idempotencyKey: string;
|
||||
metadata?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export async function uploadDeviceRunSessionArtifactAsync(
|
||||
ctx: CustomBuildContext,
|
||||
options: ArtifactMetadata & {
|
||||
openStream: () => Readable;
|
||||
signal?: AbortSignal;
|
||||
attempts?: number;
|
||||
idempotencyKey?: string;
|
||||
}
|
||||
): Promise<void> {
|
||||
const idempotencyKey = options.idempotencyKey ?? randomUUID();
|
||||
try {
|
||||
const uploadSession = await withDeviceRunSessionTimeoutAsync(
|
||||
{ name: 'Artifact upload session creation', timeoutMs: 15_000, signal: options.signal },
|
||||
async signal =>
|
||||
await createDeviceRunSessionArtifactUploadSessionAsync(
|
||||
ctx,
|
||||
{ ...options, idempotencyKey },
|
||||
signal
|
||||
)
|
||||
async signal => await createDeviceRunSessionArtifactUploadSessionAsync(ctx, options, signal)
|
||||
);
|
||||
options.signal?.throwIfAborted();
|
||||
await uploadWithSignedUrl(
|
||||
@@ -61,8 +47,6 @@ export async function uploadDeviceRunSessionArtifactAsync(
|
||||
}
|
||||
}
|
||||
|
||||
export class DeviceRunSessionArtifactRejectedError extends SystemError {}
|
||||
|
||||
class DeviceRunSessionArtifactUploadError extends SystemError {
|
||||
constructor(artifactId: string, reason: string) {
|
||||
super(`Failed to upload device run session artifact ${artifactId}: ${reason}.`);
|
||||
@@ -71,16 +55,7 @@ class DeviceRunSessionArtifactUploadError extends SystemError {
|
||||
|
||||
async function createDeviceRunSessionArtifactUploadSessionAsync(
|
||||
ctx: CustomBuildContext,
|
||||
{
|
||||
deviceRunSessionId,
|
||||
artifactId,
|
||||
name,
|
||||
filename,
|
||||
kind,
|
||||
metadata,
|
||||
size,
|
||||
idempotencyKey,
|
||||
}: ArtifactMetadata & { idempotencyKey: string },
|
||||
{ deviceRunSessionId, artifactId, name, filename, kind, metadata, size }: ArtifactMetadata,
|
||||
signal: AbortSignal
|
||||
): Promise<SignedUrl> {
|
||||
const workerApi = requireDeviceRunSessionWorkerApi(ctx);
|
||||
@@ -93,19 +68,17 @@ async function createDeviceRunSessionArtifactUploadSessionAsync(
|
||||
...(kind !== undefined ? { kind } : {}),
|
||||
...(metadata !== undefined ? { metadata } : {}),
|
||||
size,
|
||||
idempotencyKey,
|
||||
},
|
||||
{ signal }
|
||||
);
|
||||
} catch (err) {
|
||||
signal.throwIfAborted();
|
||||
const message = `Failed to create upload session for device run session artifact ${artifactId}: ${
|
||||
err instanceof Error ? err.message : String(err)
|
||||
}`;
|
||||
if (err instanceof WorkerApiError && !err.isTransient) {
|
||||
throw new DeviceRunSessionArtifactRejectedError(message, { cause: err });
|
||||
}
|
||||
throw new SystemError(message, { cause: err });
|
||||
throw new SystemError(
|
||||
`Failed to create upload session for device run session artifact ${artifactId}: ${
|
||||
err instanceof Error ? err.message : String(err)
|
||||
}`,
|
||||
{ cause: err }
|
||||
);
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
return uploadSession;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { formatBytes } from '@expo/eas-build-job';
|
||||
import type { bunyan } from '@expo/logger';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { type FSWatcher, createReadStream, watch } from 'node:fs';
|
||||
import { mkdtemp, readFile, readdir, rm, rmdir, stat } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
@@ -9,11 +8,7 @@ import { z } from 'zod';
|
||||
|
||||
import type { CustomBuildContext } from '../../customBuildContext';
|
||||
import { Sentry } from '../../sentry';
|
||||
import {
|
||||
type ArtifactUploadRequest,
|
||||
DeviceRunSessionArtifactRejectedError,
|
||||
uploadDeviceRunSessionArtifactAsync,
|
||||
} from './deviceRunSessionArtifacts';
|
||||
import { uploadDeviceRunSessionArtifactAsync } from './deviceRunSessionArtifacts';
|
||||
import { createScreenshotMetadataAsync } from './deviceRunSessionScreenshotMetadata';
|
||||
import {
|
||||
type ScreenshotSession,
|
||||
@@ -56,10 +51,7 @@ async function reportScreenshotFailureRecordAsync(file: string, logger: bunyan):
|
||||
await rm(file, { force: true });
|
||||
}
|
||||
|
||||
type FailedUploads = Map<
|
||||
string,
|
||||
{ attempts: number; lastError: Error; request: ArtifactUploadRequest }
|
||||
>;
|
||||
type FailedUploads = Map<string, { attempts: number; lastError: Error }>;
|
||||
|
||||
type ScreenshotEntry = { kind: 'failureRecord' } | { kind: 'screenshot'; timestamp: string };
|
||||
|
||||
@@ -82,7 +74,6 @@ async function uploadScreenshotAsync(
|
||||
session,
|
||||
signal,
|
||||
failedUploads,
|
||||
request,
|
||||
logger,
|
||||
}: {
|
||||
file: string;
|
||||
@@ -93,34 +84,31 @@ async function uploadScreenshotAsync(
|
||||
session: Promise<ScreenshotSession | null>;
|
||||
signal: AbortSignal;
|
||||
failedUploads: FailedUploads;
|
||||
request: ArtifactUploadRequest;
|
||||
logger: bunyan;
|
||||
}
|
||||
): Promise<void> {
|
||||
const artifactDetails = screenshotArtifactDetails(timestamp, await session);
|
||||
const startedAt = Date.now();
|
||||
request.metadata ??= {
|
||||
...artifactDetails.metadata,
|
||||
...(await createScreenshotMetadataAsync(file, { source: 'manual', logger })),
|
||||
};
|
||||
await uploadDeviceRunSessionArtifactAsync(ctx, {
|
||||
deviceRunSessionId,
|
||||
artifactId: name.slice(0, -4),
|
||||
name: artifactDetails.name,
|
||||
filename: artifactDetails.filename,
|
||||
metadata: request.metadata,
|
||||
metadata: {
|
||||
...artifactDetails.metadata,
|
||||
...(await createScreenshotMetadataAsync(file, { source: 'manual', logger })),
|
||||
},
|
||||
kind: 'screenshot',
|
||||
size,
|
||||
openStream: () => createReadStream(file),
|
||||
attempts: 3,
|
||||
signal,
|
||||
idempotencyKey: request.idempotencyKey,
|
||||
});
|
||||
await rm(file);
|
||||
const previousFailures = failedUploads.get(name)?.attempts ?? 0;
|
||||
failedUploads.delete(name);
|
||||
// An earlier failed attempt may have created the artifact row without uploading the file.
|
||||
// The retry reuses that row through the Idempotency-Key.
|
||||
// Each earlier failed attempt may have left an artifact row without a file on the server.
|
||||
// The API deletes such rows when the job run finishes (expo/universe#31539).
|
||||
const retryNote =
|
||||
previousFailures > 0
|
||||
? ` after ${previousFailures} failed attempt${previousFailures === 1 ? '' : 's'}`
|
||||
@@ -139,7 +127,6 @@ function recordUploadFailure(
|
||||
size,
|
||||
signal,
|
||||
failedUploads,
|
||||
request,
|
||||
logger,
|
||||
}: {
|
||||
file: string;
|
||||
@@ -147,7 +134,6 @@ function recordUploadFailure(
|
||||
size: number | undefined;
|
||||
signal: AbortSignal;
|
||||
failedUploads: FailedUploads;
|
||||
request: ArtifactUploadRequest;
|
||||
logger: bunyan;
|
||||
}
|
||||
): 'aborted' | 'recorded' {
|
||||
@@ -160,14 +146,7 @@ function recordUploadFailure(
|
||||
}
|
||||
const error = err instanceof Error ? err : new Error(String(err));
|
||||
const attempt = (failedUploads.get(name)?.attempts ?? 0) + 1;
|
||||
failedUploads.set(name, { attempts: attempt, lastError: error, request });
|
||||
if (error instanceof DeviceRunSessionArtifactRejectedError) {
|
||||
logger.warn(
|
||||
{ err: error, file, attempt, size },
|
||||
'EAS rejected the preview screenshot upload. Not retrying it.'
|
||||
);
|
||||
return 'recorded';
|
||||
}
|
||||
failedUploads.set(name, { attempts: attempt, lastError: error });
|
||||
// A sustained outage would otherwise warn for every waiting file on each 30 s scan.
|
||||
if (attempt <= 3 || attempt % 10 === 0) {
|
||||
logger.warn(
|
||||
@@ -223,11 +202,6 @@ export async function uploadDeviceRunSessionScreenshotsAsync(
|
||||
saveFailures++;
|
||||
continue;
|
||||
}
|
||||
const failure = failedUploads.get(entry.name);
|
||||
if (failure?.lastError instanceof DeviceRunSessionArtifactRejectedError) {
|
||||
continue;
|
||||
}
|
||||
const request = failure?.request ?? { idempotencyKey: randomUUID() };
|
||||
let size: number | undefined;
|
||||
try {
|
||||
size = (await stat(file)).size;
|
||||
@@ -240,7 +214,6 @@ export async function uploadDeviceRunSessionScreenshotsAsync(
|
||||
session,
|
||||
signal,
|
||||
failedUploads,
|
||||
request,
|
||||
logger,
|
||||
});
|
||||
uploadedCount++;
|
||||
@@ -254,7 +227,6 @@ export async function uploadDeviceRunSessionScreenshotsAsync(
|
||||
size,
|
||||
signal,
|
||||
failedUploads,
|
||||
request,
|
||||
logger,
|
||||
});
|
||||
if (outcome === 'aborted') {
|
||||
|
||||
@@ -61,12 +61,8 @@ export type CreateDeviceRunSessionArtifactUploadSessionInput = {
|
||||
kind?: string | null;
|
||||
size: number;
|
||||
metadata?: Record<string, unknown> | null;
|
||||
idempotencyKey: string;
|
||||
};
|
||||
|
||||
/** Why the worker stops a session; www stores it as the session's end reason. */
|
||||
export type DeviceRunSessionStopReason = 'idle_timeout' | 'max_duration';
|
||||
|
||||
/**
|
||||
* Client for the www routes under `/v2/device-run-session-worker/`. These routes act only on the
|
||||
* session that the token names.
|
||||
@@ -100,25 +96,19 @@ export class DeviceRunSessionWorkerApi {
|
||||
});
|
||||
}
|
||||
|
||||
public async stopAsync(
|
||||
{ reason }: { reason?: DeviceRunSessionStopReason } = {},
|
||||
options: WorkerApiRequestOptions = {}
|
||||
): Promise<DeviceRunSessionStatus> {
|
||||
return await this.client.requestAsync('POST', 'stop', DeviceRunSessionStatusSchema, {
|
||||
...options,
|
||||
...(reason ? { json: { reason } } : {}),
|
||||
});
|
||||
public async stopAsync(options: WorkerApiRequestOptions = {}): Promise<DeviceRunSessionStatus> {
|
||||
return await this.client.requestAsync('POST', 'stop', DeviceRunSessionStatusSchema, options);
|
||||
}
|
||||
|
||||
public async createArtifactUploadSessionAsync(
|
||||
{ idempotencyKey, ...input }: CreateDeviceRunSessionArtifactUploadSessionInput,
|
||||
input: CreateDeviceRunSessionArtifactUploadSessionInput,
|
||||
options: WorkerApiRequestOptions = {}
|
||||
): Promise<DeviceRunSessionUploadSession> {
|
||||
const { uploadSession } = await this.client.requestAsync(
|
||||
'POST',
|
||||
'artifact-upload-sessions',
|
||||
UploadSessionSchema,
|
||||
{ ...options, json: input, idempotencyKey }
|
||||
{ ...options, json: input }
|
||||
);
|
||||
return uploadSession;
|
||||
}
|
||||
|
||||
@@ -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, {
|
||||
|
||||
@@ -1,19 +1,20 @@
|
||||
import { bunyan } from '@expo/logger';
|
||||
import { BuildStepEnv } from '@expo/steps';
|
||||
import spawn, { SpawnResult } from '@expo/turtle-spawn';
|
||||
import path from 'path';
|
||||
|
||||
import { COMMON_FASTLANE_ENV, DEFAULT_FASTLANE_GYM_ENV } from '../../../common/fastlane';
|
||||
import { XcodeBuildLogger } from '../../../common/xcpretty';
|
||||
|
||||
export async function runFastlaneGym({
|
||||
workingDir,
|
||||
gymfileDirectory,
|
||||
logger,
|
||||
buildLogsDirectory,
|
||||
env,
|
||||
extraEnv,
|
||||
}: {
|
||||
workingDir: string;
|
||||
gymfileDirectory: string;
|
||||
logger: bunyan;
|
||||
buildLogsDirectory: string;
|
||||
env: BuildStepEnv;
|
||||
@@ -23,7 +24,7 @@ export async function runFastlaneGym({
|
||||
void buildLogger.watchLogFiles(buildLogsDirectory);
|
||||
try {
|
||||
await runFastlane(['gym'], {
|
||||
cwd: path.join(workingDir, 'ios'),
|
||||
cwd: gymfileDirectory,
|
||||
logger,
|
||||
env: { ...DEFAULT_FASTLANE_GYM_ENV, ...env },
|
||||
extraEnv,
|
||||
|
||||
@@ -20,5 +20,5 @@ export async function isTVOS({
|
||||
targetName,
|
||||
buildConfiguration,
|
||||
});
|
||||
return xcBuildConfiguration?.buildSettings?.SDKROOT?.includes('appletv');
|
||||
return xcBuildConfiguration?.buildSettings?.SDKROOT?.includes('appletv') ?? false;
|
||||
}
|
||||
+761
@@ -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 */;
|
||||
}
|
||||
+87
@@ -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,173 @@
|
||||
import { vol } from 'memfs';
|
||||
import path from 'path';
|
||||
|
||||
import { getBuildConfigurations, openXcodeProject } from '../pbxproj';
|
||||
import {
|
||||
SigningBuildSettings,
|
||||
TargetSigning,
|
||||
assertSigningBuildSettingsAreEffective,
|
||||
writeSigningBuildSettingsAsync,
|
||||
} from '../signing';
|
||||
|
||||
const originalFs = jest.requireActual('fs');
|
||||
|
||||
const xcodeprojPath = '/project/App.xcodeproj';
|
||||
const NATIVE_APP_TARGET_ID = '2870BA69F546F142D461562E';
|
||||
const MULTITARGET_APP_TARGET_ID = '13B07F861A680F5B00A75B9A';
|
||||
const SIGNING_BUILD_SETTINGS: SigningBuildSettings = {
|
||||
PROVISIONING_PROFILE_SPECIFIER: 'App Store Profile',
|
||||
DEVELOPMENT_TEAM: 'ABCDE12345',
|
||||
CODE_SIGN_IDENTITY: 'iPhone Distribution',
|
||||
CODE_SIGN_STYLE: 'Manual',
|
||||
};
|
||||
const NATIVE_APP_SIGNING: TargetSigning = {
|
||||
target: { id: NATIVE_APP_TARGET_ID, name: 'NativeApp' },
|
||||
buildSettings: SIGNING_BUILD_SETTINGS,
|
||||
};
|
||||
|
||||
function writeProjectFile(contents: string): void {
|
||||
vol.fromJSON({ [`${xcodeprojPath}/project.pbxproj`]: contents });
|
||||
}
|
||||
|
||||
function readFixture(relativePath: string): string {
|
||||
return originalFs.readFileSync(path.join(__dirname, relativePath), 'utf-8');
|
||||
}
|
||||
|
||||
function readBuildSettings(targetId: string, buildConfiguration: string): Record<string, unknown> {
|
||||
return getBuildConfigurations(openXcodeProject(xcodeprojPath), targetId).find(
|
||||
({ name }) => name === buildConfiguration
|
||||
)!.buildSettings;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vol.reset();
|
||||
});
|
||||
|
||||
describe(writeSigningBuildSettingsAsync, () => {
|
||||
it('writes the settings on the build configuration and removes their conditional variants', async () => {
|
||||
writeProjectFile(
|
||||
readFixture('fixtures/native-app.pbxproj').replaceAll(
|
||||
'PRODUCT_BUNDLE_IDENTIFIER = dev.expo.nativeapp;',
|
||||
[
|
||||
'PRODUCT_BUNDLE_IDENTIFIER = dev.expo.nativeapp;',
|
||||
'"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";',
|
||||
'"CODE_SIGN_STYLE[sdk=iphoneos*]" = Automatic;',
|
||||
'"DEVELOPMENT_TEAM[sdk=iphoneos*]" = OLDTEAM123;',
|
||||
'"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" = "Old Profile";',
|
||||
'"OTHER_LDFLAGS[sdk=iphoneos*]" = "-ObjC";',
|
||||
].join('\n')
|
||||
)
|
||||
);
|
||||
|
||||
await writeSigningBuildSettingsAsync({
|
||||
xcodeprojPath,
|
||||
buildConfiguration: 'Release',
|
||||
targetSignings: [NATIVE_APP_SIGNING],
|
||||
});
|
||||
|
||||
const releaseBuildSettings = readBuildSettings(NATIVE_APP_TARGET_ID, 'Release');
|
||||
expect(releaseBuildSettings).toMatchObject({
|
||||
PROVISIONING_PROFILE_SPECIFIER: '"App Store Profile"',
|
||||
DEVELOPMENT_TEAM: '"ABCDE12345"',
|
||||
CODE_SIGN_IDENTITY: '"iPhone Distribution"',
|
||||
CODE_SIGN_STYLE: '"Manual"',
|
||||
});
|
||||
expect(Object.keys(releaseBuildSettings).filter(key => key.includes('[sdk='))).toEqual([
|
||||
'"OTHER_LDFLAGS[sdk=iphoneos*]"',
|
||||
]);
|
||||
expect(readBuildSettings(NATIVE_APP_TARGET_ID, 'Debug')).toMatchObject({
|
||||
CODE_SIGN_STYLE: 'Automatic',
|
||||
'"CODE_SIGN_IDENTITY[sdk=iphoneos*]"': '"iPhone Developer"',
|
||||
'"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]"': '"Old Profile"',
|
||||
});
|
||||
});
|
||||
|
||||
it('escapes double quotes and backslashes in the values', async () => {
|
||||
writeProjectFile(readFixture('fixtures/native-app.pbxproj'));
|
||||
|
||||
await writeSigningBuildSettingsAsync({
|
||||
xcodeprojPath,
|
||||
buildConfiguration: 'Release',
|
||||
targetSignings: [
|
||||
{
|
||||
...NATIVE_APP_SIGNING,
|
||||
buildSettings: {
|
||||
...SIGNING_BUILD_SETTINGS,
|
||||
PROVISIONING_PROFILE_SPECIFIER: 'App "Ad Hoc" Profile \\ 1',
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(readBuildSettings(NATIVE_APP_TARGET_ID, 'Release')).toMatchObject({
|
||||
PROVISIONING_PROFILE_SPECIFIER: '"App \\"Ad Hoc\\" Profile \\\\ 1"',
|
||||
});
|
||||
});
|
||||
|
||||
it('writes the settings when the project has no attributes', async () => {
|
||||
writeProjectFile(
|
||||
readFixture('fixtures/native-app.pbxproj').replace(/\t\t\tattributes = \{[^}]*\};\n/, '')
|
||||
);
|
||||
|
||||
await writeSigningBuildSettingsAsync({
|
||||
xcodeprojPath,
|
||||
buildConfiguration: 'Release',
|
||||
targetSignings: [NATIVE_APP_SIGNING],
|
||||
});
|
||||
|
||||
expect(readBuildSettings(NATIVE_APP_TARGET_ID, 'Release')).toMatchObject({
|
||||
CODE_SIGN_STYLE: '"Manual"',
|
||||
});
|
||||
});
|
||||
|
||||
it('sets manual signing in the target attributes when the project has target attributes', async () => {
|
||||
writeProjectFile(readFixture('../../__tests__/fixtures/multitarget-project.pbxproj'));
|
||||
|
||||
await writeSigningBuildSettingsAsync({
|
||||
xcodeprojPath,
|
||||
buildConfiguration: 'Release',
|
||||
targetSignings: [
|
||||
{
|
||||
target: { id: MULTITARGET_APP_TARGET_ID, name: 'multitarget' },
|
||||
buildSettings: SIGNING_BUILD_SETTINGS,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(
|
||||
openXcodeProject(xcodeprojPath).getFirstProject().firstProject.attributes.TargetAttributes[
|
||||
MULTITARGET_APP_TARGET_ID
|
||||
]
|
||||
).toMatchObject({ DevelopmentTeam: '"ABCDE12345"', ProvisioningStyle: '"Manual"' });
|
||||
});
|
||||
});
|
||||
|
||||
describe(assertSigningBuildSettingsAreEffective, () => {
|
||||
function assertWithEffectiveBuildSettings(buildSettings: Record<string, string>): void {
|
||||
assertSigningBuildSettingsAreEffective({
|
||||
buildConfiguration: 'Release',
|
||||
targetSignings: [NATIVE_APP_SIGNING],
|
||||
effectiveBuildSettingsByTargetName: { NativeApp: buildSettings },
|
||||
});
|
||||
}
|
||||
|
||||
it('passes when Xcode resolves every setting to the written value', () => {
|
||||
expect(() => assertWithEffectiveBuildSettings(SIGNING_BUILD_SETTINGS)).not.toThrow();
|
||||
});
|
||||
|
||||
it('fails when Xcode resolves a setting to another value', () => {
|
||||
expect(() =>
|
||||
assertWithEffectiveBuildSettings({
|
||||
...SIGNING_BUILD_SETTINGS,
|
||||
PROVISIONING_PROFILE_SPECIFIER: 'Profile From Xcconfig',
|
||||
})
|
||||
).toThrow(
|
||||
expect.objectContaining({
|
||||
errorCode: 'NATIVE_XCODE_SIGNING_SETTING_OVERRIDDEN',
|
||||
message: expect.stringMatching(
|
||||
/PROVISIONING_PROFILE_SPECIFIER to "App Store Profile" on the target "NativeApp".*"Profile From Xcconfig"/
|
||||
),
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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,90 @@
|
||||
import { IOSConfig } from '@expo/config-plugins';
|
||||
import { UserError } from '@expo/eas-build-job';
|
||||
import assert from 'node:assert';
|
||||
import fs from 'node:fs';
|
||||
|
||||
import { XcodeTarget, getBuildConfigurations, openXcodeProject } from './pbxproj';
|
||||
|
||||
const SIGNING_BUILD_SETTING_NAMES = [
|
||||
'PROVISIONING_PROFILE_SPECIFIER',
|
||||
'DEVELOPMENT_TEAM',
|
||||
'CODE_SIGN_IDENTITY',
|
||||
'CODE_SIGN_STYLE',
|
||||
] as const;
|
||||
|
||||
export type SigningBuildSettings = Record<(typeof SIGNING_BUILD_SETTING_NAMES)[number], string>;
|
||||
|
||||
export interface TargetSigning {
|
||||
target: XcodeTarget;
|
||||
buildSettings: SigningBuildSettings;
|
||||
}
|
||||
|
||||
export async function writeSigningBuildSettingsAsync({
|
||||
xcodeprojPath,
|
||||
buildConfiguration,
|
||||
targetSignings,
|
||||
}: {
|
||||
xcodeprojPath: string;
|
||||
buildConfiguration: string;
|
||||
targetSignings: TargetSigning[];
|
||||
}): Promise<void> {
|
||||
const project = openXcodeProject(xcodeprojPath);
|
||||
const targetAttributesById: Record<string, object> | undefined =
|
||||
project.getFirstProject().firstProject.attributes?.TargetAttributes;
|
||||
for (const { target, buildSettings } of targetSignings) {
|
||||
const targetBuildSettings = getBuildConfigurations(project, target.id).find(
|
||||
({ name }) => IOSConfig.XcodeUtils.unquote(name) === buildConfiguration
|
||||
)?.buildSettings;
|
||||
assert(
|
||||
targetBuildSettings,
|
||||
`Target "${target.name}" has no build configuration named "${buildConfiguration}"`
|
||||
);
|
||||
for (const key of Object.keys(targetBuildSettings)) {
|
||||
if (isConditionalVariantOfSigningBuildSetting(key)) {
|
||||
delete targetBuildSettings[key];
|
||||
}
|
||||
}
|
||||
for (const name of SIGNING_BUILD_SETTING_NAMES) {
|
||||
targetBuildSettings[name] = quote(buildSettings[name]);
|
||||
}
|
||||
if (targetAttributesById) {
|
||||
targetAttributesById[target.id] = {
|
||||
...targetAttributesById[target.id],
|
||||
DevelopmentTeam: quote(buildSettings.DEVELOPMENT_TEAM),
|
||||
ProvisioningStyle: quote(buildSettings.CODE_SIGN_STYLE),
|
||||
};
|
||||
}
|
||||
}
|
||||
await fs.promises.writeFile(project.filepath, project.writeSync());
|
||||
}
|
||||
|
||||
export function assertSigningBuildSettingsAreEffective({
|
||||
buildConfiguration,
|
||||
targetSignings,
|
||||
effectiveBuildSettingsByTargetName,
|
||||
}: {
|
||||
buildConfiguration: string;
|
||||
targetSignings: TargetSigning[];
|
||||
effectiveBuildSettingsByTargetName: Record<string, Record<string, string>>;
|
||||
}): void {
|
||||
for (const { target, buildSettings } of targetSignings) {
|
||||
for (const name of SIGNING_BUILD_SETTING_NAMES) {
|
||||
const effectiveValue = effectiveBuildSettingsByTargetName[target.name]?.[name];
|
||||
if (effectiveValue !== buildSettings[name]) {
|
||||
throw new UserError(
|
||||
'NATIVE_XCODE_SIGNING_SETTING_OVERRIDDEN',
|
||||
`EAS set ${name} to "${buildSettings[name]}" on the target "${target.name}" for the build configuration "${buildConfiguration}", but Xcode resolves it to "${effectiveValue}". Another definition of ${name} overrides the one EAS wrote, so the target would be signed with the wrong credentials. Remove the other definition of ${name} for this target, for example one with a condition in an ".xcconfig" file.`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isConditionalVariantOfSigningBuildSetting(buildSettingKey: string): boolean {
|
||||
const key = IOSConfig.XcodeUtils.unquote(buildSettingKey);
|
||||
return SIGNING_BUILD_SETTING_NAMES.some(name => key.startsWith(`${name}[`));
|
||||
}
|
||||
|
||||
function quote(value: string): string {
|
||||
return `"${value.replace(/[\\"]/g, '\\$&')}"`;
|
||||
}
|
||||
@@ -29,7 +29,6 @@ import { createProcessOutput } from './processOutput';
|
||||
import { withDeviceRunSessionTimeoutAsync } from './deviceRunSessionTimeout';
|
||||
import {
|
||||
type DeviceRunSessionStatus,
|
||||
type DeviceRunSessionStopReason,
|
||||
requireDeviceRunSessionWorkerApi,
|
||||
} from './deviceRunSessionWorkerApi';
|
||||
import { WorkerApiError } from './workerApi';
|
||||
@@ -194,12 +193,7 @@ export async function waitForDeviceRunSessionStoppedAsync({
|
||||
`Device run session ${deviceRunSessionId} had no activity for ` +
|
||||
`${idleTimeout.maxIdleTimeMinutes} minute(s) (max idle time). Stopping the session.`
|
||||
);
|
||||
await ensureDeviceRunSessionStoppedSafelyAsync({
|
||||
ctx,
|
||||
deviceRunSessionId,
|
||||
logger,
|
||||
reason: 'idle_timeout',
|
||||
});
|
||||
await ensureDeviceRunSessionStoppedSafelyAsync({ ctx, deviceRunSessionId, logger });
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -218,7 +212,7 @@ export async function waitForDeviceRunSessionStoppedAsync({
|
||||
throw err;
|
||||
}
|
||||
if (signal.aborted) {
|
||||
break;
|
||||
return;
|
||||
}
|
||||
|
||||
const error = err instanceof Error ? err : new Error(String(err));
|
||||
@@ -233,15 +227,6 @@ export async function waitForDeviceRunSessionStoppedAsync({
|
||||
}
|
||||
await sleepUntilAbortedAsync(DEVICE_RUN_SESSION_STATUS_POLL_INTERVAL_MS, signal);
|
||||
}
|
||||
// Stop through the worker route so www records the reason; a canceled step is not a max-duration end.
|
||||
if (durationAbortController.signal.aborted && !cancelSignal?.aborted) {
|
||||
await ensureDeviceRunSessionStoppedSafelyAsync({
|
||||
ctx,
|
||||
deviceRunSessionId,
|
||||
logger,
|
||||
reason: 'max_duration',
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
if (durationTimeout !== undefined) {
|
||||
clearTimeout(durationTimeout);
|
||||
@@ -269,23 +254,20 @@ async function ensureDeviceRunSessionStoppedSafelyAsync({
|
||||
ctx,
|
||||
deviceRunSessionId,
|
||||
logger,
|
||||
reason,
|
||||
}: {
|
||||
ctx: CustomBuildContext;
|
||||
deviceRunSessionId: string;
|
||||
logger: bunyan;
|
||||
reason: DeviceRunSessionStopReason;
|
||||
}): Promise<void> {
|
||||
try {
|
||||
await requireDeviceRunSessionWorkerApi(ctx).stopAsync(
|
||||
{ reason },
|
||||
{ timeoutMs: DEVICE_RUN_SESSION_WORKER_REQUEST_TIMEOUT_MS }
|
||||
);
|
||||
await requireDeviceRunSessionWorkerApi(ctx).stopAsync({
|
||||
timeoutMs: DEVICE_RUN_SESSION_WORKER_REQUEST_TIMEOUT_MS,
|
||||
});
|
||||
} catch (err) {
|
||||
const error = err instanceof Error ? err : new Error(String(err));
|
||||
Sentry.capture('Could not mark device run session as stopped', error, {
|
||||
Sentry.capture('Could not mark idle device run session as stopped', error, {
|
||||
level: 'warning',
|
||||
extras: { deviceRunSessionId, reason },
|
||||
extras: { deviceRunSessionId },
|
||||
});
|
||||
logger.warn(
|
||||
{ err: error },
|
||||
|
||||
@@ -15,15 +15,8 @@ import { type SandboxArtifactUploadSession, type SandboxWorkerApi } from './sand
|
||||
import { WorkerApiError } from './workerApi';
|
||||
|
||||
const WORKER_API_REQUEST_TIMEOUT_MS = 15_000;
|
||||
const UPLOAD_SESSION_RETRIES = 2;
|
||||
const UPLOAD_SESSION_ATTEMPT_TIMEOUT_MS = 8_000;
|
||||
const UPLOAD_SESSION_DEADLINE_MS = 25_000;
|
||||
const FINALIZE_RETRIES = 2;
|
||||
const REJECTED_UPLOAD_SESSION_ERROR_CODES = new Set([
|
||||
'VALIDATION_ERROR',
|
||||
'UNAUTHORIZED',
|
||||
'ARTIFACT_NAME_CONFLICT',
|
||||
]);
|
||||
const REJECTED_UPLOAD_SESSION_ERROR_CODES = new Set(['VALIDATION_ERROR', 'UNAUTHORIZED']);
|
||||
|
||||
type SandboxArtifactUploadOutcome =
|
||||
| { status: 'uploaded'; downloadUrl: string }
|
||||
@@ -131,7 +124,7 @@ export async function startSandboxArtifactUploadAsync({
|
||||
} = await createSandboxArtifactUploadSessionAsync(
|
||||
workerApi,
|
||||
{ name, filename: path.basename(filePath), size },
|
||||
{ signal, logger }
|
||||
signal
|
||||
);
|
||||
const completed = (async (): Promise<SandboxArtifactUploadOutcome> => {
|
||||
logger.info(`Uploading sandbox artifact "${name}" (${artifactId}, ${size} bytes).`);
|
||||
@@ -165,30 +158,15 @@ export async function startSandboxArtifactUploadAsync({
|
||||
async function createSandboxArtifactUploadSessionAsync(
|
||||
workerApi: SandboxWorkerApi,
|
||||
input: { name: string; filename: string; size: number },
|
||||
{ signal, logger }: { signal: AbortSignal; logger: bunyan }
|
||||
signal: AbortSignal
|
||||
): Promise<SandboxArtifactUploadSession> {
|
||||
const deadline = new AbortController();
|
||||
const deadlineTimer = setTimeout(
|
||||
() =>
|
||||
deadline.abort(
|
||||
new Error(
|
||||
`Could not create an upload session for sandbox artifact "${input.name}" within ${
|
||||
UPLOAD_SESSION_DEADLINE_MS / 1000
|
||||
} seconds.`
|
||||
)
|
||||
),
|
||||
UPLOAD_SESSION_DEADLINE_MS
|
||||
);
|
||||
try {
|
||||
return await workerApi.createArtifactUploadSessionAsync(input, {
|
||||
signal: AbortSignal.any([signal, deadline.signal]),
|
||||
timeoutMs: UPLOAD_SESSION_ATTEMPT_TIMEOUT_MS,
|
||||
retries: UPLOAD_SESSION_RETRIES,
|
||||
logger,
|
||||
signal,
|
||||
timeoutMs: WORKER_API_REQUEST_TIMEOUT_MS,
|
||||
});
|
||||
} catch (error) {
|
||||
signal.throwIfAborted();
|
||||
deadline.signal.throwIfAborted();
|
||||
if (
|
||||
error instanceof WorkerApiError &&
|
||||
error.code !== undefined &&
|
||||
@@ -199,8 +177,6 @@ async function createSandboxArtifactUploadSessionAsync(
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
clearTimeout(deadlineTimer);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { type Env, type EnvironmentSecret, type Job, SystemError } from '@expo/eas-build-job';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { z } from 'zod';
|
||||
|
||||
import {
|
||||
@@ -66,7 +65,7 @@ export class SandboxWorkerApi {
|
||||
'POST',
|
||||
'artifact-upload-sessions',
|
||||
ArtifactUploadSessionSchema,
|
||||
{ ...options, json: input, idempotencyKey: randomUUID() }
|
||||
{ ...options, json: input }
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { SystemError, UserError } from '@expo/eas-build-job';
|
||||
import { SystemError } from '@expo/eas-build-job';
|
||||
import { constants } from 'node:fs';
|
||||
import { cp, mkdir, mkdtemp, realpath, rm } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
@@ -104,11 +104,8 @@ export async function runServeSimActionWithResultAsync({
|
||||
finish(
|
||||
reply.exitCode === 0
|
||||
? undefined
|
||||
: createServeSimActionError(
|
||||
action,
|
||||
(typeof reply.error === 'string' && reply.error) ||
|
||||
(typeof reply.stderr === 'string' && reply.stderr) ||
|
||||
'invalid response'
|
||||
: new SystemError(
|
||||
`serve-sim ${action} failed: ${(typeof reply.error === 'string' && reply.error) || (typeof reply.stderr === 'string' && reply.stderr) || 'invalid response'}`
|
||||
),
|
||||
typeof reply.stdout === 'string' ? reply.stdout : ''
|
||||
);
|
||||
@@ -119,18 +116,3 @@ export async function runServeSimActionWithResultAsync({
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// simctl's IXUserPresentableErrorDomain message when the app's minimum iOS version is above the Simulator runtime.
|
||||
const NEWER_IOS_REQUIRED_MESSAGE = 'Requires a Newer Version of iOS';
|
||||
|
||||
function createServeSimActionError(action: string, detail: string): Error {
|
||||
const message = `serve-sim ${action} failed: ${detail}`;
|
||||
if (action === 'app.install' && detail.includes(NEWER_IOS_REQUIRED_MESSAGE)) {
|
||||
return new UserError(
|
||||
'EAS_INSTALL_APPLICATION_REQUIRES_NEWER_IOS',
|
||||
"This app requires a newer iOS version than the selected iOS Simulator runs. Choose an iOS Simulator device whose iOS version meets the app's minimum iOS version, or lower the app's iOS deployment target.",
|
||||
{ cause: new Error(message) }
|
||||
);
|
||||
}
|
||||
return new SystemError(message);
|
||||
}
|
||||
@@ -26,11 +26,6 @@ export type WorkerApiRequestOptions = {
|
||||
logger?: bunyan;
|
||||
};
|
||||
|
||||
type WorkerApiRequest = WorkerApiRequestOptions & {
|
||||
json?: Record<string, unknown>;
|
||||
idempotencyKey?: string;
|
||||
};
|
||||
|
||||
const ApiV2ErrorResponseSchema = z.object({
|
||||
errors: z.array(z.object({ code: z.string().optional(), message: z.string() })).min(1),
|
||||
});
|
||||
@@ -52,7 +47,7 @@ export class WorkerApiError extends Error {
|
||||
}
|
||||
|
||||
get isTransient(): boolean {
|
||||
return this.status === undefined || this.status === 429 || this.status >= 500;
|
||||
return this.status === undefined || this.status >= 500;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,7 +66,7 @@ export class WorkerApi {
|
||||
method: 'GET' | 'POST',
|
||||
route: string,
|
||||
dataSchema: z.ZodType<T>,
|
||||
{ retries = 0, ...options }: WorkerApiRequest = {}
|
||||
{ retries = 0, ...options }: WorkerApiRequestOptions & { json?: Record<string, unknown> } = {}
|
||||
): Promise<T> {
|
||||
const url = new URL(route, this.baseUrl);
|
||||
const routeDescription = `${method} ${url.pathname}`;
|
||||
@@ -84,7 +79,10 @@ export class WorkerApi {
|
||||
}
|
||||
return await promiseRetryWithCondition(
|
||||
request,
|
||||
error => !options.signal?.aborted && error instanceof WorkerApiError && error.isTransient,
|
||||
error =>
|
||||
!options.signal?.aborted &&
|
||||
error instanceof WorkerApiError &&
|
||||
(error.status === undefined || error.status === 429 || error.status >= 500),
|
||||
{ retries, factor: 2, minTimeout: 1000 },
|
||||
({ attemptNumber, maxAttemptsCount }) =>
|
||||
options.logger?.warn(
|
||||
@@ -98,14 +96,18 @@ export class WorkerApi {
|
||||
url: string,
|
||||
routeDescription: string,
|
||||
dataSchema: z.ZodType<T>,
|
||||
{ signal, timeoutMs, logger, json, idempotencyKey }: Omit<WorkerApiRequest, 'retries'>
|
||||
{
|
||||
signal,
|
||||
timeoutMs,
|
||||
logger,
|
||||
json,
|
||||
}: Omit<WorkerApiRequestOptions, 'retries'> & {
|
||||
json?: Record<string, unknown>;
|
||||
}
|
||||
): Promise<T> {
|
||||
const responseResult = await asyncResult(
|
||||
turtleFetch(url, method, {
|
||||
headers: {
|
||||
[this.auth.authHeader]: this.auth.token,
|
||||
...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}),
|
||||
},
|
||||
headers: { [this.auth.authHeader]: this.auth.token },
|
||||
...(json ? { json } : {}),
|
||||
...(signal ? { signal } : {}),
|
||||
...(timeoutMs !== undefined ? { timeout: timeoutMs } : {}),
|
||||
|
||||
@@ -21,5 +21,5 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
"include": ["src/**/*", "../../ts-declarations/xcode/index.d.ts"]
|
||||
}
|
||||
@@ -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',
|
||||
])
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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]');
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
});
|
||||
@@ -12,6 +12,11 @@ export enum BuildMode {
|
||||
REPACK = 'repack',
|
||||
}
|
||||
|
||||
export enum NativeBuilder {
|
||||
XCODE = 'xcode',
|
||||
GRADLE = 'gradle',
|
||||
}
|
||||
|
||||
export enum Workflow {
|
||||
GENERIC = 'generic',
|
||||
MANAGED = 'managed',
|
||||
@@ -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',
|
||||
|
||||
@@ -14,6 +14,7 @@ export {
|
||||
EnvironmentSecret,
|
||||
EnvironmentSecretType,
|
||||
Hooks,
|
||||
NativeBuilder,
|
||||
SshSettings,
|
||||
Workflow,
|
||||
Platform,
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
@@ -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 {
|
||||
|
||||
@@ -227,12 +227,6 @@
|
||||
"project": {
|
||||
"description": "manage project"
|
||||
},
|
||||
"project:icon": {
|
||||
"description": "manage the project icon displayed on the EAS dashboard"
|
||||
},
|
||||
"project:name": {
|
||||
"description": "manage the project display name shown on the EAS dashboard"
|
||||
},
|
||||
"release": {
|
||||
"description": "manage update releases"
|
||||
},
|
||||
|
||||
@@ -190,7 +190,7 @@ describe(WorkflowLogView, () => {
|
||||
},
|
||||
},
|
||||
platform: AppPlatform.Android,
|
||||
logFileUrls: ['https://example.com/log1'],
|
||||
logFiles: ['https://example.com/log1'],
|
||||
});
|
||||
let promptCalls = 0;
|
||||
let stepPrompt: any;
|
||||
|
||||
@@ -72,7 +72,7 @@ function createMockBuildFragment({
|
||||
updatedAt: new Date().toISOString(),
|
||||
platform: AppPlatform.Android,
|
||||
id: buildId ?? uuid(),
|
||||
logFileUrls: [],
|
||||
logFiles: [],
|
||||
priority: BuildPriority.Normal,
|
||||
app: {
|
||||
__typename: 'App',
|
||||
|
||||
@@ -70,7 +70,7 @@ function createMockBuildFragment({
|
||||
return {
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
logFileUrls: [],
|
||||
logFiles: [],
|
||||
platform: AppPlatform.Android,
|
||||
id: buildId ?? uuid(),
|
||||
priority: BuildPriority.Normal,
|
||||
|
||||
@@ -26,7 +26,7 @@ function createBuildFragment(overrides: Partial<BuildFragment> = {}): BuildFragm
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
platform: AppPlatform.Android,
|
||||
logFileUrls: [],
|
||||
logFiles: [],
|
||||
priority: BuildPriority.Normal,
|
||||
app: {
|
||||
__typename: 'App',
|
||||
@@ -98,7 +98,7 @@ describe(logSourceForBuild, () => {
|
||||
} as any);
|
||||
|
||||
const source = logSourceForBuild(
|
||||
createBuildFragment({ logFileUrls: ['https://logs.test/first', 'https://logs.test/second'] })
|
||||
createBuildFragment({ logFiles: ['https://logs.test/first', 'https://logs.test/second'] })
|
||||
);
|
||||
|
||||
await expect(source.fetchRawLogLinesAsync()).resolves.toEqual([
|
||||
@@ -113,7 +113,7 @@ describe(logSourceForBuild, () => {
|
||||
|
||||
it('returns null when the build has no log file', async () => {
|
||||
await expect(
|
||||
logSourceForBuild(createBuildFragment({ logFileUrls: [] })).fetchRawLogLinesAsync()
|
||||
logSourceForBuild(createBuildFragment({ logFiles: [] })).fetchRawLogLinesAsync()
|
||||
).resolves.toBeNull();
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -47,7 +47,7 @@ function createBuildFragment(status: BuildStatus): BuildFragment {
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
platform: AppPlatform.Android,
|
||||
logFileUrls: [],
|
||||
logFiles: [],
|
||||
priority: BuildPriority.Normal,
|
||||
app: {
|
||||
__typename: 'App',
|
||||
|
||||
@@ -2,6 +2,7 @@ import { ArchiveSource, ArchiveSourceType, BuildJob, Metadata, Platform, formatB
|
||||
import { CredentialsSource } from '@expo/eas-json';
|
||||
import assert from 'assert';
|
||||
import chalk from 'chalk';
|
||||
import cliProgress from 'cli-progress';
|
||||
import fs from 'fs-extra';
|
||||
import { GraphQLError } from 'graphql/error';
|
||||
import nullthrows from 'nullthrows';
|
||||
@@ -60,6 +61,7 @@ import {
|
||||
BuildFragment,
|
||||
BuildMetadataInput,
|
||||
BuildParamsInput,
|
||||
BuildPriority,
|
||||
BuildStatus,
|
||||
FingerprintSourceInput,
|
||||
UploadSessionType,
|
||||
@@ -649,6 +651,12 @@ type BuildLogsProgressOptions = {
|
||||
installRender: (render: () => void) => void;
|
||||
};
|
||||
|
||||
let queueProgressBarStarted = false;
|
||||
const queueProgressBar = new cliProgress.SingleBar(
|
||||
{ format: '|{bar}| {estimatedWaitTime}' },
|
||||
cliProgress.Presets.rect
|
||||
);
|
||||
|
||||
let statusNewSetAt: number | null = null;
|
||||
const NEW_STATUS_GRACE_PERIOD_MS = 15_000;
|
||||
|
||||
@@ -669,6 +677,18 @@ async function handleSingleBuildProgressAsync(
|
||||
return { refetch: true };
|
||||
}
|
||||
|
||||
if (queueProgressBarStarted && build?.status && build.status !== BuildStatus.InQueue) {
|
||||
if (build.status === BuildStatus.InProgress) {
|
||||
queueProgressBar.update(queueProgressBar.getTotal(), {
|
||||
estimatedWaitTime: '',
|
||||
});
|
||||
}
|
||||
queueProgressBar.stop();
|
||||
Log.newLine();
|
||||
queueProgressBarStarted = false;
|
||||
spinner.start('Build is about to start');
|
||||
}
|
||||
|
||||
switch (build.status) {
|
||||
case BuildStatus.Finished:
|
||||
spinner.succeed('Build finished');
|
||||
@@ -688,9 +708,40 @@ async function handleSingleBuildProgressAsync(
|
||||
}
|
||||
break;
|
||||
}
|
||||
case BuildStatus.InQueue:
|
||||
case BuildStatus.InQueue: {
|
||||
updateSpinnerText(spinner, { text: 'Build queued...' });
|
||||
const progressBarPayload =
|
||||
typeof build.estimatedWaitTimeLeftSeconds === 'number'
|
||||
? { estimatedWaitTime: formatEstimatedWaitTime(build.estimatedWaitTimeLeftSeconds) }
|
||||
: { estimatedWaitTime: '' };
|
||||
|
||||
if (
|
||||
!queueProgressBarStarted &&
|
||||
typeof build.initialQueuePosition === 'number' &&
|
||||
typeof build.queuePosition === 'number' &&
|
||||
typeof build.estimatedWaitTimeLeftSeconds === 'number'
|
||||
) {
|
||||
spinner.stopAndPersist();
|
||||
if (build.priority !== BuildPriority.High) {
|
||||
Log.newLine();
|
||||
Log.log('Start builds sooner in the priority queue.');
|
||||
Log.log(`Sign up for a paid plan at ${link(getAccountBillingUrl(accountName))}`);
|
||||
}
|
||||
|
||||
Log.newLine();
|
||||
Log.log(`Waiting in ${priorityToQueueDisplayName[build.priority]}`);
|
||||
queueProgressBar.start(
|
||||
build.initialQueuePosition + 1,
|
||||
build.initialQueuePosition - build.queuePosition + 1,
|
||||
progressBarPayload
|
||||
);
|
||||
queueProgressBarStarted = true;
|
||||
}
|
||||
if (typeof build.queuePosition === 'number') {
|
||||
queueProgressBar.update(build.queuePosition, progressBarPayload);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case BuildStatus.PendingCancel:
|
||||
case BuildStatus.Canceled:
|
||||
spinner.fail('Build canceled');
|
||||
@@ -720,6 +771,12 @@ async function handleSingleBuildProgressAsync(
|
||||
return { refetch: true };
|
||||
}
|
||||
|
||||
const priorityToQueueDisplayName: Record<BuildPriority, string> = {
|
||||
[BuildPriority.Normal]: 'Free tier queue',
|
||||
[BuildPriority.NormalPlus]: 'Free tier queue',
|
||||
[BuildPriority.High]: 'priority queue',
|
||||
};
|
||||
|
||||
const statusToDisplayName: Record<BuildStatus, string> = {
|
||||
[BuildStatus.New]: 'waiting to enter the queue',
|
||||
[BuildStatus.InQueue]: 'in queue',
|
||||
@@ -823,9 +880,26 @@ function formatPendingBuildsText(
|
||||
showConcurrencyWarning && build?.status === BuildStatus.New
|
||||
? ' (concurrency limit reached)'
|
||||
: '';
|
||||
let extraInfo = '';
|
||||
if (
|
||||
build?.status === BuildStatus.InQueue &&
|
||||
typeof build.initialQueuePosition === 'number' &&
|
||||
typeof build.queuePosition === 'number'
|
||||
) {
|
||||
const percent = Math.floor(
|
||||
((build.initialQueuePosition - build.queuePosition + 1) /
|
||||
(build.initialQueuePosition + 1)) *
|
||||
100
|
||||
);
|
||||
const estimatedWaitTime =
|
||||
typeof build.estimatedWaitTimeLeftSeconds === 'number'
|
||||
? ` - ${formatEstimatedWaitTime(build.estimatedWaitTimeLeftSeconds)}`
|
||||
: '';
|
||||
extraInfo = ` - queue progress: ${chalk.bold(`${percent}%`)}${estimatedWaitTime}`;
|
||||
}
|
||||
return `${appPlatformEmojis[platform]} ${
|
||||
appPlatformDisplayNames[platform]
|
||||
} build - status: ${chalk.bold(status)}${concurrencyWarning}`;
|
||||
} build - status: ${chalk.bold(status)}${concurrencyWarning}${extraInfo}`;
|
||||
}),
|
||||
].join('\n ');
|
||||
}
|
||||
@@ -834,6 +908,15 @@ function isBuildFragment(maybeBuild: MaybeBuildFragment): maybeBuild is BuildFra
|
||||
return maybeBuild !== null;
|
||||
}
|
||||
|
||||
function formatEstimatedWaitTime(estimatedWaitTimeLeftSeconds: number): string {
|
||||
if (estimatedWaitTimeLeftSeconds < 5 * 60) {
|
||||
return 'starting soon...';
|
||||
} else {
|
||||
const n = Math.floor(estimatedWaitTimeLeftSeconds / (10 * 60)) + 1;
|
||||
return `starting in about ${n}0 minutes...`;
|
||||
}
|
||||
}
|
||||
|
||||
async function computeAndMaybeUploadRuntimeAndFingerprintMetadataAsync<T extends Platform>(
|
||||
ctx: BuildContext<T>
|
||||
): Promise<{
|
||||
|
||||
@@ -15,7 +15,7 @@ const SINGLE_BUILD_MAX_LOG_LINES = 5;
|
||||
const MULTIPLE_BUILDS_MAX_LOG_LINES = 3;
|
||||
|
||||
async function fetchAndParseLogsForBuildAsync(build: BuildFragment): Promise<RawLogLine[] | null> {
|
||||
const logFileUrl = build.logFileUrls[0];
|
||||
const logFileUrl = build.logFiles[0];
|
||||
if (!logFileUrl) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ export async function fetchRawLogsForJobAsync(
|
||||
const buildFragment = await BuildQuery.byIdAsync(state.graphqlClient, buildId, {
|
||||
useCache: false,
|
||||
});
|
||||
const firstLogFileUrl = buildFragment.logFileUrls?.[0];
|
||||
const firstLogFileUrl = buildFragment.logFiles?.[0];
|
||||
if (!firstLogFileUrl) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
import { getMockOclifConfig } from '../../../__tests__/commands/utils';
|
||||
import { ExpoGraphqlClient } from '../../../commandUtils/context/contextUtils/createGraphqlClient';
|
||||
import { AppQuery } from '../../../graphql/queries/AppQuery';
|
||||
import Log from '../../../log';
|
||||
import ProjectInfo from '../info';
|
||||
|
||||
jest.mock('../../../graphql/queries/AppQuery');
|
||||
jest.mock('../../../log');
|
||||
|
||||
const projectId = 'test-project-id';
|
||||
|
||||
async function runAndGetOutputAsync(): Promise<string> {
|
||||
const command = new ProjectInfo([], getMockOclifConfig());
|
||||
// @ts-expect-error getContextAsync is protected
|
||||
jest.spyOn(command, 'getContextAsync').mockResolvedValue({
|
||||
projectId,
|
||||
loggedIn: { graphqlClient: {} as ExpoGraphqlClient },
|
||||
});
|
||||
await command.runAsync();
|
||||
return jest.mocked(Log.log).mock.calls.flat().join('\n');
|
||||
}
|
||||
|
||||
describe(ProjectInfo, () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
jest.mocked(AppQuery.byIdAsync).mockResolvedValue({
|
||||
id: projectId,
|
||||
name: 'My App',
|
||||
fullName: '@jester/my-app',
|
||||
slug: 'my-app',
|
||||
} as any);
|
||||
});
|
||||
|
||||
it('prints the display name, slug and icon URL', async () => {
|
||||
jest
|
||||
.mocked(AppQuery.byIdProfileImageUrlAsync)
|
||||
.mockResolvedValue('https://example.com/icon.png');
|
||||
|
||||
const output = await runAndGetOutputAsync();
|
||||
|
||||
expect(output).toMatch(/fullName.* @jester\/my-app/);
|
||||
expect(output).toMatch(/name.* My App/);
|
||||
expect(output).toMatch(/slug.* my-app/);
|
||||
expect(output).toMatch(/icon.* https:\/\/example\.com\/icon\.png/);
|
||||
expect(output).toMatch(/ID.* test-project-id/);
|
||||
});
|
||||
|
||||
it('prints "not set" when the project has no icon', async () => {
|
||||
jest.mocked(AppQuery.byIdProfileImageUrlAsync).mockResolvedValue(null);
|
||||
|
||||
expect(await runAndGetOutputAsync()).toMatch(/icon.* not set/);
|
||||
});
|
||||
});
|
||||
@@ -96,8 +96,9 @@ function makeSubmission(overrides: Partial<ProjectStatusSubmission> = {}): Proje
|
||||
createdAt: '2026-07-02T12:00:00.000Z',
|
||||
completedAt: '2026-07-02T12:05:00.000Z',
|
||||
initiatingActor: { id: 'actor-1', displayName: 'jester' },
|
||||
submittedBuild: { id: 'build-1', appIdentifier: 'com.example.app' },
|
||||
submittedBuild: { id: 'build-1' },
|
||||
androidConfig: {
|
||||
applicationIdentifier: 'com.example.app',
|
||||
track: 'production',
|
||||
releaseStatus: null,
|
||||
rollout: 50,
|
||||
|
||||
@@ -4,7 +4,6 @@ import { vol } from 'memfs';
|
||||
import { ExpoGraphqlClient } from '../../../../commandUtils/context/contextUtils/createGraphqlClient';
|
||||
import { AppUploadSessionType } from '../../../../graphql/generated';
|
||||
import { AppQuery } from '../../../../graphql/queries/AppQuery';
|
||||
import { getPrivateExpoConfigAsync } from '../../../../project/expoConfig';
|
||||
import { uploadAppScopedFileAtPathToGCSAsync } from '../../../../uploads';
|
||||
import { sleepAsync } from '../../../../utils/promise';
|
||||
import ProjectIconSet from '../set';
|
||||
@@ -12,7 +11,6 @@ import ProjectIconSet from '../set';
|
||||
jest.mock('fs');
|
||||
jest.mock('../../../../graphql/queries/AppQuery');
|
||||
jest.mock('../../../../log');
|
||||
jest.mock('../../../../project/expoConfig');
|
||||
jest.mock('../../../../ora', () => ({
|
||||
ora: jest.fn(() => {
|
||||
const spinner = {
|
||||
@@ -76,7 +74,6 @@ describe(ProjectIconSet, () => {
|
||||
// @ts-expect-error getContextAsync is protected
|
||||
jest.spyOn(command, 'getContextAsync').mockResolvedValue({
|
||||
projectId,
|
||||
projectDir: '/app',
|
||||
loggedIn: { graphqlClient },
|
||||
});
|
||||
return command;
|
||||
@@ -112,51 +109,12 @@ describe(ProjectIconSet, () => {
|
||||
expect(mockUploadAsync).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('uploads the icon from the app config when no path is given', async () => {
|
||||
vol.fromJSON({ '/app/assets/icon.png': 'fake-png-bytes' });
|
||||
jest.mocked(getPrivateExpoConfigAsync).mockResolvedValue({
|
||||
name: 'test',
|
||||
slug: 'test-project',
|
||||
icon: './assets/icon.png',
|
||||
} as any);
|
||||
mockByIdProfileImageUrlAsync
|
||||
.mockResolvedValueOnce('https://example.com/old.png')
|
||||
.mockResolvedValueOnce('https://example.com/new.png');
|
||||
|
||||
await createCommand([]).runAsync();
|
||||
|
||||
expect(mockUploadAsync).toHaveBeenCalledWith(graphqlClient, {
|
||||
type: AppUploadSessionType.ProfileImageUpload,
|
||||
appId: projectId,
|
||||
path: '/app/assets/icon.png',
|
||||
});
|
||||
});
|
||||
|
||||
it('throws when no path is given and the app config has no icon', async () => {
|
||||
jest
|
||||
.mocked(getPrivateExpoConfigAsync)
|
||||
.mockResolvedValue({ name: 'test', slug: 'test-project' } as any);
|
||||
|
||||
await expect(createCommand([]).runAsync()).rejects.toThrow(
|
||||
'No local icon found in the app config'
|
||||
);
|
||||
expect(mockUploadAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('throws when the file does not exist', async () => {
|
||||
const command = createCommand(['/app/missing.png']);
|
||||
await expect(command.runAsync()).rejects.toThrow('No file found at /app/missing.png');
|
||||
expect(mockUploadAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('throws for a directory', async () => {
|
||||
vol.fromJSON({ '/app/assets/icon.png': 'fake-png-bytes' });
|
||||
const command = createCommand(['/app/assets']);
|
||||
|
||||
await expect(command.runAsync()).rejects.toThrow('/app/assets is not a file.');
|
||||
expect(mockUploadAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('throws for an unsupported image format', async () => {
|
||||
vol.fromJSON({ '/app/icon.gif': 'fake-gif-bytes' });
|
||||
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
import { getMockOclifConfig } from '../../../../__tests__/commands/utils';
|
||||
import { ExpoGraphqlClient } from '../../../../commandUtils/context/contextUtils/createGraphqlClient';
|
||||
import { AppMutation } from '../../../../graphql/mutations/AppMutation';
|
||||
import Log from '../../../../log';
|
||||
import ProjectIconUnset from '../unset';
|
||||
|
||||
jest.mock('../../../../graphql/mutations/AppMutation');
|
||||
jest.mock('../../../../log');
|
||||
|
||||
describe(ProjectIconUnset, () => {
|
||||
it('removes the icon of the current project', async () => {
|
||||
const graphqlClient = {} as ExpoGraphqlClient;
|
||||
jest
|
||||
.mocked(AppMutation.removeProfileImageAsync)
|
||||
.mockResolvedValue({ id: 'project-123', fullName: '@test-account/test-project' });
|
||||
|
||||
const command = new ProjectIconUnset([], getMockOclifConfig());
|
||||
// @ts-expect-error getContextAsync is protected
|
||||
jest.spyOn(command, 'getContextAsync').mockResolvedValue({
|
||||
projectId: 'project-123',
|
||||
loggedIn: { graphqlClient },
|
||||
});
|
||||
await command.runAsync();
|
||||
|
||||
expect(AppMutation.removeProfileImageAsync).toHaveBeenCalledWith(graphqlClient, 'project-123');
|
||||
expect(jest.mocked(Log.withTick).mock.calls.flat().join()).toContain(
|
||||
'@test-account/test-project'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -9,20 +9,18 @@ import Log, { link } from '../../../log';
|
||||
import { ora } from '../../../ora';
|
||||
import {
|
||||
pollForProfileImageChangeAsync,
|
||||
resolveAppConfigIconAsync,
|
||||
uploadProjectIconAsync,
|
||||
validateIconAsync,
|
||||
} from '../../../project/projectIcon';
|
||||
|
||||
export default class ProjectIconSet extends EasCommand {
|
||||
static override description =
|
||||
'set the project icon displayed on the EAS dashboard (requires the Admin role)';
|
||||
static override description = 'set the project icon displayed on the EAS dashboard';
|
||||
|
||||
static override args = {
|
||||
path: Args.string({
|
||||
required: true,
|
||||
description:
|
||||
'Path to the icon image (PNG or JPEG, at most 10 MB). The image is resized to a 1024x1024 PNG, and a non-square image is center-cropped. Defaults to the icon in the app config.',
|
||||
ignoreStdin: true,
|
||||
'Path to the icon image (PNG or JPEG, at most 10 MB). Non-square images are center-cropped to a square.',
|
||||
}),
|
||||
};
|
||||
|
||||
@@ -32,24 +30,21 @@ export default class ProjectIconSet extends EasCommand {
|
||||
|
||||
static override contextDefinition = {
|
||||
...this.ContextOptions.ProjectId,
|
||||
...this.ContextOptions.ProjectDir,
|
||||
...this.ContextOptions.LoggedIn,
|
||||
};
|
||||
|
||||
async runAsync(): Promise<void> {
|
||||
const {
|
||||
args: { path: pathArgument },
|
||||
args: { path: imagePath },
|
||||
flags,
|
||||
} = await this.parse(ProjectIconSet);
|
||||
const {
|
||||
projectId,
|
||||
projectDir,
|
||||
loggedIn: { graphqlClient },
|
||||
} = await this.getContextAsync(ProjectIconSet, {
|
||||
nonInteractive: flags['non-interactive'],
|
||||
});
|
||||
|
||||
const imagePath = pathArgument ?? (await getAppConfigIconPathAsync(projectDir));
|
||||
await validateIconAsync(imagePath);
|
||||
|
||||
const app = await AppQuery.byIdAsync(graphqlClient, projectId);
|
||||
@@ -79,14 +74,3 @@ export default class ProjectIconSet extends EasCommand {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function getAppConfigIconPathAsync(projectDir: string): Promise<string> {
|
||||
const icon = await resolveAppConfigIconAsync(projectDir);
|
||||
if (!icon) {
|
||||
throw new Error(
|
||||
'No local icon found in the app config (icon, ios.icon, android.adaptiveIcon.foregroundImage or android.icon). Pass the path to an image instead.'
|
||||
);
|
||||
}
|
||||
Log.log(`Using "${icon.field}" from your app config: ${icon.path}`);
|
||||
return icon.path;
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
import chalk from 'chalk';
|
||||
|
||||
import EasCommand from '../../../commandUtils/EasCommand';
|
||||
import { EASNonInteractiveFlag } from '../../../commandUtils/flags';
|
||||
import { AppMutation } from '../../../graphql/mutations/AppMutation';
|
||||
import Log from '../../../log';
|
||||
|
||||
export default class ProjectIconUnset extends EasCommand {
|
||||
static override description =
|
||||
'remove the project icon displayed on the EAS dashboard (requires the Admin role)';
|
||||
|
||||
static override flags = {
|
||||
...EASNonInteractiveFlag,
|
||||
};
|
||||
|
||||
static override contextDefinition = {
|
||||
...this.ContextOptions.ProjectId,
|
||||
...this.ContextOptions.LoggedIn,
|
||||
};
|
||||
|
||||
async runAsync(): Promise<void> {
|
||||
const { flags } = await this.parse(ProjectIconUnset);
|
||||
const {
|
||||
projectId,
|
||||
loggedIn: { graphqlClient },
|
||||
} = await this.getContextAsync(ProjectIconUnset, {
|
||||
nonInteractive: flags['non-interactive'],
|
||||
});
|
||||
|
||||
const { fullName } = await AppMutation.removeProfileImageAsync(graphqlClient, projectId);
|
||||
Log.withTick(`${chalk.bold(fullName)} now has no icon`);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,38 @@
|
||||
import gql from 'graphql-tag';
|
||||
|
||||
import EasCommand from '../../commandUtils/EasCommand';
|
||||
import { AppQuery } from '../../graphql/queries/AppQuery';
|
||||
import { ExpoGraphqlClient } from '../../commandUtils/context/contextUtils/createGraphqlClient';
|
||||
import { withErrorHandlingAsync } from '../../graphql/client';
|
||||
import { AppInfoQuery, AppInfoQueryVariables } from '../../graphql/generated';
|
||||
import Log from '../../log';
|
||||
import formatFields from '../../utils/formatFields';
|
||||
|
||||
async function projectInfoByIdAsync(
|
||||
graphqlClient: ExpoGraphqlClient,
|
||||
appId: string
|
||||
): Promise<AppInfoQuery> {
|
||||
const data = await withErrorHandlingAsync(
|
||||
graphqlClient
|
||||
.query<AppInfoQuery, AppInfoQueryVariables>(
|
||||
gql`
|
||||
query AppInfo($appId: String!) {
|
||||
app {
|
||||
byId(appId: $appId) {
|
||||
id
|
||||
fullName
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
{ appId },
|
||||
{ additionalTypenames: ['App'] }
|
||||
)
|
||||
.toPromise()
|
||||
);
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
export default class ProjectInfo extends EasCommand {
|
||||
static override description = 'information about the current project';
|
||||
|
||||
@@ -19,18 +49,15 @@ export default class ProjectInfo extends EasCommand {
|
||||
nonInteractive: true,
|
||||
});
|
||||
|
||||
const [app, iconUrl] = await Promise.all([
|
||||
AppQuery.byIdAsync(graphqlClient, projectId),
|
||||
AppQuery.byIdProfileImageUrlAsync(graphqlClient, projectId),
|
||||
]);
|
||||
const { app } = await projectInfoByIdAsync(graphqlClient, projectId);
|
||||
if (!app) {
|
||||
throw new Error(`Could not find project with id: ${projectId}`);
|
||||
}
|
||||
|
||||
Log.addNewLineIfNone();
|
||||
Log.log(
|
||||
formatFields([
|
||||
{ label: 'fullName', value: app.fullName },
|
||||
{ label: 'name', value: app.name },
|
||||
{ label: 'slug', value: app.slug },
|
||||
{ label: 'icon', value: iconUrl ?? 'not set' },
|
||||
{ label: 'fullName', value: app.byId.fullName },
|
||||
{ label: 'ID', value: projectId },
|
||||
])
|
||||
);
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
import { getMockOclifConfig } from '../../../../__tests__/commands/utils';
|
||||
import { ExpoGraphqlClient } from '../../../../commandUtils/context/contextUtils/createGraphqlClient';
|
||||
import { AppMutation } from '../../../../graphql/mutations/AppMutation';
|
||||
import { getPrivateExpoConfigAsync } from '../../../../project/expoConfig';
|
||||
import ProjectNameSet from '../set';
|
||||
|
||||
jest.mock('../../../../graphql/mutations/AppMutation');
|
||||
jest.mock('../../../../log');
|
||||
jest.mock('../../../../project/expoConfig');
|
||||
|
||||
const graphqlClient = {} as ExpoGraphqlClient;
|
||||
const mockSetDisplayNameAsync = jest.mocked(AppMutation.setDisplayNameAsync);
|
||||
|
||||
async function runAsync(argv: string[]): Promise<void> {
|
||||
const command = new ProjectNameSet(argv, getMockOclifConfig());
|
||||
// @ts-expect-error getContextAsync is protected
|
||||
jest.spyOn(command, 'getContextAsync').mockResolvedValue({
|
||||
projectId: 'project-123',
|
||||
projectDir: '/app',
|
||||
loggedIn: { graphqlClient },
|
||||
});
|
||||
await command.runAsync();
|
||||
}
|
||||
|
||||
describe(ProjectNameSet, () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockSetDisplayNameAsync.mockResolvedValue({
|
||||
id: 'project-123',
|
||||
name: 'My App',
|
||||
fullName: '@test-account/my-app',
|
||||
});
|
||||
jest
|
||||
.mocked(getPrivateExpoConfigAsync)
|
||||
.mockResolvedValue({ name: 'Config Name', slug: 'my-app' } as any);
|
||||
});
|
||||
|
||||
it('sets the given display name, trimmed', async () => {
|
||||
await runAsync([' My App ']);
|
||||
|
||||
expect(mockSetDisplayNameAsync).toHaveBeenCalledWith(graphqlClient, {
|
||||
appId: 'project-123',
|
||||
displayName: 'My App',
|
||||
});
|
||||
});
|
||||
|
||||
it('uses the name from the app config when no name is given', async () => {
|
||||
await runAsync([]);
|
||||
|
||||
expect(mockSetDisplayNameAsync).toHaveBeenCalledWith(graphqlClient, {
|
||||
appId: 'project-123',
|
||||
displayName: 'Config Name',
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects a blank name', async () => {
|
||||
await expect(runAsync([' '])).rejects.toThrow('The display name cannot be blank.');
|
||||
expect(mockSetDisplayNameAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,55 +0,0 @@
|
||||
import { Args } from '@oclif/core';
|
||||
import chalk from 'chalk';
|
||||
|
||||
import EasCommand from '../../../commandUtils/EasCommand';
|
||||
import { EASNonInteractiveFlag } from '../../../commandUtils/flags';
|
||||
import { AppMutation } from '../../../graphql/mutations/AppMutation';
|
||||
import Log from '../../../log';
|
||||
import { getPrivateExpoConfigAsync } from '../../../project/expoConfig';
|
||||
|
||||
export default class ProjectNameSet extends EasCommand {
|
||||
static override description =
|
||||
'set the project display name shown on the EAS dashboard (does not change the slug)';
|
||||
|
||||
static override args = {
|
||||
name: Args.string({
|
||||
description: 'Display name, at most 255 characters. Defaults to the name in the app config.',
|
||||
ignoreStdin: true,
|
||||
}),
|
||||
};
|
||||
|
||||
static override flags = {
|
||||
...EASNonInteractiveFlag,
|
||||
};
|
||||
|
||||
static override contextDefinition = {
|
||||
...this.ContextOptions.ProjectId,
|
||||
...this.ContextOptions.ProjectDir,
|
||||
...this.ContextOptions.LoggedIn,
|
||||
};
|
||||
|
||||
async runAsync(): Promise<void> {
|
||||
const {
|
||||
args: { name: nameArgument },
|
||||
flags,
|
||||
} = await this.parse(ProjectNameSet);
|
||||
const {
|
||||
projectId,
|
||||
projectDir,
|
||||
loggedIn: { graphqlClient },
|
||||
} = await this.getContextAsync(ProjectNameSet, {
|
||||
nonInteractive: flags['non-interactive'],
|
||||
});
|
||||
|
||||
const displayName = (nameArgument ?? (await getPrivateExpoConfigAsync(projectDir)).name).trim();
|
||||
if (!displayName) {
|
||||
throw new Error('The display name cannot be blank.');
|
||||
}
|
||||
|
||||
const app = await AppMutation.setDisplayNameAsync(graphqlClient, {
|
||||
appId: projectId,
|
||||
displayName,
|
||||
});
|
||||
Log.withTick(`Set the display name of ${chalk.bold(app.fullName)} to ${chalk.bold(app.name)}`);
|
||||
}
|
||||
}
|
||||
@@ -133,7 +133,7 @@ export default class WorkflowView extends EasCommand {
|
||||
|
||||
result.logURL = getWorkflowRunUrl(
|
||||
result.workflow.app.ownerAccount.name,
|
||||
result.workflow.app.slug,
|
||||
result.workflow.app.name,
|
||||
result.id
|
||||
);
|
||||
|
||||
|
||||
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user