Compare commits

...
Author SHA1 Message Date
Jakub Tkacz 6e1e21967d refactor: extract makeMetricsKey 2026-02-25 15:21:54 +01:00
Jakub Tkacz 09c219bb49 improve description in fetchMetrics test 2026-02-25 14:54:04 +01:00
Jakub Tkacz 49a59f41f3 cover better null cases in formatMetrics tests 2026-02-25 14:51:08 +01:00
Jakub Tkacz 06f6179f8c add todos about multiple queries 2026-02-25 13:43:18 +01:00
Jakub Tkacz 80227eb070 improve and simplify the tests 2026-02-25 13:40:10 +01:00
Jakub Tkacz 0c77831d15 code format 2026-02-25 13:39:49 +01:00
Jakub Tkacz 8438fca136 refactor: move validateDateFlag to utils 2026-02-25 13:33:20 +01:00
Jakub Tkacz 1a6dfd5d04 adds comment to resolveStatKey 2026-02-25 13:19:00 +01:00
Jakub Tkacz 33654bfdb9 refactor: rename DEFAULT_STATS_TABLE to TABLE_FORMAT_DEFAULT_STATS 2026-02-25 13:17:37 +01:00
Jakub Tkacz 30dfeb0f9e refactor: revert pagination to version from main 2026-02-25 13:16:36 +01:00
Jakub Tkacz e361856877 [eas-cli] Add observe:metrics command 2026-02-25 10:34:47 +01:00
Douglas Lowder 0c32aa3a39 [release] Work around the removal of yarn --silent (#3424)
# Why

When yarn moved to version 4, they removed the `--silent` flag. Because of this change, any use of yarn to call scripts and get output will also get yarn debugging garbage, and there is no way to suppress it.

The release scripts are mostly ok with this, except for calling the `next-version` script. The output of this script has to be clean for it to be used as input for `lerna version`.

# How

Replaced the yarn call with a direct invocation of the node Typescript source, bypassing yarn.

# Test Plan

Since the `trigger-release.yml` workflow supports a dry run mode, it's safe to modify it to check out a test branch and run the workflow many times to debug the issue.

Once this change is merged, a dry run invocation of the workflow should succeed even if no version string is passed in.
2026-02-24 03:37:51 -08:00
Tomek Czajecki 59ac8ae77a [eas-cli] Add go command (#3376) 2026-02-23 15:23:22 -08:00
Douglas Lowder 3e13df470e [eas-cli] Require --environment flag for eas update when SDK >= 55 (#3418)
# Why

Problems can occur if an update intended for a development build is published with the environment defaulting to or set to production, and vice versa.

To prevent such problems in the future, this PR makes the `--environment` flag a required flag for projects using SDK 55 and greater.

# How

Add a new utility function to throw an error if sdkVersion does not meet the requirement, and use that function in `eas update:configure` and `eas update`.

Skip the check if EAS_BUILD env is set.

# Test Plan

Unit tests added.

Testing locally with different projects.
2026-02-23 13:48:35 -08:00
Expo CI 83877f6285 update CHANGELOG.md 2026-02-23 20:47:53 +00:00
30 changed files with 2042 additions and 20 deletions

No files matched your search

+10 -2
View File
@@ -6,14 +6,22 @@ This is the log of notable changes to EAS CLI and related packages.
### 🛠 Breaking changes
- Require --environment flag for update commands when SDK >= 55. ([#3398](https://github.com/expo/eas-cli/pull/3398) by [@douglowder](https://github.com/douglowder))
### 🎉 New features
- Add `eas observe:metrics` command for monitoring app performance metrics. ([#3401](https://github.com/expo/eas-cli/pull/3401) by [@ubax](https://github.com/ubax))
### 🐛 Bug fixes
### 🧹 Chores
## [18.0.4](https://github.com/expo/eas-cli/releases/tag/v18.0.4) - 2026-02-23
### 🐛 Bug fixes
- Revert authorization code flow with PKCE for browser-based login. ([#3422](https://github.com/expo/eas-cli/pull/3422) by [@byronkarlen](https://github.com/byronkarlen))
### 🧹 Chores
## [18.0.3](https://github.com/expo/eas-cli/releases/tag/v18.0.3) - 2026-02-20
### 🎉 New features
+3
View File
@@ -203,6 +203,9 @@
"metadata": {
"description": "manage store configuration"
},
"observe": {
"description": "monitor app performance metrics"
},
"project": {
"description": "manage project"
},
+1 -1
View File
@@ -67,7 +67,7 @@ export const EasJsonOnlyFlag = {
export const EasUpdateEnvironmentFlag = {
environment: Flags.string({
description:
'Environment to use for the server-side defined EAS environment variables during command execution, e.g. "production", "preview", "development"',
'Environment to use for the server-side defined EAS environment variables during command execution, e.g. "production", "preview", "development". Required for projects using Expo SDK 55 or greater.',
required: false,
default: undefined,
}),
+610
View File
@@ -0,0 +1,610 @@
import { App, User, UserRole } from '@expo/apple-utils';
import spawnAsync from '@expo/spawn-async';
import { Flags } from '@oclif/core';
import chalk from 'chalk';
import * as fs from 'fs-extra';
import * as os from 'os';
import * as path from 'path';
import { Analytics } from '../analytics/AnalyticsManager';
import EasCommand from '../commandUtils/EasCommand';
import { ExpoGraphqlClient } from '../commandUtils/context/contextUtils/createGraphqlClient';
import { saveProjectIdToAppConfigAsync } from '../commandUtils/context/contextUtils/getProjectIdAsync';
import { CredentialsContext } from '../credentials/context';
import { AppStoreApiKeyPurpose } from '../credentials/ios/actions/AscApiKeyUtils';
import { getAppFromContextAsync } from '../credentials/ios/actions/BuildCredentialsUtils';
import { SetUpAscApiKey } from '../credentials/ios/actions/SetUpAscApiKey';
import { SetUpBuildCredentials } from '../credentials/ios/actions/SetUpBuildCredentials';
import { SetUpPushKey } from '../credentials/ios/actions/SetUpPushKey';
import { ensureAppExistsAsync } from '../credentials/ios/appstore/ensureAppExists';
import { Target } from '../credentials/ios/types';
import {
WorkflowJobStatus,
WorkflowProjectSourceType,
WorkflowRunStatus,
} from '../graphql/generated';
import { AppMutation } from '../graphql/mutations/AppMutation';
import { WorkflowRunMutation } from '../graphql/mutations/WorkflowRunMutation';
import { AppQuery } from '../graphql/queries/AppQuery';
import { WorkflowRunQuery } from '../graphql/queries/WorkflowRunQuery';
import Log, { learnMore } from '../log';
import { confirmAsync } from '../prompts';
import { ora } from '../ora';
import { getPrivateExpoConfigAsync } from '../project/expoConfig';
import { findProjectIdByAccountNameAndSlugNullableAsync } from '../project/fetchOrCreateProjectIDForWriteToConfigWithConfirmationAsync';
import { uploadAccountScopedFileAsync } from '../project/uploadAccountScopedFileAsync';
import { uploadAccountScopedProjectSourceAsync } from '../project/uploadAccountScopedProjectSourceAsync';
import { Actor, getActorDisplayName } from '../user/User';
import { sleepAsync } from '../utils/promise';
import { resolveVcsClient } from '../vcs';
import { Client as VcsClient } from '../vcs/vcs';
// Expo Go release info - update when releasing a new version
const EXPO_GO_SDK_VERSION = '55';
const EXPO_GO_APP_VERSION = '55.0.11';
const EXPO_GO_BUILD_NUMBER = '1017799';
const TESTFLIGHT_GROUP_NAME = 'Team (Expo)';
async function setupTestFlightAsync(ascApp: App): Promise<void> {
// Create or get TestFlight group
let group;
for (let attempt = 0; attempt < 10; attempt++) {
try {
const groups = await ascApp.getBetaGroupsAsync({
query: { includes: ['betaTesters'] },
});
group = groups.find(
g => g.attributes.isInternalGroup && g.attributes.name === TESTFLIGHT_GROUP_NAME
);
if (!group) {
group = await ascApp.createBetaGroupAsync({
name: TESTFLIGHT_GROUP_NAME,
isInternalGroup: true,
hasAccessToAllBuilds: true,
});
}
break;
} catch (error: any) {
// Apple returns this error when the app isn't ready yet
if (error?.data?.errors?.some((e: any) => e.code === 'ENTITY_ERROR.RELATIONSHIP.INVALID')) {
if (attempt < 9) {
await new Promise(resolve => setTimeout(resolve, 10000));
continue;
}
}
throw error;
}
}
if (!group) {
throw new Error('Failed to create TestFlight group');
}
const users = await User.getAsync(ascApp.context);
const admins = users.filter(u => u.attributes.roles?.includes(UserRole.ADMIN));
const existingEmails = new Set(
group.attributes.betaTesters?.map((t: any) => t.attributes.email?.toLowerCase()) ?? []
);
const newTesters = admins
.filter(u => u.attributes.email && !existingEmails.has(u.attributes.email.toLowerCase()))
.map(u => ({
email: u.attributes.email!,
firstName: u.attributes.firstName ?? '',
lastName: u.attributes.lastName ?? '',
}));
if (newTesters.length > 0) {
await group.createBulkBetaTesterAssignmentsAsync(newTesters);
}
}
/* eslint-disable no-console */
async function withSuppressedOutputAsync<T>(fn: () => Promise<T>): Promise<T> {
const originalStdoutWrite = process.stdout.write.bind(process.stdout);
const originalConsoleLog = console.log;
const originalConsoleError = console.error;
const originalConsoleWarn = console.warn;
let capturedOutput = '';
const capture = (chunk: any): boolean => {
if (typeof chunk === 'string') {
capturedOutput += chunk;
}
return true;
};
// Only suppress stdout, not stderr — ora writes spinner frames to stderr and
// patching it would freeze the spinner animation during suppressed async work.
process.stdout.write = capture as any;
console.log = () => {};
console.error = () => {};
console.warn = () => {};
try {
return await fn();
} catch (error) {
process.stdout.write = originalStdoutWrite;
console.log = originalConsoleLog;
console.error = originalConsoleError;
console.warn = originalConsoleWarn;
if (capturedOutput) {
originalConsoleLog(capturedOutput);
}
throw error;
} finally {
process.stdout.write = originalStdoutWrite;
console.log = originalConsoleLog;
console.error = originalConsoleError;
console.warn = originalConsoleWarn;
}
}
/* eslint-enable no-console */
export default class Go extends EasCommand {
static override description = 'Create a custom Expo Go and submit to TestFlight';
static override hidden = true;
static override flags = {
'bundle-id': Flags.string({
description: 'iOS bundle identifier (auto-generated if not provided)',
required: false,
}),
name: Flags.string({
description: 'App name',
default: 'My Expo Go',
}),
credentials: Flags.boolean({
description: 'Interactively select credentials (default: auto-select)',
default: false,
}),
};
static override contextDefinition = {
...this.ContextOptions.LoggedIn,
...this.ContextOptions.Analytics,
};
async runAsync(): Promise<void> {
Log.log(
chalk.bold(
`Creating your personal Expo Go and deploying to TestFlight. ${learnMore('https://expo.fyi/personal-expo-go')}`
)
);
const { flags } = await this.parse(Go);
const spinner = ora('Logging in to Expo...').start();
const {
loggedIn: { actor, graphqlClient },
analytics,
} = await this.getContextAsync(Go, {
nonInteractive: false,
});
spinner.succeed(`Logged in as ${chalk.cyan(getActorDisplayName(actor))}`);
const bundleId = flags['bundle-id'] ?? this.generateBundleId(actor);
const appName = flags.name ?? 'My Expo Go';
const slug = bundleId.split('.').pop() || 'my-expo-go';
const projectDir = path.join(os.tmpdir(), `eas-go-${slug}`);
await fs.emptyDir(projectDir);
const originalCwd = process.cwd();
process.chdir(projectDir);
const setupSpinner = ora('Creating project...').start();
// Step 1: Create project files and initialize git (silently)
try {
await withSuppressedOutputAsync(async () => {
await this.createProjectFilesAsync(projectDir, bundleId, appName);
await this.initGitRepoAsync(projectDir);
});
const vcsClient = resolveVcsClient();
// Step 2: Create/link EAS project (silently)
const projectId = await withSuppressedOutputAsync(() =>
this.ensureEasProjectAsync(graphqlClient, actor, projectDir, bundleId)
);
// Step 3: Set up iOS credentials and create App Store Connect app
const ascApp = await this.setupCredentialsAsync(
projectDir,
projectId,
bundleId,
appName,
graphqlClient,
actor,
analytics,
vcsClient,
flags.credentials,
() => {
setupSpinner.stop();
Log.markFreshLine();
}
);
// Step 4: Start workflow and monitor progress
const { workflowUrl, workflowRunId } = await this.runWorkflowAsync(
graphqlClient,
projectDir,
projectId,
actor,
vcsClient
);
Log.withTick(`Workflow started: ${chalk.cyan(workflowUrl)}`);
const status = await this.monitorWorkflowJobsAsync(graphqlClient, workflowRunId);
if (status === WorkflowRunStatus.Failure) {
throw new Error('Workflow failed');
} else if (status === WorkflowRunStatus.Canceled) {
throw new Error('Workflow was canceled');
}
// Step 5: Set up TestFlight group (silently)
try {
await setupTestFlightAsync(ascApp);
} catch {
// Non-fatal: TestFlight group setup failure shouldn't block the user
}
Log.newLine();
Log.succeed(
`Done! Your custom Expo Go has been submitted to TestFlight. ${learnMore(
`https://appstoreconnect.apple.com/apps/${ascApp.id}/testflight`,
{ learnMoreMessage: 'Open it on App Store Connect' }
)}`
);
Log.log(
`App Store processing may take several minutes to complete. ${learnMore(
'https://expo.fyi/personal-expo-go',
{ learnMoreMessage: 'Learn more about Expo Go on TestFlight' }
)}`
);
await fs.remove(projectDir);
} catch (error) {
Log.gray(`Project files preserved for debugging: ${projectDir}`);
throw error;
} finally {
process.chdir(originalCwd);
}
}
private generateBundleId(actor: Actor): string {
const username = actor.accounts[0].name;
// Sanitize username for bundle ID: only alphanumeric and hyphens allowed
const sanitizedUsername = username
.toLowerCase()
.replace(/[^a-z0-9-]/g, '')
.replace(/^-+|-+$/g, ''); // trim leading/trailing hyphens
// Deterministic bundle ID per user + SDK version (reuses same ASC app)
return `com.${sanitizedUsername || 'app'}.expogo${EXPO_GO_SDK_VERSION}`;
}
private async createProjectFilesAsync(
projectDir: string,
bundleId: string,
appName: string
): Promise<void> {
const slug = bundleId.split('.').pop() || 'custom-expo-go';
const extensionBundleId = `${bundleId}.ExpoNotificationServiceExtension`;
const appJson = {
expo: {
name: appName,
slug,
version: EXPO_GO_APP_VERSION,
ios: {
bundleIdentifier: bundleId,
buildNumber: EXPO_GO_BUILD_NUMBER,
config: {
usesNonExemptEncryption: false,
},
},
extra: {
eas: {
build: {
experimental: {
ios: {
appExtensions: [
{
targetName: 'ExpoNotificationServiceExtension',
bundleIdentifier: extensionBundleId,
},
],
},
},
},
},
},
},
};
const easJson = {
cli: {
version: '>= 5.0.0',
},
build: {
production: {
distribution: 'store',
credentialsSource: 'remote',
},
},
submit: {
production: {
ios: {},
},
},
};
const packageJson = {
name: slug,
version: '1.0.0',
dependencies: {
expo: '~54.0.0',
},
};
await fs.writeJson(path.join(projectDir, 'app.json'), appJson, { spaces: 2 });
await fs.writeJson(path.join(projectDir, 'eas.json'), easJson, { spaces: 2 });
await fs.writeJson(path.join(projectDir, 'package.json'), packageJson, { spaces: 2 });
await spawnAsync('npm', ['install'], { cwd: projectDir });
}
private async initGitRepoAsync(projectDir: string): Promise<void> {
await spawnAsync('git', ['init'], { cwd: projectDir });
await spawnAsync('git', ['add', '.'], { cwd: projectDir });
await spawnAsync('git', ['commit', '-m', 'Initial commit'], { cwd: projectDir });
}
private async ensureEasProjectAsync(
graphqlClient: ExpoGraphqlClient,
actor: Actor,
projectDir: string,
bundleId: string
): Promise<string> {
const slug = bundleId.split('.').pop() || 'custom-expo-go';
const account = actor.accounts[0];
const existingProjectId = await findProjectIdByAccountNameAndSlugNullableAsync(
graphqlClient,
account.name,
slug
);
if (existingProjectId) {
await saveProjectIdToAppConfigAsync(projectDir, existingProjectId);
return existingProjectId;
}
const projectId = await AppMutation.createAppAsync(graphqlClient, {
accountId: account.id,
projectName: slug,
});
await saveProjectIdToAppConfigAsync(projectDir, projectId);
return projectId;
}
private async setupCredentialsAsync(
projectDir: string,
projectId: string,
bundleId: string,
appName: string,
graphqlClient: ExpoGraphqlClient,
actor: Actor,
analytics: Analytics,
vcsClient: VcsClient,
customizeCreds: boolean,
onBeforeAppleAuth?: () => void
): Promise<App> {
const exp = await getPrivateExpoConfigAsync(projectDir);
const extensionBundleId = `${bundleId}.ExpoNotificationServiceExtension`;
const credentialsCtx = new CredentialsContext({
projectInfo: { exp, projectId },
nonInteractive: false,
autoAcceptCredentialReuse: !customizeCreds,
projectDir,
user: actor,
graphqlClient,
analytics,
vcsClient,
});
onBeforeAppleAuth?.();
const userAuthCtx = await credentialsCtx.appStore.ensureUserAuthenticatedAsync();
const app = await getAppFromContextAsync(credentialsCtx);
const targets: Target[] = [
{
targetName: exp.slug,
bundleIdentifier: bundleId,
entitlements: {},
},
{
targetName: 'ExpoNotificationServiceExtension',
bundleIdentifier: extensionBundleId,
parentBundleIdentifier: bundleId,
entitlements: {},
},
];
const ascApp = await withSuppressedOutputAsync(async () => {
await new SetUpBuildCredentials({
app,
targets,
distribution: 'store',
}).runAsync(credentialsCtx);
const appLookupParams = {
...app,
bundleIdentifier: bundleId,
};
await new SetUpAscApiKey(appLookupParams, AppStoreApiKeyPurpose.SUBMISSION_SERVICE).runAsync(
credentialsCtx
);
const ascAppResult = await ensureAppExistsAsync(userAuthCtx, {
name: appName,
bundleIdentifier: bundleId,
});
const easJsonPath = path.join(projectDir, 'eas.json');
const easJson = await fs.readJson(easJsonPath);
easJson.submit = easJson.submit || {};
easJson.submit.production = easJson.submit.production || {};
easJson.submit.production.ios = easJson.submit.production.ios || {};
easJson.submit.production.ios.ascAppId = ascAppResult.id;
await fs.writeJson(easJsonPath, easJson, { spaces: 2 });
await spawnAsync('git', ['add', 'eas.json'], { cwd: projectDir });
await spawnAsync('git', ['commit', '-m', 'Add ascAppId to eas.json'], { cwd: projectDir });
return ascAppResult;
});
// Set up push notifications (outside suppressed block so prompts are visible)
const appLookupParamsForPushKey = { ...app, bundleIdentifier: bundleId };
const setupPushKeyAction = new SetUpPushKey(appLookupParamsForPushKey);
const isPushKeySetup = await setupPushKeyAction.isPushKeySetupAsync(credentialsCtx);
if (!isPushKeySetup) {
if (customizeCreds) {
const wantsPushNotifications = await confirmAsync({
message: 'Would you like to set up Push Notifications for your app?',
initial: true,
});
if (wantsPushNotifications) {
await setupPushKeyAction.runAsync(credentialsCtx);
}
} else {
await setupPushKeyAction.runAsync(credentialsCtx);
}
}
return ascApp;
}
private async runWorkflowAsync(
graphqlClient: ExpoGraphqlClient,
projectDir: string,
projectId: string,
actor: Actor,
vcsClient: VcsClient
): Promise<{ workflowUrl: string; workflowRunId: string }> {
const account = actor.accounts[0];
const { projectArchiveBucketKey, easJsonBucketKey, packageJsonBucketKey } =
await withSuppressedOutputAsync(async () => {
const { projectArchiveBucketKey } = await uploadAccountScopedProjectSourceAsync({
graphqlClient,
vcsClient,
accountId: account.id,
});
const { fileBucketKey: easJsonBucketKey } = await uploadAccountScopedFileAsync({
graphqlClient,
accountId: account.id,
filePath: path.join(projectDir, 'eas.json'),
maxSizeBytes: 1024 * 1024,
});
const { fileBucketKey: packageJsonBucketKey } = await uploadAccountScopedFileAsync({
graphqlClient,
accountId: account.id,
filePath: path.join(projectDir, 'package.json'),
maxSizeBytes: 1024 * 1024,
});
return { projectArchiveBucketKey, easJsonBucketKey, packageJsonBucketKey };
});
const { id: workflowRunId } = await WorkflowRunMutation.createExpoGoRepackWorkflowRunAsync(
graphqlClient,
{
appId: projectId,
projectSource: {
type: WorkflowProjectSourceType.Gcs,
projectArchiveBucketKey,
easJsonBucketKey,
packageJsonBucketKey,
projectRootDirectory: '.',
},
}
);
const app = await AppQuery.byIdAsync(graphqlClient, projectId);
const workflowUrl = `https://expo.dev/accounts/${account.name}/projects/${app.slug}/workflows/${workflowRunId}`;
return { workflowUrl, workflowRunId };
}
private async monitorWorkflowJobsAsync(
graphqlClient: ExpoGraphqlClient,
workflowRunId: string
): Promise<WorkflowRunStatus> {
const buildSpinner = ora('Building Expo Go').start();
let submitSpinner: ReturnType<typeof ora> | null = null;
let buildCompleted = false;
let failedFetchesCount = 0;
while (true) {
try {
const workflowRun = await WorkflowRunQuery.withJobsByIdAsync(graphqlClient, workflowRunId, {
useCache: false,
});
failedFetchesCount = 0;
const repackJob = workflowRun.jobs.find(j => j.name === 'Repack Expo Go');
const submitJob = workflowRun.jobs.find(j => j.name === 'Submit to TestFlight');
if (!buildCompleted) {
if (repackJob?.status === WorkflowJobStatus.Success) {
buildSpinner.succeed('Built Expo Go');
buildCompleted = true;
} else if (
repackJob?.status === WorkflowJobStatus.Failure ||
repackJob?.status === WorkflowJobStatus.Canceled
) {
buildSpinner.fail('Build failed');
return WorkflowRunStatus.Failure;
}
}
if (buildCompleted && submitSpinner === null && submitJob) {
submitSpinner = ora('Submitting to TestFlight').start();
}
if (workflowRun.status === WorkflowRunStatus.Success) {
submitSpinner?.stop();
return WorkflowRunStatus.Success;
} else if (workflowRun.status === WorkflowRunStatus.Failure) {
buildSpinner.stop();
submitSpinner?.fail('Submission failed');
return WorkflowRunStatus.Failure;
} else if (workflowRun.status === WorkflowRunStatus.Canceled) {
buildSpinner.stop();
submitSpinner?.stop();
return WorkflowRunStatus.Canceled;
}
} catch {
failedFetchesCount++;
if (failedFetchesCount > 6) {
buildSpinner.fail();
submitSpinner?.fail();
throw new Error('Failed to fetch the workflow run status 6 times in a row');
}
}
await sleepAsync(10 * 1000);
}
}
}
@@ -0,0 +1,189 @@
import { Config } from '@oclif/core';
import { ExpoGraphqlClient } from '../../../commandUtils/context/contextUtils/createGraphqlClient';
import { AppPlatform } from '../../../graphql/generated';
import { fetchObserveMetricsAsync } from '../../../observe/fetchMetrics';
import { buildObserveMetricsJson, buildObserveMetricsTable } from '../../../observe/formatMetrics';
import { enableJsonOutput, printJsonOnlyOutput } from '../../../utils/json';
import ObserveMetrics from '../metrics';
jest.mock('../../../observe/fetchMetrics', () => ({
fetchObserveMetricsAsync: jest.fn(),
}));
jest.mock('../../../observe/formatMetrics', () => ({
...jest.requireActual('../../../observe/formatMetrics'),
buildObserveMetricsTable: jest.fn().mockReturnValue('table'),
buildObserveMetricsJson: jest.fn().mockReturnValue([]),
}));
jest.mock('../../../log');
jest.mock('../../../utils/json');
const mockFetchObserveMetricsAsync = jest.mocked(fetchObserveMetricsAsync);
const mockBuildObserveMetricsTable = jest.mocked(buildObserveMetricsTable);
const mockBuildObserveMetricsJson = jest.mocked(buildObserveMetricsJson);
const mockEnableJsonOutput = jest.mocked(enableJsonOutput);
const mockPrintJsonOnlyOutput = jest.mocked(printJsonOnlyOutput);
describe(ObserveMetrics, () => {
const graphqlClient = {} as any as ExpoGraphqlClient;
const mockConfig = {} as unknown as Config;
const projectId = 'test-project-id';
beforeEach(() => {
jest.clearAllMocks();
mockFetchObserveMetricsAsync.mockResolvedValue(new Map());
});
function createCommand(argv: string[]): ObserveMetrics {
const command = new ObserveMetrics(argv, mockConfig);
// @ts-expect-error getContextAsync is a protected method
jest.spyOn(command, 'getContextAsync').mockReturnValue({
projectId,
loggedIn: { graphqlClient },
});
return command;
}
it('fetches metrics with default parameters (both platforms)', async () => {
const now = new Date('2025-06-15T12:00:00.000Z');
jest.useFakeTimers({ now });
const command = createCommand([]);
await command.runAsync();
expect(mockFetchObserveMetricsAsync).toHaveBeenCalledTimes(1);
const platforms = mockFetchObserveMetricsAsync.mock.calls[0][3];
expect(platforms).toEqual([AppPlatform.Android, AppPlatform.Ios]);
jest.useRealTimers();
});
it('queries only Android when --platform android is passed', async () => {
const command = createCommand(['--platform', 'android']);
await command.runAsync();
const platforms = mockFetchObserveMetricsAsync.mock.calls[0][3];
expect(platforms).toEqual([AppPlatform.Android]);
});
it('queries only iOS when --platform ios is passed', async () => {
const command = createCommand(['--platform', 'ios']);
await command.runAsync();
const platforms = mockFetchObserveMetricsAsync.mock.calls[0][3];
expect(platforms).toEqual([AppPlatform.Ios]);
});
it('resolves --metric aliases before passing to fetchObserveMetricsAsync', async () => {
const command = createCommand(['--metric', 'tti', '--metric', 'cold_launch']);
await command.runAsync();
const metricNames = mockFetchObserveMetricsAsync.mock.calls[0][2];
expect(metricNames).toEqual(['expo.app_startup.tti', 'expo.app_startup.cold_launch_time']);
});
it('uses default time range (60 days back) when no --start/--end flags', async () => {
const now = new Date('2025-06-15T12:00:00.000Z');
jest.useFakeTimers({ now });
const command = createCommand([]);
await command.runAsync();
const startTime = mockFetchObserveMetricsAsync.mock.calls[0][4];
const endTime = mockFetchObserveMetricsAsync.mock.calls[0][5];
expect(endTime).toBe('2025-06-15T12:00:00.000Z');
expect(startTime).toBe('2025-04-16T12:00:00.000Z');
jest.useRealTimers();
});
it('uses explicit --start and --end when provided', async () => {
const command = createCommand([
'--start',
'2025-01-01T00:00:00.000Z',
'--end',
'2025-02-01T00:00:00.000Z',
]);
await command.runAsync();
const startTime = mockFetchObserveMetricsAsync.mock.calls[0][4];
const endTime = mockFetchObserveMetricsAsync.mock.calls[0][5];
expect(startTime).toBe('2025-01-01T00:00:00.000Z');
expect(endTime).toBe('2025-02-01T00:00:00.000Z');
});
it('passes resolved --stat flags to buildObserveMetricsTable', async () => {
const command = createCommand(['--stat', 'p90', '--stat', 'count']);
await command.runAsync();
expect(mockBuildObserveMetricsTable).toHaveBeenCalledWith(expect.any(Map), expect.any(Array), [
'p90',
'eventCount',
]);
});
it('deduplicates --stat flags that resolve to the same key', async () => {
const command = createCommand(['--stat', 'med', '--stat', 'median']);
await command.runAsync();
expect(mockBuildObserveMetricsTable).toHaveBeenCalledWith(expect.any(Map), expect.any(Array), [
'median',
]);
});
it('uses --days-from-now to compute start/end time range', async () => {
const now = new Date('2025-06-15T12:00:00.000Z');
jest.useFakeTimers({ now });
const command = createCommand(['--days-from-now', '7']);
await command.runAsync();
const startTime = mockFetchObserveMetricsAsync.mock.calls[0][4];
const endTime = mockFetchObserveMetricsAsync.mock.calls[0][5];
expect(endTime).toBe('2025-06-15T12:00:00.000Z');
expect(startTime).toBe('2025-06-08T12:00:00.000Z');
jest.useRealTimers();
});
it('rejects --days-from-now combined with --start', async () => {
const command = createCommand(['--days-from-now', '7', '--start', '2025-01-01T00:00:00.000Z']);
await expect(command.runAsync()).rejects.toThrow();
});
it('rejects --days-from-now combined with --end', async () => {
const command = createCommand(['--days-from-now', '7', '--end', '2025-02-01T00:00:00.000Z']);
await expect(command.runAsync()).rejects.toThrow();
});
it('uses default stats when --stat is not provided', async () => {
const command = createCommand([]);
await command.runAsync();
expect(mockBuildObserveMetricsTable).toHaveBeenCalledWith(expect.any(Map), expect.any(Array), [
'median',
'eventCount',
]);
});
it('passes resolved --stat flags to buildObserveMetricsJson when --json is used', async () => {
const command = createCommand([
'--json',
'--non-interactive',
'--stat',
'min',
'--stat',
'avg',
]);
await command.runAsync();
expect(mockEnableJsonOutput).toHaveBeenCalled();
expect(mockBuildObserveMetricsJson).toHaveBeenCalledWith(expect.any(Map), expect.any(Array), [
'min',
'average',
]);
expect(mockPrintJsonOnlyOutput).toHaveBeenCalled();
});
});
@@ -0,0 +1,143 @@
import { Flags } from '@oclif/core';
import EasCommand from '../../commandUtils/EasCommand';
import { EasNonInteractiveAndJsonFlags } from '../../commandUtils/flags';
import { AppPlatform } from '../../graphql/generated';
import Log from '../../log';
import { fetchObserveMetricsAsync } from '../../observe/fetchMetrics';
import {
StatisticKey,
buildObserveMetricsJson,
buildObserveMetricsTable,
resolveStatKey,
} from '../../observe/formatMetrics';
import { validateDateFlag } from '../../observe/utils';
import { resolveMetricName } from '../../observe/metricNames';
import { enableJsonOutput, printJsonOnlyOutput } from '../../utils/json';
const DEFAULT_METRICS = [
'expo.app_startup.cold_launch_time',
'expo.app_startup.warm_launch_time',
'expo.app_startup.tti',
'expo.app_startup.ttr',
'expo.app_startup.bundle_load_time',
];
const DEFAULT_DAYS_BACK = 60;
const TABLE_FORMAT_DEFAULT_STATS: StatisticKey[] = ['median', 'eventCount'];
const JSON_FORMAT_DEFAULT_STATS: StatisticKey[] = [
'min',
'median',
'max',
'average',
'p80',
'p90',
'p99',
'eventCount',
];
export default class ObserveMetrics extends EasCommand {
static override description = 'display app performance metrics grouped by app version';
static override flags = {
platform: Flags.enum<'android' | 'ios'>({
description: 'Filter by platform',
options: ['android', 'ios'],
}),
metric: Flags.string({
description:
'Metric name to display (can be specified multiple times). Supports aliases: tti, ttr, cold_launch, warm_launch, bundle_load',
multiple: true,
}),
stat: Flags.string({
description:
'Statistic to display per metric (can be specified multiple times). Options: min, max, med, avg, p80, p90, p99, count',
multiple: true,
}),
start: Flags.string({
description: 'Start of time range for metrics data (ISO date).',
exclusive: ['days-from-now'],
}),
end: Flags.string({
description: 'End of time range for metrics data (ISO date).',
exclusive: ['days-from-now'],
}),
'days-from-now': Flags.integer({
description: 'Show metrics from the last N days (mutually exclusive with --start/--end)',
min: 1,
exclusive: ['start', 'end'],
}),
...EasNonInteractiveAndJsonFlags,
};
static override contextDefinition = {
...this.ContextOptions.ProjectId,
...this.ContextOptions.LoggedIn,
};
async runAsync(): Promise<void> {
const { flags } = await this.parse(ObserveMetrics);
const {
projectId,
loggedIn: { graphqlClient },
} = await this.getContextAsync(ObserveMetrics, {
nonInteractive: flags['non-interactive'],
});
if (flags.json) {
enableJsonOutput();
} else {
Log.warn('EAS Observe is in preview and subject to breaking changes.');
}
if (flags.start) {
validateDateFlag(flags.start, '--start');
}
if (flags.end) {
validateDateFlag(flags.end, '--end');
}
const metricNames = flags.metric?.length
? flags.metric.map(resolveMetricName)
: DEFAULT_METRICS;
let startTime: string;
let endTime: string;
if (flags['days-from-now']) {
endTime = new Date().toISOString();
startTime = new Date(Date.now() - flags['days-from-now'] * 24 * 60 * 60 * 1000).toISOString();
} else {
endTime = flags.end ?? new Date().toISOString();
startTime =
flags.start ?? new Date(Date.now() - DEFAULT_DAYS_BACK * 24 * 60 * 60 * 1000).toISOString();
}
const platforms: AppPlatform[] = flags.platform
? [flags.platform === 'android' ? AppPlatform.Android : AppPlatform.Ios]
: [AppPlatform.Android, AppPlatform.Ios];
const metricsMap = await fetchObserveMetricsAsync(
graphqlClient,
projectId,
metricNames,
platforms,
startTime,
endTime
);
const argumentsStat = flags.stat?.length
? Array.from(new Set(flags.stat.map(resolveStatKey)))
: undefined;
if (flags.json) {
const stats: StatisticKey[] = argumentsStat ?? JSON_FORMAT_DEFAULT_STATS;
printJsonOnlyOutput(buildObserveMetricsJson(metricsMap, metricNames, stats));
} else {
const stats: StatisticKey[] = argumentsStat ?? TABLE_FORMAT_DEFAULT_STATS;
Log.addNewLineIfNone();
Log.log(buildObserveMetricsTable(metricsMap, metricNames, stats));
}
}
}
@@ -143,6 +143,67 @@ describe(UpdatePublish.name, () => {
expect(PublishMutation.publishUpdateGroupAsync).toHaveBeenCalled();
});
it('errors when SDK >= 55 and --environment is not provided', async () => {
const flags = ['--non-interactive', '--branch=branch123', '--message=abc'];
mockTestProject({ expoConfig: { sdkVersion: '55.0.0' } });
await expect(new UpdatePublish(flags, commandOptions).run()).rejects.toThrow(
'--environment flag is required for projects using Expo SDK 55 or greater'
);
});
it('does not error when SDK >= 55 and --environment is provided', async () => {
const flags = [
'--non-interactive',
'--branch=branch123',
'--message=abc',
'--environment=production',
];
mockTestProject({ expoConfig: { sdkVersion: '55.0.0' } });
const { platforms, runtimeVersion } = mockTestExport();
jest.mocked(ensureBranchExistsAsync).mockResolvedValue({
branch: {
id: 'branch123',
name: 'wat',
},
createdBranch: false,
});
jest
.mocked(PublishMutation.publishUpdateGroupAsync)
.mockResolvedValue(platforms.map(platform => ({ ...updateStub, platform, runtimeVersion })));
await new UpdatePublish(flags, commandOptions).run();
expect(PublishMutation.publishUpdateGroupAsync).toHaveBeenCalled();
});
it('does not error when SDK < 55 and --environment is not provided', async () => {
const flags = ['--non-interactive', '--branch=branch123', '--message=abc'];
mockTestProject({ expoConfig: { sdkVersion: '54.0.0' } });
const { platforms, runtimeVersion } = mockTestExport();
jest.mocked(ensureBranchExistsAsync).mockResolvedValue({
branch: {
id: 'branch123',
name: 'wat',
},
createdBranch: false,
});
jest
.mocked(PublishMutation.publishUpdateGroupAsync)
.mockResolvedValue(platforms.map(platform => ({ ...updateStub, platform, runtimeVersion })));
await new UpdatePublish(flags, commandOptions).run();
expect(PublishMutation.publishUpdateGroupAsync).toHaveBeenCalled();
});
it('creates a new update with the public expo config', async () => {
const flags = ['--non-interactive', '--branch=branch123', '--message=abc'];
@@ -11,6 +11,7 @@ import {
ensureEASUpdateIsConfiguredAsync,
ensureEASUpdateIsConfiguredInEasJsonAsync,
} from '../../update/configure';
import { assertEnvironmentFlagForSdk55OrGreater } from '../../update/utils';
export default class UpdateConfigure extends EasCommand {
static override description = 'configure the project to support EAS Update';
@@ -42,6 +43,11 @@ export default class UpdateConfigure extends EasCommand {
withServerSideEnvironment: flags['environment'] ?? null,
});
assertEnvironmentFlagForSdk55OrGreater({
sdkVersion: exp.sdkVersion,
environment: flags['environment'],
});
Log.log(
'💡 The following process will configure your project to use EAS Update. These changes only apply to your local project files and you can safely revert them at any time.'
);
@@ -9,6 +9,7 @@ import { ensureRepoIsCleanAsync } from '../../build/utils/repository';
import { getUpdateGroupUrl } from '../../build/utils/url';
import EasCommand from '../../commandUtils/EasCommand';
import { EasNonInteractiveAndJsonFlags, EasUpdateEnvironmentFlag } from '../../commandUtils/flags';
import { assertEnvironmentFlagForSdk55OrGreater } from '../../update/utils';
import { getPaginatedQueryOptions } from '../../commandUtils/pagination';
import fetch from '../../fetch';
import {
@@ -249,6 +250,11 @@ export default class UpdatePublish extends EasCommand {
projectDir,
} = await getDynamicPublicProjectConfigAsync();
assertEnvironmentFlagForSdk55OrGreater({
sdkVersion: expPossiblyWithoutEasUpdateConfigured.sdkVersion,
environment,
});
await maybeWarnAboutEasOutagesAsync(graphqlClient, [StatuspageServiceName.EasUpdate]);
const easJsonAccessor = EasJsonAccessor.fromProjectPath(projectDir);
@@ -25,6 +25,7 @@ export class CredentialsContext {
public readonly appStore = new AppStoreApi();
public readonly ios = IosGraphqlClient;
public readonly nonInteractive: boolean;
public readonly autoAcceptCredentialReuse: boolean;
public readonly freezeCredentials: boolean = false;
public readonly projectDir: string;
public readonly user: Actor;
@@ -50,6 +51,7 @@ export class CredentialsContext {
analytics: Analytics;
vcsClient: Client;
freezeCredentials?: boolean;
autoAcceptCredentialReuse?: boolean;
env?: Env;
}
) {
@@ -60,6 +62,7 @@ export class CredentialsContext {
this.analytics = options.analytics;
this.vcsClient = options.vcsClient;
this.nonInteractive = options.nonInteractive ?? false;
this.autoAcceptCredentialReuse = options.autoAcceptCredentialReuse ?? false;
this.projectInfo = options.projectInfo;
this.freezeCredentials = options.freezeCredentials ?? false;
this.usesBroadcastPushNotifications =
@@ -66,6 +66,11 @@ export async function provideOrGenerateAscApiKeyAsync(
throw new Error(`A new App Store Connect API Key cannot be created in non-interactive mode.`);
}
// When auto-accepting credentials, always auto-generate without asking for user input
if (ctx.autoAcceptCredentialReuse) {
return await generateAscApiKeyAsync(ctx, purpose);
}
const userProvided = await promptForAscApiKeyAsync(ctx);
if (!userProvided) {
return await generateAscApiKeyAsync(ctx, purpose);
@@ -14,7 +14,7 @@ import { pushKeySchema } from '../credentials';
import { isPushKeyValidAndTrackedAsync } from '../validators/validatePushKey';
export async function provideOrGeneratePushKeyAsync(ctx: CredentialsContext): Promise<PushKey> {
if (!ctx.nonInteractive) {
if (!ctx.nonInteractive && !ctx.autoAcceptCredentialReuse) {
const userProvided = await promptForPushKeyAsync(ctx);
if (userProvided) {
if (!ctx.appStore.authCtx) {
@@ -65,6 +65,12 @@ export class SetUpAscApiKey {
return await new AssignAscApiKey(this.app).runAsync(ctx, maybeAutoselectedKey, this.purpose);
}
// When auto-accepting credentials and no valid key was found, generate a new one without prompting
if (ctx.autoAcceptCredentialReuse) {
const ascApiKey = await new CreateAscApiKey(this.app.account).runAsync(ctx, this.purpose);
return await new AssignAscApiKey(this.app).runAsync(ctx, ascApiKey, this.purpose);
}
const availableChoices =
keysForAccount.length === 0
? this.choices.filter(choice => choice.value !== SetupAscApiKeyChoice.USE_EXISTING)
@@ -90,9 +96,11 @@ export class SetUpAscApiKey {
return null;
}
const [autoselectedKey] = sortAscApiKeysByUpdatedAtDesc(validKeys);
const useAutoselected = await confirmAsync({
message: `Reuse this App Store Connect API Key?\n${formatAscApiKey(autoselectedKey)}`,
});
const useAutoselected =
ctx.autoAcceptCredentialReuse ||
(await confirmAsync({
message: `Reuse this App Store Connect API Key?\n${formatAscApiKey(autoselectedKey)}`,
}));
if (useAutoselected) {
Log.log(`Using App Store Connect API Key with ID ${autoselectedKey.keyIdentifier}`);
@@ -117,11 +117,13 @@ export class SetUpDistributionCertificate {
const validDistCerts = await this.getValidDistCertsAsync(ctx);
const autoselectedDistCert = validDistCerts[0];
const useAutoselected = await confirmAsync({
message: `Reuse this distribution certificate?\n${formatDistributionCertificate(
autoselectedDistCert
)}`,
});
const useAutoselected =
ctx.autoAcceptCredentialReuse ||
(await confirmAsync({
message: `Reuse this distribution certificate?\n${formatDistributionCertificate(
autoselectedDistCert
)}`,
}));
if (useAutoselected) {
Log.log(
@@ -142,7 +142,7 @@ export class SetUpProvisioningProfile {
}
const isNonInteractiveOrUserDidConfirmAsync = async (): Promise<boolean> => {
if (ctx.nonInteractive) {
if (ctx.nonInteractive || ctx.autoAcceptCredentialReuse) {
return true;
}
return await confirmAsync({
@@ -63,12 +63,14 @@ export class SetUpPushKey {
if (validPushKeys.length > 0) {
const autoselectedPushKey = validPushKeys[0];
const useAutoselected = await confirmAsync({
message: `Reuse this Push Key?\n${formatPushKey(
autoselectedPushKey,
validPushKeys.map(pushKey => pushKey.keyIdentifier)
)}`,
});
const useAutoselected =
ctx.autoAcceptCredentialReuse ||
(await confirmAsync({
message: `Reuse this Push Key?\n${formatPushKey(
autoselectedPushKey,
validPushKeys.map(pushKey => pushKey.keyIdentifier)
)}`,
}));
if (useAutoselected) {
Log.log(`Using push key with ID ${autoselectedPushKey.keyIdentifier}`);
@@ -77,6 +79,11 @@ export class SetUpPushKey {
}
}
// When auto-accepting and no valid push key was found, generate a new one without prompting
if (ctx.autoAcceptCredentialReuse) {
return await new CreatePushKey(this.app.account).runAsync(ctx);
}
const { action } = await promptAsync({
type: 'select',
name: 'action',
@@ -9,6 +9,7 @@ import {
CreateWorkflowRunFromGitRefMutationVariables,
CreateWorkflowRunMutation,
CreateWorkflowRunMutationVariables,
WorkflowProjectSourceInput,
WorkflowRevisionInput,
WorkflowRunInput,
} from '../generated';
@@ -103,6 +104,40 @@ export namespace WorkflowRunMutation {
return { id: data.workflowRun.createWorkflowRunFromGitRef.id };
}
export async function createExpoGoRepackWorkflowRunAsync(
graphqlClient: ExpoGraphqlClient,
{
appId,
projectSource,
}: {
appId: string;
projectSource: WorkflowProjectSourceInput;
}
): Promise<{ id: string }> {
const data = await withErrorHandlingAsync(
graphqlClient
.mutation<
{ workflowRun: { createExpoGoRepackWorkflowRun: { id: string } } },
{ appId: string; projectSource: WorkflowProjectSourceInput }
>(
/* eslint-disable graphql/template-strings */
gql`
mutation CreateExpoGoRepackWorkflowRun($appId: ID!, $projectSource: WorkflowProjectSourceInput!) {
workflowRun {
createExpoGoRepackWorkflowRun(appId: $appId, projectSource: $projectSource) {
id
}
}
}
`,
/* eslint-enable graphql/template-strings */
{ appId, projectSource }
)
.toPromise()
);
return { id: data.workflowRun.createExpoGoRepackWorkflowRun.id };
}
export async function cancelWorkflowRunAsync(
graphqlClient: ExpoGraphqlClient,
{
@@ -0,0 +1,86 @@
import gql from 'graphql-tag';
import { ExpoGraphqlClient } from '../../commandUtils/context/contextUtils/createGraphqlClient';
import { withErrorHandlingAsync } from '../client';
import {
AppObservePlatform,
AppObserveTimeSeriesInput,
AppObserveVersionMarker,
} from '../generated';
type AppObserveTimeSeriesQuery = {
app: {
byId: {
id: string;
observe: {
timeSeries: {
versionMarkers: AppObserveVersionMarker[];
};
};
};
};
};
type AppObserveTimeSeriesQueryVariables = {
appId: string;
input: Pick<AppObserveTimeSeriesInput, 'metricName' | 'platform' | 'startTime' | 'endTime'>;
};
export const ObserveQuery = {
async timeSeriesVersionMarkersAsync(
graphqlClient: ExpoGraphqlClient,
{
appId,
metricName,
platform,
startTime,
endTime,
}: {
appId: string;
metricName: string;
platform: AppObservePlatform;
startTime: string;
endTime: string;
}
): Promise<AppObserveVersionMarker[]> {
const data = await withErrorHandlingAsync(
graphqlClient
.query<AppObserveTimeSeriesQuery, AppObserveTimeSeriesQueryVariables>(
gql`
query AppObserveTimeSeries($appId: String!, $input: AppObserveTimeSeriesInput!) {
app {
byId(appId: $appId) {
id
observe {
timeSeries(input: $input) {
versionMarkers {
appVersion
eventCount
firstSeenAt
statistics {
min
max
median
average
p80
p90
p99
}
}
}
}
}
}
}
`,
{
appId,
input: { metricName, platform, startTime, endTime },
}
)
.toPromise()
);
return data.app.byId.observe.timeSeries.versionMarkers;
},
};
+9
View File
@@ -26,6 +26,15 @@ export default class Log {
}
}
/**
* Signal that the cursor is already at the start of a fresh line (e.g. after
* a spinner clears itself), so that the next `addNewLineIfNone()` call knows
* it doesn't need to emit an extra blank line.
*/
public static markFreshLine(): void {
Log.isLastLineNewLine = true;
}
public static error(...args: any[]): void {
Log.consoleLog(...Log.withTextColor(args, chalk.red));
}
@@ -0,0 +1,137 @@
import { AppObservePlatform, AppPlatform } from '../../graphql/generated';
import { ObserveQuery } from '../../graphql/queries/ObserveQuery';
import { makeMetricsKey } from '../utils';
import { fetchObserveMetricsAsync } from '../fetchMetrics';
jest.mock('../../graphql/queries/ObserveQuery');
jest.mock('../../log');
const SIMPLE_MARKER = {
__typename: 'AppObserveVersionMarker' as const,
appVersion: '1.0.0',
eventCount: 100,
firstSeenAt: '2025-01-01T00:00:00.000Z',
statistics: {
__typename: 'AppObserveVersionMarkerStatistics' as const,
min: 0.1,
max: 0.5,
median: 0.2,
average: 0.3,
p80: 0.35,
p90: 0.4,
p99: 0.48,
},
};
describe('fetchObserveMetricsAsync', () => {
const mockTimeSeriesMarkers = jest.mocked(ObserveQuery.timeSeriesVersionMarkersAsync);
const mockGraphqlClient = {} as any;
beforeEach(() => {
mockTimeSeriesMarkers.mockClear();
});
// TODO(@ubax): add support for fetching multiple metrics and platforms in a single query
it('creates queries for each metric+platform combination and assembles metricsMap', async () => {
mockTimeSeriesMarkers
.mockResolvedValueOnce([{ ...SIMPLE_MARKER, eventCount: 100 }])
.mockResolvedValueOnce([{ ...SIMPLE_MARKER, eventCount: 80 }]);
const metricsMap = await fetchObserveMetricsAsync(
mockGraphqlClient,
'project-123',
['expo.app_startup.tti', 'expo.app_startup.cold_launch_time'],
[AppPlatform.Ios],
'2025-01-01T00:00:00.000Z',
'2025-03-01T00:00:00.000Z'
);
expect(mockTimeSeriesMarkers).toHaveBeenCalledTimes(2);
expect(mockTimeSeriesMarkers).toHaveBeenNthCalledWith(1, mockGraphqlClient, {
appId: 'project-123',
metricName: 'expo.app_startup.tti',
platform: AppObservePlatform.Ios,
startTime: '2025-01-01T00:00:00.000Z',
endTime: '2025-03-01T00:00:00.000Z',
});
expect(mockTimeSeriesMarkers).toHaveBeenNthCalledWith(2, mockGraphqlClient, {
appId: 'project-123',
metricName: 'expo.app_startup.cold_launch_time',
platform: AppObservePlatform.Ios,
startTime: '2025-01-01T00:00:00.000Z',
endTime: '2025-03-01T00:00:00.000Z',
});
const key = makeMetricsKey('1.0.0', AppPlatform.Ios);
const metricsForVersion = metricsMap.get(key)!;
expect(metricsForVersion.get('expo.app_startup.tti')).toEqual(
expect.objectContaining({ eventCount: 100, min: 0.1, p99: 0.48 })
);
expect(metricsForVersion.get('expo.app_startup.cold_launch_time')).toEqual(
expect.objectContaining({ eventCount: 80 })
);
});
it('creates queries for each platform', async () => {
mockTimeSeriesMarkers.mockResolvedValue([]);
await fetchObserveMetricsAsync(
mockGraphqlClient,
'project-123',
['expo.app_startup.tti'],
[AppPlatform.Ios, AppPlatform.Android],
'2025-01-01T00:00:00.000Z',
'2025-03-01T00:00:00.000Z'
);
expect(mockTimeSeriesMarkers).toHaveBeenCalledTimes(2);
expect(mockTimeSeriesMarkers).toHaveBeenNthCalledWith(1, mockGraphqlClient, {
appId: 'project-123',
metricName: 'expo.app_startup.tti',
platform: AppObservePlatform.Ios,
startTime: '2025-01-01T00:00:00.000Z',
endTime: '2025-03-01T00:00:00.000Z',
});
expect(mockTimeSeriesMarkers).toHaveBeenNthCalledWith(2, mockGraphqlClient, {
appId: 'project-123',
metricName: 'expo.app_startup.tti',
platform: AppObservePlatform.Android,
startTime: '2025-01-01T00:00:00.000Z',
endTime: '2025-03-01T00:00:00.000Z',
});
});
it('handles partial failures gracefully - successful queries still populate metricsMap', async () => {
mockTimeSeriesMarkers
.mockResolvedValueOnce([SIMPLE_MARKER])
.mockRejectedValueOnce(new Error('Unknown metric'));
const metricsMap = await fetchObserveMetricsAsync(
mockGraphqlClient,
'project-123',
['expo.app_startup.tti', 'bad.metric'],
[AppPlatform.Android],
'2025-01-01T00:00:00.000Z',
'2025-03-01T00:00:00.000Z'
);
const key = makeMetricsKey('1.0.0', AppPlatform.Android);
expect(metricsMap.get(key)!.has('expo.app_startup.tti')).toBe(true);
expect(metricsMap.get(key)!.has('bad.metric')).toBe(false);
});
it('returns empty map when all queries fail', async () => {
mockTimeSeriesMarkers.mockRejectedValue(new Error('Network error'));
const metricsMap = await fetchObserveMetricsAsync(
mockGraphqlClient,
'project-123',
['expo.app_startup.tti'],
[AppPlatform.Ios],
'2025-01-01T00:00:00.000Z',
'2025-03-01T00:00:00.000Z'
);
expect(metricsMap.size).toBe(0);
});
});
@@ -0,0 +1,297 @@
import { AppPlatform } from '../../graphql/generated';
import {
buildObserveMetricsJson,
buildObserveMetricsTable,
resolveStatKey,
} from '../formatMetrics';
import type { MetricValues, ObserveMetricsMap } from '../metrics.types';
import { makeMetricsKey } from '../utils';
function makeMetricValueWithDefaults(overrides: Partial<MetricValues>): MetricValues {
return {
min: 0.1,
median: 0.3,
max: 1.1,
average: 0.5,
p80: 0.8,
p90: 0.9,
p99: 1.0,
eventCount: 100,
...overrides,
};
}
describe(buildObserveMetricsTable, () => {
it('formats metrics grouped by version with metric columns', () => {
const metricsMap: ObserveMetricsMap = new Map();
const iosKey = makeMetricsKey('1.2.0', AppPlatform.Ios);
metricsMap.set(
iosKey,
new Map([
[
'expo.app_startup.cold_launch_time',
makeMetricValueWithDefaults({ median: 0.35, eventCount: 110 }),
],
['expo.app_startup.tti', makeMetricValueWithDefaults({ median: 1.32123, eventCount: 90 })],
])
);
const androidKey = makeMetricsKey('1.1.0', AppPlatform.Android);
metricsMap.set(
androidKey,
new Map([
[
'expo.app_startup.cold_launch_time',
makeMetricValueWithDefaults({ median: 0.25, eventCount: 120 }),
],
['expo.app_startup.tti', makeMetricValueWithDefaults({ median: 1.12111, eventCount: 100 })],
])
);
const output = buildObserveMetricsTable(
metricsMap,
['expo.app_startup.cold_launch_time', 'expo.app_startup.tti'],
['median', 'eventCount']
);
// The header is bolded, thus the escape characters in the snapshot
expect(output).toMatchInlineSnapshot(`
"App Version Platform Cold Launch Med Cold Launch Count TTI Med TTI Count
----------- -------- --------------- ----------------- ------- ---------
1.2.0 iOS 0.35s 110 1.32s 90
1.1.0 Android 0.25s 120 1.12s 100 "
`);
});
it('shows - for metrics with missing values for versions', () => {
const metricsMap: ObserveMetricsMap = new Map();
const key = makeMetricsKey('2.0.0', AppPlatform.Ios);
metricsMap.set(
key,
new Map([
[
'expo.app_startup.cold_launch_time',
makeMetricValueWithDefaults({ median: 0.25, eventCount: 80 }),
],
])
);
const output = buildObserveMetricsTable(
metricsMap,
['expo.app_startup.cold_launch_time', 'expo.app_startup.tti'],
['median', 'eventCount']
);
expect(output).toMatchInlineSnapshot(`
"App Version Platform Cold Launch Med Cold Launch Count TTI Med TTI Count
----------- -------- --------------- ----------------- ------- ---------
2.0.0 iOS 0.25s 80 - - "
`);
});
it('returns message when no metrics data found', () => {
const output = buildObserveMetricsTable(
new Map(),
['expo.app_startup.cold_launch_time', 'expo.app_startup.tti'],
['median', 'eventCount']
);
expect(output).toMatchInlineSnapshot(`"No metrics data found."`);
});
});
describe(buildObserveMetricsJson, () => {
it('produces JSON with all stats per metric', () => {
const metricsMap: ObserveMetricsMap = new Map();
const key = makeMetricsKey('1.0.0', AppPlatform.Ios);
metricsMap.set(
key,
new Map([
['expo.app_startup.tti', makeMetricValueWithDefaults({ median: 0.12, eventCount: 90 })],
])
);
const result = buildObserveMetricsJson(
metricsMap,
['expo.app_startup.tti'],
['min', 'median', 'max', 'p99']
);
expect(result).toHaveLength(1);
expect(result[0]).toEqual({
appVersion: '1.0.0',
platform: AppPlatform.Ios,
metrics: {
'expo.app_startup.tti': {
min: 0.1,
median: 0.12,
max: 1.1,
p99: 1.0,
},
},
});
});
it('produces null values for metrics missing from a version that has other metric data', () => {
const metricsMap: ObserveMetricsMap = new Map();
const key = makeMetricsKey('3.0.0', AppPlatform.Android);
metricsMap.set(
key,
new Map([
[
'expo.app_startup.cold_launch_time',
makeMetricValueWithDefaults({ median: 0.25, eventCount: 80 }),
],
])
);
const result = buildObserveMetricsJson(
metricsMap,
['expo.app_startup.cold_launch_time', 'expo.app_startup.tti'],
['median', 'eventCount']
);
expect(result[0].metrics).toEqual({
'expo.app_startup.cold_launch_time': {
median: 0.25,
eventCount: 80,
},
'expo.app_startup.tti': {
median: null,
eventCount: null,
},
});
});
});
describe(makeMetricsKey, () => {
it('creates a key from version and platform', () => {
expect(makeMetricsKey('1.0.0', AppPlatform.Ios)).toBe('1.0.0:IOS');
expect(makeMetricsKey('2.0.0', AppPlatform.Android)).toBe('2.0.0:ANDROID');
});
});
describe(resolveStatKey, () => {
it('resolves canonical stat names', () => {
expect(resolveStatKey('min')).toBe('min');
expect(resolveStatKey('max')).toBe('max');
expect(resolveStatKey('median')).toBe('median');
expect(resolveStatKey('average')).toBe('average');
expect(resolveStatKey('p80')).toBe('p80');
expect(resolveStatKey('p90')).toBe('p90');
expect(resolveStatKey('p99')).toBe('p99');
expect(resolveStatKey('eventCount')).toBe('eventCount');
});
it('resolves short aliases', () => {
expect(resolveStatKey('med')).toBe('median');
expect(resolveStatKey('avg')).toBe('average');
expect(resolveStatKey('count')).toBe('eventCount');
expect(resolveStatKey('event_count')).toBe('eventCount');
});
it('throws on unknown stat', () => {
expect(() => resolveStatKey('unknown')).toThrow('Unknown statistic: "unknown"');
});
});
describe('custom stats parameter', () => {
it('table renders only selected stats', () => {
const metricsMap: ObserveMetricsMap = new Map();
const key = makeMetricsKey('1.0.0', AppPlatform.Ios);
metricsMap.set(
key,
new Map([
[
'expo.app_startup.tti',
{
min: 0.01,
median: 0.1,
max: 0.5,
average: null,
p80: null,
p90: null,
p99: 0.9,
eventCount: 42,
},
],
])
);
const output = buildObserveMetricsTable(
metricsMap,
['expo.app_startup.tti'],
['p99', 'eventCount']
);
expect(output).toContain('TTI P99');
expect(output).toContain('TTI Count');
expect(output).toContain('0.90s');
expect(output).toContain('42');
expect(output).not.toContain('TTI Min');
expect(output).not.toContain('TTI Med');
expect(output).not.toContain('TTI Max');
});
it("table formats eventCount as integer without 's' suffix", () => {
const metricsMap: ObserveMetricsMap = new Map();
const key = makeMetricsKey('1.0.0', AppPlatform.Ios);
metricsMap.set(
key,
new Map([
[
'expo.app_startup.tti',
{
min: 0.01,
median: 0.1,
max: 0.5,
average: null,
p80: null,
p90: null,
p99: null,
eventCount: 100,
},
],
])
);
const output = buildObserveMetricsTable(metricsMap, ['expo.app_startup.tti'], ['eventCount']);
expect(output).toContain('100');
expect(output).not.toContain('100s');
expect(output).not.toContain('100.00s');
});
it('JSON includes only selected stats', () => {
const metricsMap: ObserveMetricsMap = new Map();
const key = makeMetricsKey('1.0.0', AppPlatform.Ios);
metricsMap.set(
key,
new Map([
[
'expo.app_startup.tti',
{
min: 0.01,
median: 0.1,
max: 0.5,
average: 0.15,
p80: 0.3,
p90: 0.4,
p99: 0.9,
eventCount: 42,
},
],
])
);
const result = buildObserveMetricsJson(
metricsMap,
['expo.app_startup.tti'],
['p90', 'eventCount']
);
expect(result[0].metrics['expo.app_startup.tti']).toEqual({
p90: 0.4,
eventCount: 42,
});
});
});
@@ -0,0 +1,52 @@
import { getMetricDisplayName, resolveMetricName } from '../metricNames';
describe(resolveMetricName, () => {
it('resolves short alias "tti" to full metric name', () => {
expect(resolveMetricName('tti')).toBe('expo.app_startup.tti');
});
it('resolves short alias "ttr" to full metric name', () => {
expect(resolveMetricName('ttr')).toBe('expo.app_startup.ttr');
});
it('resolves short alias "cold_launch" to full metric name', () => {
expect(resolveMetricName('cold_launch')).toBe('expo.app_startup.cold_launch_time');
});
it('resolves short alias "warm_launch" to full metric name', () => {
expect(resolveMetricName('warm_launch')).toBe('expo.app_startup.warm_launch_time');
});
it('resolves short alias "bundle_load" to full metric name', () => {
expect(resolveMetricName('bundle_load')).toBe('expo.app_startup.bundle_load_time');
});
it('passes through full metric names unchanged', () => {
expect(resolveMetricName('expo.app_startup.tti')).toBe('expo.app_startup.tti');
expect(resolveMetricName('expo.app_startup.cold_launch_time')).toBe(
'expo.app_startup.cold_launch_time'
);
});
it('throws on unknown alias', () => {
expect(() => resolveMetricName('unknown_metric')).toThrow('Unknown metric: "unknown_metric"');
});
it('passes through dot-containing custom metric names', () => {
expect(resolveMetricName('custom.metric.name')).toBe('custom.metric.name');
});
});
describe(getMetricDisplayName, () => {
it('returns short display name for known metrics', () => {
expect(getMetricDisplayName('expo.app_startup.cold_launch_time')).toBe('Cold Launch');
expect(getMetricDisplayName('expo.app_startup.warm_launch_time')).toBe('Warm Launch');
expect(getMetricDisplayName('expo.app_startup.tti')).toBe('TTI');
expect(getMetricDisplayName('expo.app_startup.ttr')).toBe('TTR');
expect(getMetricDisplayName('expo.app_startup.bundle_load_time')).toBe('Bundle Load');
});
it('returns the full metric name for unknown metrics', () => {
expect(getMetricDisplayName('custom.metric.name')).toBe('custom.metric.name');
});
});
@@ -0,0 +1,17 @@
import { validateDateFlag } from '../utils';
describe(validateDateFlag, () => {
it('throws on invalid --start date', () => {
expect(() => validateDateFlag('not-a-date', '--start')).toThrow(
'Invalid --start date: "not-a-date"'
);
});
it('throws on invalid --end date', () => {
expect(() => validateDateFlag('also-bad', '--end')).toThrow('Invalid --end date: "also-bad"');
});
it('accepts valid ISO date in --start', () => {
expect(() => validateDateFlag('2025-01-01', '--start')).not.toThrow();
});
});
@@ -0,0 +1,91 @@
import { ExpoGraphqlClient } from '../commandUtils/context/contextUtils/createGraphqlClient';
import { AppObservePlatform, AppObserveVersionMarker, AppPlatform } from '../graphql/generated';
import { ObserveQuery } from '../graphql/queries/ObserveQuery';
import Log from '../log';
import type { MetricValues, ObserveMetricsMap } from './metrics.types';
import { makeMetricsKey } from './utils';
const appPlatformToObservePlatform: Record<AppPlatform, AppObservePlatform> = {
[AppPlatform.Android]: AppObservePlatform.Android,
[AppPlatform.Ios]: AppObservePlatform.Ios,
};
const observePlatformToAppPlatform: Record<AppObservePlatform, AppPlatform> = {
[AppObservePlatform.Android]: AppPlatform.Android,
[AppObservePlatform.Ios]: AppPlatform.Ios,
};
interface ObserveQueryResult {
metricName: string;
platform: AppObservePlatform;
markers: AppObserveVersionMarker[];
}
export async function fetchObserveMetricsAsync(
graphqlClient: ExpoGraphqlClient,
appId: string,
metricNames: string[],
platforms: AppPlatform[],
startTime: string,
endTime: string
): Promise<ObserveMetricsMap> {
const observeQueries: Promise<ObserveQueryResult | null>[] = [];
// TODO(@ubax): add support for fetching multiple metrics and platforms in a single query
for (const metricName of metricNames) {
for (const appPlatform of platforms) {
const observePlatform = appPlatformToObservePlatform[appPlatform];
observeQueries.push(
ObserveQuery.timeSeriesVersionMarkersAsync(graphqlClient, {
appId,
metricName,
platform: observePlatform,
startTime,
endTime,
})
.then(markers => ({
metricName,
platform: observePlatform,
markers,
}))
.catch(error => {
Log.warn(
`Failed to fetch observe data for metric "${metricName}" on ${observePlatform}: ${error.message}`
);
return null;
})
);
}
}
const observeResults = await Promise.all(observeQueries);
const metricsMap: ObserveMetricsMap = new Map();
for (const result of observeResults) {
if (!result) {
continue;
}
const { metricName, platform, markers } = result;
const appPlatform = observePlatformToAppPlatform[platform];
for (const marker of markers) {
const key = makeMetricsKey(marker.appVersion, appPlatform);
if (!metricsMap.has(key)) {
metricsMap.set(key, new Map());
}
const values: MetricValues = {
min: marker.statistics.min,
max: marker.statistics.max,
median: marker.statistics.median,
average: marker.statistics.average,
p80: marker.statistics.p80,
p90: marker.statistics.p90,
p99: marker.statistics.p99,
eventCount: marker.eventCount,
};
metricsMap.get(key)!.set(metricName, values);
}
}
return metricsMap;
}
@@ -0,0 +1,143 @@
import chalk from 'chalk';
import { EasCommandError } from '../commandUtils/errors';
import { AppPlatform } from '../graphql/generated';
import { appPlatformDisplayNames } from '../platform';
import { getMetricDisplayName } from './metricNames';
import { parseMetricsKey } from './utils';
import type { ObserveMetricsMap } from './metrics.types';
export type StatisticKey =
| 'min'
| 'max'
| 'median'
| 'average'
| 'p80'
| 'p90'
| 'p99'
| 'eventCount';
export const STAT_ALIASES: Record<string, StatisticKey> = {
min: 'min',
max: 'max',
med: 'median',
median: 'median',
avg: 'average',
average: 'average',
p80: 'p80',
p90: 'p90',
p99: 'p99',
count: 'eventCount',
event_count: 'eventCount',
eventCount: 'eventCount',
};
export const STAT_DISPLAY_NAMES: Record<StatisticKey, string> = {
min: 'Min',
max: 'Max',
median: 'Med',
average: 'Avg',
p80: 'P80',
p90: 'P90',
p99: 'P99',
eventCount: 'Count',
};
/**
* Resolves a user-provided stat alias (e.g. "avg", "med", "count") to graphql supported StatisticKey.
*/
export function resolveStatKey(input: string): StatisticKey {
const resolved = STAT_ALIASES[input];
if (resolved) {
return resolved;
}
throw new EasCommandError(
`Unknown statistic: "${input}". Valid options: ${Object.keys(STAT_ALIASES).join(', ')}`
);
}
function formatStatValue(stat: StatisticKey, value: number | null | undefined): string {
if (value == null) {
return '-';
}
if (stat === 'eventCount') {
return String(value);
}
return `${value.toFixed(2)}s`;
}
export type MetricValuesJson = Partial<Record<StatisticKey, number | null>>;
export interface ObserveMetricsVersionResult {
appVersion: string;
platform: AppPlatform;
metrics: Record<string, MetricValuesJson>;
}
export function buildObserveMetricsJson(
metricsMap: ObserveMetricsMap,
metricNames: string[],
stats: StatisticKey[]
): ObserveMetricsVersionResult[] {
const results: ObserveMetricsVersionResult[] = [];
for (const [key, versionMetrics] of metricsMap) {
const { appVersion, platform } = parseMetricsKey(key);
const metrics: Record<string, MetricValuesJson> = {};
for (const metricName of metricNames) {
const values = versionMetrics.get(metricName);
const statValues: MetricValuesJson = {};
for (const stat of stats) {
statValues[stat] = values?.[stat] ?? null;
}
metrics[metricName] = statValues;
}
results.push({ appVersion, platform, metrics });
}
return results;
}
export function buildObserveMetricsTable(
metricsMap: ObserveMetricsMap,
metricNames: string[],
stats: StatisticKey[]
): string {
const results = buildObserveMetricsJson(metricsMap, metricNames, stats);
if (results.length === 0) {
return chalk.yellow('No metrics data found.');
}
const fixedHeaders = ['App Version', 'Platform'];
const metricHeaders: string[] = [];
for (const m of metricNames) {
const name = getMetricDisplayName(m);
for (const stat of stats) {
metricHeaders.push(`${name} ${STAT_DISPLAY_NAMES[stat]}`);
}
}
const headers = [...fixedHeaders, ...metricHeaders];
const rows: string[][] = results.map(result => {
const metricCells: string[] = [];
for (const m of metricNames) {
const values = result.metrics[m];
for (const stat of stats) {
metricCells.push(formatStatValue(stat, values?.[stat] ?? null));
}
}
return [result.appVersion, appPlatformDisplayNames[result.platform], ...metricCells];
});
const colWidths = headers.map((h, i) => Math.max(h.length, ...rows.map(r => r[i].length)));
const headerLine = headers.map((h, i) => h.padEnd(colWidths[i])).join(' ');
const separatorLine = colWidths.map(w => '-'.repeat(w)).join(' ');
const dataLines = rows.map(row => row.map((cell, i) => cell.padEnd(colWidths[i])).join(' '));
return [chalk.bold(headerLine), separatorLine, ...dataLines].join('\n');
}
@@ -0,0 +1,35 @@
import { EasCommandError } from '../commandUtils/errors';
export const METRIC_ALIASES: Record<string, string> = {
tti: 'expo.app_startup.tti',
ttr: 'expo.app_startup.ttr',
cold_launch: 'expo.app_startup.cold_launch_time',
warm_launch: 'expo.app_startup.warm_launch_time',
bundle_load: 'expo.app_startup.bundle_load_time',
};
const KNOWN_FULL_NAMES = new Set(Object.values(METRIC_ALIASES));
export const METRIC_SHORT_NAMES: Record<string, string> = {
'expo.app_startup.cold_launch_time': 'Cold Launch',
'expo.app_startup.warm_launch_time': 'Warm Launch',
'expo.app_startup.tti': 'TTI',
'expo.app_startup.ttr': 'TTR',
'expo.app_startup.bundle_load_time': 'Bundle Load',
};
export function resolveMetricName(input: string): string {
if (METRIC_ALIASES[input]) {
return METRIC_ALIASES[input];
}
if (KNOWN_FULL_NAMES.has(input) || input.includes('.')) {
return input;
}
throw new EasCommandError(
`Unknown metric: "${input}". Use a full metric name (e.g. expo.app_startup.tti) or a short alias: ${Object.keys(METRIC_ALIASES).join(', ')}`
);
}
export function getMetricDisplayName(metricName: string): string {
return METRIC_SHORT_NAMES[metricName] ?? metricName;
}
@@ -0,0 +1,21 @@
import type { AppPlatform } from '../graphql/generated';
export interface MetricValues {
min: number | null | undefined;
max: number | null | undefined;
median: number | null | undefined;
average: number | null | undefined;
p80: number | null | undefined;
p90: number | null | undefined;
p99: number | null | undefined;
eventCount: number | null | undefined;
}
/**
* ObserveMetricsKey encodes an app version + platform pair into a single string key.
* This is needed because the observe API returns metrics per (version, platform) combination,
* and we use a flat Map
*/
export type ObserveMetricsKey = `${string}:${AppPlatform}`;
export type ObserveMetricsMap = Map<ObserveMetricsKey, Map<string, MetricValues>>;
+27
View File
@@ -0,0 +1,27 @@
import { EasCommandError } from '../commandUtils/errors';
import { AppPlatform } from '../graphql/generated';
import type { ObserveMetricsKey } from './metrics.types';
export function makeMetricsKey(appVersion: string, platform: AppPlatform): ObserveMetricsKey {
return `${appVersion}:${platform}`;
}
export function parseMetricsKey(key: ObserveMetricsKey): {
appVersion: string;
platform: AppPlatform;
} {
const lastColon = key.lastIndexOf(':');
return {
appVersion: key.slice(0, lastColon),
platform: key.slice(lastColon + 1) as AppPlatform,
};
}
export function validateDateFlag(value: string, flagName: string): void {
const parsed = new Date(value);
if (isNaN(parsed.getTime())) {
throw new EasCommandError(
`Invalid ${flagName} date: "${value}". Provide a valid ISO 8601 date (e.g. 2025-01-01).`
);
}
}
+19
View File
@@ -1,7 +1,9 @@
import { ExpoConfig } from '@expo/config';
import { Errors } from '@oclif/core';
import { format } from '@expo/timeago.js';
import chalk from 'chalk';
import dateFormat from 'dateformat';
import semver from 'semver';
import { ExpoGraphqlClient } from '../commandUtils/context/contextUtils/createGraphqlClient';
import {
@@ -357,3 +359,20 @@ export const updatePublishPlatformToAppPlatform: Record<UpdatePublishPlatform, A
android: AppPlatform.Android,
ios: AppPlatform.Ios,
};
export function assertEnvironmentFlagForSdk55OrGreater({
sdkVersion,
environment,
}: {
sdkVersion: string | undefined;
environment: string | undefined;
}): void {
if (process.env.EAS_BUILD) {
return;
}
if (sdkVersion && semver.gte(sdkVersion, '55.0.0') && !environment) {
Errors.error('--environment flag is required for projects using Expo SDK 55 or greater', {
exit: 1,
});
}
}
+3 -1
View File
@@ -12,9 +12,11 @@ ROOT_DIR="$( cd "$SCRIPTS_DIR"/.. && pwd )"
# to @expo/eas-build-job dependency, so the update-local-plugin step is no longer needed.
# $SCRIPTS_DIR/bin/run update-local-plugin
next_version_bump=$($SCRIPTS_DIR/bin/run next-version)
next_version_bump=`(cd $SCRIPTS_DIR; node --no-warnings=ExperimentalWarning --loader ts-node/esm src/nextVersion.ts)`
next_version=${1:-$next_version_bump}
echo "next_version = ${next_version}"
if [[ "$GITHUB_USER" == "Expo CI" && "$GITHUB_EMAIL" == "[email protected]" && "$INPUT_DRY_RUN" != "true" ]]; then
echo "Releasing with version $next_version"
lerna version --yes --exact "$next_version"