Compare commits

...
Author SHA1 Message Date
Krystof WoldrichandClaude Opus 5.5 38d337f607 [build-tools] Start expo-device-hub and serve-sim from the EAS package mirror
Device sessions ran `npx expo-device-hub@latest` and
`npx @expo/serve-sim@latest`, so a release that npm listed but did not
serve yet failed new sessions. Read the mirror pointer in the turtle-v2
bucket first, check the tarball's sha512, and run it as a `file:` spec.
Fall back to `npm pack <name>@latest` with retries, then to the old spec.
A requested version, a warm serve-sim and bun keep the npm spec.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 21:17:45 +01:00
6 changed files with 695 additions and 5 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
'@expo/build-tools': patch
---
Start expo-device-hub and serve-sim in device sessions from the EAS package mirror in the `turtle-v2` bucket after a sha512 check, and fall back to npm with retries, so a new release that npm does not serve yet no longer fails new sessions.
@@ -0,0 +1,289 @@
import downloadFile from '@expo/downloader';
import type { bunyan } from '@expo/logger';
import type { BuildStepEnv } from '@expo/steps';
import spawn from '@expo/turtle-spawn';
import { createHash } from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { Sentry } from '../../../sentry';
import { turtleFetch } from '../../../utils/turtleFetch';
import { resolveLatestDevicePackageAsync } from '../devicePackageMirror';
jest.mock('@expo/downloader', () => ({ __esModule: true, default: jest.fn() }));
jest.mock('@expo/turtle-spawn', () => ({ __esModule: true, default: jest.fn() }));
jest.mock('../../../utils/turtleFetch');
jest.mock('../../../sentry');
const MIRROR = 'https://storage.googleapis.com/turtle-v2/npm';
const HUB_TARBALL = Buffer.from('expo-device-hub 0.24.0 tarball');
const NPM_TARBALL = Buffer.from('expo-device-hub 0.24.1 tarball from npm');
function integrityOf(bytes: Buffer): string {
return `sha512-${createHash('sha512').update(bytes).digest('base64')}`;
}
function hubPointer(overrides: Record<string, unknown> = {}) {
return {
name: 'expo-device-hub',
version: '0.24.0',
tarball: '-/expo-device-hub-0.24.0.tgz',
integrity: integrityOf(HUB_TARBALL),
shasum: 'ff556b0858baea6125fe07bcb86c1441d41c80aa',
...overrides,
};
}
const logger = { info: jest.fn(), warn: jest.fn() } as unknown as bunyan;
const env = { PATH: '/usr/bin' } as BuildStepEnv;
const mockedFetch = jest.mocked(turtleFetch);
const mockedDownload = jest.mocked(downloadFile);
const mockedSpawn = jest.mocked(spawn);
/** Serves the pointer at `<mirror>/<name>/latest.json`; a missing entry is an HTTP 404. */
function servePointers(pointers: Record<string, unknown>) {
mockedFetch.mockImplementation((async (url: string) => {
if (!(url in pointers)) {
throw new Error(`Request failed with status 404 (${url})`);
}
return { json: async () => pointers[url] };
}) as unknown as typeof turtleFetch);
}
/** Writes the given bytes for each URL; a missing URL fails like a failed download. */
function serveFiles(files: Record<string, Buffer>) {
mockedDownload.mockImplementation(async (url, outputPath) => {
const bytes = files[url];
if (!bytes) {
throw new Error(`Failed to download the file: 404 (${url})`);
}
await fs.promises.writeFile(outputPath, bytes);
});
}
/** Each call answers like `npm pack <spec> --json`: an Error rejects, a Buffer writes a tarball. */
function npmPackAnswers(...answers: (Error | Buffer)[]) {
for (const answer of answers) {
mockedSpawn.mockImplementationOnce((async (
_command: string,
args: string[]
): Promise<{ stdout: string }> => {
if (answer instanceof Error) {
throw answer;
}
const destination = args[args.indexOf('--pack-destination') + 1];
await fs.promises.writeFile(path.join(destination, 'expo-device-hub-0.24.1.tgz'), answer);
return {
stdout: JSON.stringify([
{
name: 'expo-device-hub',
version: '0.24.1',
filename: 'expo-device-hub-0.24.1.tgz',
integrity: integrityOf(answer),
},
]),
};
}) as unknown as typeof spawn);
}
}
function resolveAsync(options: { packageName?: string; env?: BuildStepEnv; signal?: AbortSignal }) {
return resolveLatestDevicePackageAsync({
packageName: 'expo-device-hub',
env,
logger,
npmRetryDelaysMs: [1, 1],
...options,
});
}
function localPathOf(packageSpec: string): string {
expect(packageSpec).toMatch(/^file:/);
return packageSpec.slice('file:'.length);
}
describe(resolveLatestDevicePackageAsync, () => {
it('runs the mirrored tarball after its sha512 matches the pointer', async () => {
servePointers({ [`${MIRROR}/expo-device-hub/latest.json`]: hubPointer() });
serveFiles({ [`${MIRROR}/expo-device-hub/-/expo-device-hub-0.24.0.tgz`]: HUB_TARBALL });
const resolved = await resolveAsync({});
expect(resolved).toEqual({
packageSpec: expect.stringMatching(/eas-device-package-.*\/expo-device-hub-0\.24\.0\.tgz$/),
description: '[email protected] from the EAS package mirror',
source: 'mirror',
version: '0.24.0',
});
const tarballPath = localPathOf(resolved.packageSpec);
expect(tarballPath.startsWith(os.tmpdir())).toBe(true);
expect(await fs.promises.readFile(tarballPath)).toEqual(HUB_TARBALL);
expect(mockedSpawn).not.toHaveBeenCalled();
expect(logger.info).toHaveBeenCalledWith(
'Using [email protected] from the EAS package mirror.'
);
});
it('reads a scoped package from its npm directory layout', async () => {
const serveSim = Buffer.from('serve-sim 0.14.3');
servePointers({
[`${MIRROR}/@expo/serve-sim/latest.json`]: hubPointer({
name: '@expo/serve-sim',
version: '0.14.3',
tarball: '-/serve-sim-0.14.3.tgz',
integrity: integrityOf(serveSim),
}),
});
serveFiles({ [`${MIRROR}/@expo/serve-sim/-/serve-sim-0.14.3.tgz`]: serveSim });
const resolved = await resolveAsync({ packageName: '@expo/serve-sim' });
expect(resolved.source).toBe('mirror');
expect(localPathOf(resolved.packageSpec)).toMatch(/\/serve-sim-0\.14\.3\.tgz$/);
});
it('reads the mirror from the step env value instead of the default bucket', async () => {
servePointers({ ['https://mirror.test/npm/expo-device-hub/latest.json']: hubPointer() });
serveFiles({
['https://mirror.test/npm/expo-device-hub/-/expo-device-hub-0.24.0.tgz']: HUB_TARBALL,
});
const resolved = await resolveAsync({
env: { ...env, EAS_DEVICE_PACKAGE_MIRROR_URL: 'https://mirror.test/npm/' },
});
expect(resolved.source).toBe('mirror');
});
it('downloads the tarball through the cache proxy, but never the pointer', async () => {
const proxied =
'https://cache.example.com/storage.googleapis.com/turtle-v2/npm/expo-device-hub/-/expo-device-hub-0.24.0.tgz';
servePointers({ [`${MIRROR}/expo-device-hub/latest.json`]: hubPointer() });
serveFiles({ [proxied]: HUB_TARBALL });
const resolved = await resolveAsync({
env: { ...env, EAS_BUILD_COCOAPODS_CACHE_URL: 'https://cache.example.com/' },
});
expect(resolved.source).toBe('mirror');
expect(mockedFetch).toHaveBeenCalledWith(
`${MIRROR}/expo-device-hub/latest.json`,
'GET',
expect.anything()
);
expect(mockedDownload.mock.calls.map(([url]) => url)).toEqual([proxied]);
});
it('downloads the tarball directly when the cache proxy fails', async () => {
servePointers({ [`${MIRROR}/expo-device-hub/latest.json`]: hubPointer() });
serveFiles({ [`${MIRROR}/expo-device-hub/-/expo-device-hub-0.24.0.tgz`]: HUB_TARBALL });
const resolved = await resolveAsync({
env: { ...env, EAS_BUILD_COCOAPODS_CACHE_URL: 'https://cache.example.com' },
});
expect(resolved.source).toBe('mirror');
expect(mockedDownload).toHaveBeenCalledTimes(2);
});
it('downloads the latest release from npm when the mirror has no pointer', async () => {
servePointers({});
npmPackAnswers(NPM_TARBALL);
const resolved = await resolveAsync({});
expect(resolved).toEqual({
packageSpec: expect.stringMatching(/\/expo-device-hub-0\.24\.1\.tgz$/),
description: '[email protected] from npm',
source: 'npm',
version: '0.24.1',
});
expect(await fs.promises.readFile(localPathOf(resolved.packageSpec))).toEqual(NPM_TARBALL);
expect(mockedSpawn).toHaveBeenCalledWith(
'npm',
[
'pack',
'expo-device-hub@latest',
'--pack-destination',
expect.stringContaining('eas-device-package-'),
'--json',
],
expect.objectContaining({ env, stdio: 'pipe' })
);
expect(logger.warn).toHaveBeenCalledWith(
{ err: expect.any(Error) },
'Could not use expo-device-hub from the EAS package mirror. Downloading expo-device-hub@latest from npm.'
);
expect(Sentry.capture).toHaveBeenCalledWith(
'Could not use expo-device-hub from the EAS package mirror',
expect.any(Error),
{ level: 'warning', tags: { packageName: 'expo-device-hub' } }
);
});
it('drops a mirrored tarball whose sha512 does not match and uses npm', async () => {
servePointers({ [`${MIRROR}/expo-device-hub/latest.json`]: hubPointer() });
serveFiles({ [`${MIRROR}/expo-device-hub/-/expo-device-hub-0.24.0.tgz`]: Buffer.from('bad') });
npmPackAnswers(NPM_TARBALL);
const resolved = await resolveAsync({});
expect(resolved.source).toBe('npm');
const directory = path.dirname(localPathOf(resolved.packageSpec));
expect(await fs.promises.readdir(directory)).toEqual(['expo-device-hub-0.24.1.tgz']);
expect(String(jest.mocked(logger.warn).mock.calls[0][0].err)).toContain('not sha512-');
});
it('uses npm when the pointer names another package', async () => {
servePointers({
[`${MIRROR}/expo-device-hub/latest.json`]: hubPointer({ name: '@expo/serve-sim' }),
});
npmPackAnswers(NPM_TARBALL);
const resolved = await resolveAsync({});
expect(resolved.source).toBe('npm');
expect(mockedDownload).not.toHaveBeenCalled();
});
it('tries npm again when the new release is not downloadable yet', async () => {
servePointers({});
npmPackAnswers(new Error('npm error code E404'), NPM_TARBALL);
const resolved = await resolveAsync({});
expect(resolved.description).toBe('[email protected] from npm');
expect(mockedSpawn).toHaveBeenCalledTimes(2);
});
it('leaves expo-device-hub@latest to the package manager when npm keeps failing', async () => {
servePointers({});
npmPackAnswers(
new Error('npm error code E404'),
new Error('npm error code E404'),
new Error('npm error code E404')
);
const resolved = await resolveAsync({});
expect(resolved).toEqual({
packageSpec: 'expo-device-hub@latest',
description: 'expo-device-hub@latest',
source: 'npm',
});
expect(mockedSpawn).toHaveBeenCalledTimes(3);
});
it('stops without a fallback when the startup is aborted', async () => {
const controller = new AbortController();
mockedFetch.mockImplementation((async () => {
controller.abort(new Error('Session stopped.'));
throw new Error('aborted');
}) as unknown as typeof turtleFetch);
await expect(resolveAsync({ signal: controller.signal })).rejects.toThrow('Session stopped.');
expect(mockedSpawn).not.toHaveBeenCalled();
});
});
@@ -32,6 +32,7 @@ import {
startDeviceSessionHostAsync,
waitForWebPreviewReadyAsync,
} from '../deviceSessionHost';
import { resolveLatestDevicePackageAsync } from '../devicePackageMirror';
import { readIosApplicationIdentifierAsync } from '../iosAppArtifact';
import { readLocalEgressHandoffAsync } from '../localEgress';
import {
@@ -72,6 +73,14 @@ jest.mock('../serveSimMetricsRecorder', () => ({
.mockResolvedValue([{ udid: 'emulator-5554', token: 'preview-token' }]),
}));
jest.mock('../../../utils/turtleFetch');
jest.mock('../devicePackageMirror', () => ({
// Sessions run `<name>@latest` unless a test resolves the package from the mirror.
resolveLatestDevicePackageAsync: jest.fn(async ({ packageName }: { packageName: string }) => ({
packageSpec: `${packageName}@latest`,
description: `${packageName}@latest`,
source: 'npm',
})),
}));
jest.mock('../remoteDeviceRunSession', () => ({
...jest.requireActual('../remoteDeviceRunSession'),
ensureFfmpegInstalledOnceAsync: jest.fn(),
@@ -2869,3 +2878,132 @@ it.each([
}
}
);
describe('package source', () => {
const hubTarball = 'file:/tmp/eas-device-package-hub/expo-device-hub-0.24.0.tgz';
const serveSimTarball = 'file:/tmp/eas-device-package-sim/serve-sim-0.14.3.tgz';
it('starts expo-device-hub from the tarball that the mirror resolved', async () => {
jest.mocked(resolveLatestDevicePackageAsync).mockResolvedValueOnce({
packageSpec: hubTarball,
description: '[email protected] from the EAS package mirror',
source: 'mirror',
version: '0.24.0',
});
const host = await startHostAsync();
try {
expect(resolveLatestDevicePackageAsync).toHaveBeenCalledWith(
expect.objectContaining({ packageName: 'expo-device-hub', env })
);
const { command, args } = jest.mocked(spawnDetached).mock.calls[0][0];
expect([command, ...args.slice(0, 2)]).toEqual(['npx', '--yes', hubTarball]);
expect(args).not.toContain('expo-device-hub@latest');
expect(logger.info).toHaveBeenCalledWith(
expect.stringMatching(
/^Launching expo-device-hub@0\.24\.0 from the EAS package mirror on 127\.0\.0\.1:\d+ via npx\.$/
)
);
} finally {
await host.finishAsync();
}
});
it('starts a cold serve-sim from the mirrored tarball and records with the same package', async () => {
jest.mocked(resolveLatestDevicePackageAsync).mockResolvedValueOnce({
packageSpec: serveSimTarball,
description: '@expo/[email protected] from the EAS package mirror',
source: 'mirror',
version: '0.14.3',
});
const recording = jest.spyOn(IosSimulatorRecordingUtils, 'useServeSimPackage');
const host = await startDeviceSessionHostAsync(ctx, {
preview: { baseDomain, authtoken },
runtimePlatform: BuildRuntimePlatform.DARWIN,
env,
logger,
separateLogPhase: true,
timeoutMs: 10_000,
});
try {
expect(resolveLatestDevicePackageAsync).toHaveBeenCalledWith(
expect.objectContaining({ packageName: '@expo/serve-sim' })
);
expect(jest.mocked(spawnDetached).mock.calls[0][0].args.slice(0, 2)).toEqual([
'--yes',
serveSimTarball,
]);
expect(recording).toHaveBeenCalledWith(serveSimTarball);
} finally {
recording.mockRestore();
await host.finishAsync();
}
});
it.each([
['a requested version', { packageVersion: '0.7.0' }, env, '[email protected]'],
[
'bun, which cannot run a local tarball',
{},
{ ...env, EAS_OVERRIDE_PACKAGE_MANAGER: 'bun' },
'expo-device-hub@latest',
],
])('keeps the npm spec for %s', async (_description, options, stepEnv, spec) => {
const host = await startDeviceSessionHostAsync(ctx, {
preview: { baseDomain, authtoken },
runtimePlatform: BuildRuntimePlatform.LINUX,
env: stepEnv,
logger,
separateLogPhase: true,
timeoutMs: 10_000,
...options,
});
try {
expect(resolveLatestDevicePackageAsync).not.toHaveBeenCalled();
expect(jest.mocked(spawnDetached).mock.calls[0][0].args).toContain(spec);
} finally {
await host.finishAsync();
}
});
it('keeps the npm spec of a warm serve-sim, which the launcher installed', async () => {
jest
.mocked(readServeSimServersAsync)
.mockResolvedValue([
{ udid: 'emulator-5554', token: 'preview-token', url: 'http://127.0.0.1:3200' },
]);
const startAsync = jest.fn(async () => ({
pid: undefined,
getOutput: () => '',
getExitError: () => undefined,
stopAsync: stopServer,
}));
const host = await startDeviceSessionHostAsync(
ctx,
{
preview: { baseDomain, authtoken },
runtimePlatform: BuildRuntimePlatform.DARWIN,
env,
logger,
iosSimulatorUdid: 'emulator-5554',
timeoutMs: 1000,
},
{
port: 3200,
turnArgs: Promise.resolve([]),
requiresPreviewRetirement: true,
startAsync,
stopAsync: stopServer,
}
);
try {
expect(resolveLatestDevicePackageAsync).not.toHaveBeenCalled();
expect(startAsync).toHaveBeenCalledWith(
expect.objectContaining({
args: expect.arrayContaining(['@expo/serve-sim@latest']),
})
);
} finally {
await host.finishAsync();
}
});
});
@@ -72,6 +72,14 @@ jest.mock('../localEgress', () => ({
jest.mock('node:timers');
jest.mock('node:timers/promises');
jest.mock('../../../utils/turtleFetch');
jest.mock('../devicePackageMirror', () => ({
// Sessions run `<name>@latest` unless a test resolves the package from the mirror.
resolveLatestDevicePackageAsync: jest.fn(async ({ packageName }: { packageName: string }) => ({
packageSpec: `${packageName}@latest`,
description: `${packageName}@latest`,
source: 'npm',
})),
}));
jest.mock('../../../utils/retry', () => ({ sleepAsync: jest.fn() }));
jest.mock('../../../sentry');
jest.mock('@expo/turtle-spawn');
@@ -0,0 +1,224 @@
import downloadFile from '@expo/downloader';
import type { bunyan } from '@expo/logger';
import type { BuildStepEnv } from '@expo/steps';
import spawn from '@expo/turtle-spawn';
import { createHash } from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import semver from 'semver';
import { z } from 'zod';
import { Sentry } from '../../sentry';
import { getProxiedDownloadUrl } from '../../utils/download';
import { sleepAsync } from '../../utils/retry';
import { turtleFetch } from '../../utils/turtleFetch';
// npm can list a new expo-device-hub or serve-sim release before it serves the tarball, for
// example while the npm security scan runs, and a session that starts then fails. The
// expo-device-hub release copies each release into this bucket and moves `<name>/latest.json`
// after it checked the copy against npm's `dist.integrity` (expo/expo-device-hub LLP 0019). So a
// session reads the copy first, and npm second.
export const DEVICE_PACKAGE_MIRROR_BASE_URL = 'https://storage.googleapis.com/turtle-v2/npm';
/** A step env value that replaces the mirror base URL, like `SERVE_EMU_SCRCPY_BASE_URL`. */
export const DEVICE_PACKAGE_MIRROR_URL_ENV = 'EAS_DEVICE_PACKAGE_MIRROR_URL';
const POINTER_TIMEOUT_MS = 10_000;
const TARBALL_TIMEOUT_MS = 120_000;
const NPM_PACK_TIMEOUT_MS = 120_000;
const DEFAULT_NPM_RETRY_DELAYS_MS = [5_000, 15_000];
const MirrorPointerSchema = z.object({
name: z.string(),
version: z.string().refine(version => semver.valid(version) !== null),
tarball: z.string().regex(/^-\/[A-Za-z0-9][A-Za-z0-9._-]*\.tgz$/),
integrity: z.string().regex(/^sha512-[A-Za-z0-9+/]+={0,2}$/),
});
const NpmPackOutputSchema = z
.array(z.object({ name: z.string(), version: z.string(), filename: z.string() }))
.min(1);
export type DevicePackageSource = 'mirror' | 'npm';
export type ResolvedDevicePackage = {
/** What the package manager runs: a local tarball (`file:`) or `<name>@latest`. */
packageSpec: string;
/** For logs, for example `[email protected] from the EAS package mirror`. */
description: string;
source: DevicePackageSource;
version?: string;
};
/**
* Downloads the latest release of a device session package: from the EAS package mirror after
* the sha512 check, else from npm with retries. When both fail, it returns `<name>@latest`, which
* the package manager resolves as before.
*
* The tarball stays in a temporary directory until the job ends: iOS recorders start serve-sim
* from the same spec during the whole session.
*/
export async function resolveLatestDevicePackageAsync({
packageName,
env,
logger,
signal,
npmRetryDelaysMs = DEFAULT_NPM_RETRY_DELAYS_MS,
}: {
packageName: string;
env: BuildStepEnv;
logger: bunyan;
signal?: AbortSignal;
npmRetryDelaysMs?: number[];
}): Promise<ResolvedDevicePackage> {
const directory = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'eas-device-package-'));
try {
const { tarballPath, version } = await downloadFromMirrorAsync({
packageName,
directory,
env,
signal,
});
const description = `${packageName}@${version} from the EAS package mirror`;
logger.info(`Using ${description}.`);
return { packageSpec: `file:${tarballPath}`, description, source: 'mirror', version };
} catch (err) {
signal?.throwIfAborted();
logger.warn(
{ err },
`Could not use ${packageName} from the EAS package mirror. Downloading ${packageName}@latest from npm.`
);
Sentry.capture(`Could not use ${packageName} from the EAS package mirror`, toError(err), {
level: 'warning',
tags: { packageName },
});
}
try {
const { tarballPath, version } = await packFromNpmAsync({
packageName,
directory,
env,
signal,
retryDelaysMs: npmRetryDelaysMs,
});
const description = `${packageName}@${version} from npm`;
logger.info(`Using ${description}.`);
return { packageSpec: `file:${tarballPath}`, description, source: 'npm', version };
} catch (err) {
signal?.throwIfAborted();
logger.warn(
{ err },
`Could not download ${packageName}@latest from npm. The package manager resolves ${packageName}@latest itself.`
);
}
return {
packageSpec: `${packageName}@latest`,
description: `${packageName}@latest`,
source: 'npm',
};
}
async function downloadFromMirrorAsync({
packageName,
directory,
env,
signal,
}: {
packageName: string;
directory: string;
env: BuildStepEnv;
signal?: AbortSignal;
}): Promise<{ tarballPath: string; version: string }> {
const baseUrl = (env[DEVICE_PACKAGE_MIRROR_URL_ENV] || DEVICE_PACKAGE_MIRROR_BASE_URL).replace(
/\/+$/,
''
);
// The pointer is never read through the cache proxy, which could serve an old release.
const response = await turtleFetch(`${baseUrl}/${packageName}/latest.json`, 'GET', {
retries: 2,
timeout: POINTER_TIMEOUT_MS,
signal,
});
const pointer = MirrorPointerSchema.parse(await response.json());
if (pointer.name !== packageName) {
throw new Error(`The mirror pointer names ${pointer.name}, not ${packageName}.`);
}
const tarballUrl = `${baseUrl}/${packageName}/${pointer.tarball}`;
const tarballPath = path.join(directory, path.posix.basename(pointer.tarball));
// A tarball never changes after the upload, so the iOS cache proxy can serve it.
const proxiedUrl = getProxiedDownloadUrl({
directUrl: tarballUrl,
proxyBaseUrl: env.EAS_BUILD_COCOAPODS_CACHE_URL,
});
let downloaded = false;
if (proxiedUrl) {
downloaded = await downloadFile(proxiedUrl, tarballPath, {
retry: 1,
timeout: TARBALL_TIMEOUT_MS,
}).then(
() => true,
() => false
);
}
signal?.throwIfAborted();
if (!downloaded) {
await downloadFile(tarballUrl, tarballPath, { retry: 2, timeout: TARBALL_TIMEOUT_MS });
}
signal?.throwIfAborted();
const integrity = await sha512IntegrityAsync(tarballPath);
if (integrity !== pointer.integrity) {
await fs.promises.rm(tarballPath, { force: true });
throw new Error(
`${packageName}@${pointer.version} from the mirror has sha512 ${integrity}, not ${pointer.integrity}.`
);
}
return { tarballPath, version: pointer.version };
}
/** `npm pack` uses the job's npm configuration and checks the tarball against npm's integrity. */
async function packFromNpmAsync({
packageName,
directory,
env,
signal,
retryDelaysMs,
}: {
packageName: string;
directory: string;
env: BuildStepEnv;
signal?: AbortSignal;
retryDelaysMs: number[];
}): Promise<{ tarballPath: string; version: string }> {
let lastError: unknown;
for (let attempt = 0; attempt <= retryDelaysMs.length; attempt++) {
if (attempt > 0) {
await sleepAsync(retryDelaysMs[attempt - 1]);
}
signal?.throwIfAborted();
try {
const { stdout } = await spawn(
'npm',
['pack', `${packageName}@latest`, '--pack-destination', directory, '--json'],
{ cwd: directory, env, signal, stdio: 'pipe', timeout: NPM_PACK_TIMEOUT_MS }
);
const [packed] = NpmPackOutputSchema.parse(JSON.parse(stdout));
return { tarballPath: path.join(directory, packed.filename), version: packed.version };
} catch (err) {
signal?.throwIfAborted();
lastError = err;
}
}
throw lastError;
}
async function sha512IntegrityAsync(filePath: string): Promise<string> {
const hash = createHash('sha512');
for await (const chunk of fs.createReadStream(filePath)) {
hash.update(chunk);
}
return `sha512-${hash.digest('base64')}`;
}
function toError(err: unknown): Error {
return err instanceof Error ? err : new Error(String(err));
}
@@ -60,6 +60,7 @@ import { type PreviewActivityPolling, startPreviewActivityPolling } from './prev
import { verifyLocalEgressGuardAsync } from './localEgressGuard';
import { type IosSimulatorUuid } from '../../utils/IosSimulatorUtils';
import { createColdIosSessionAsync } from './coldIosSession';
import { resolveLatestDevicePackageAsync } from './devicePackageMirror';
import { createStartupTasks } from './startupTasks';
const WEB_PREVIEW_HOST = '127.0.0.1';
@@ -145,6 +146,7 @@ export function createServeSimArgs({
shareUrl,
disableShare = false,
packageVersion,
packageSpec,
iosSimulatorUdid,
installAppPath,
launchAppIdentifier,
@@ -162,6 +164,8 @@ export function createServeSimArgs({
shareUrl?: string;
disableShare?: boolean;
packageVersion?: string;
/** Replaces `@expo/serve-sim@<packageVersion>`, for example with a downloaded tarball. */
packageSpec?: string;
iosSimulatorUdid?: string;
installAppPath?: string;
networkCapture?: boolean;
@@ -169,7 +173,7 @@ export function createServeSimArgs({
networkCaptureProxy?: string;
} & ServeSimLaunchOptions): string[] {
return [
createServeSimPackageSpec(packageVersion),
packageSpec ?? createServeSimPackageSpec(packageVersion),
...(iosSimulatorUdid ? [iosSimulatorUdid] : []),
...(iosSimulatorUdid && IOS_SIMULATOR_UDID.test(iosSimulatorUdid)
? ['--single-device', iosSimulatorUdid]
@@ -221,6 +225,7 @@ export function createExpoDeviceHubArgs({
frameAncestorArgs: frameArgs = [],
corsOriginArgs: corsArgs = [],
packageVersion,
packageSpec,
recordingDirectory,
}: {
port: number;
@@ -230,10 +235,12 @@ export function createExpoDeviceHubArgs({
frameAncestorArgs?: string[];
corsOriginArgs?: string[];
packageVersion?: string;
/** Replaces `expo-device-hub@<packageVersion>`, for example with a downloaded tarball. */
packageSpec?: string;
recordingDirectory?: string;
}): string[] {
return [
createExpoDeviceHubPackageSpec(packageVersion),
packageSpec ?? createExpoDeviceHubPackageSpec(packageVersion),
...(device && ANDROID_DEVICE_SERIAL.test(device) ? ['--single-device', device] : []),
'--port',
String(port),
@@ -609,9 +616,10 @@ async function startDeviceSessionHostInternalAsync(
const port = server.port;
packageVersion = server.serveSimVersion ?? packageVersion;
const serverName = isAndroid ? 'expo-device-hub' : 'serve-sim';
const packageSpec = isAndroid
let packageSpec = isAndroid
? createExpoDeviceHubPackageSpec(packageVersion)
: createServeSimPackageSpec(packageVersion);
let packageDescription = packageSpec;
const turnArgsResult = asyncResult(server.turnArgs);
const screenshots = await startDeviceRunSessionScreenshotsAsync(ctx, {
deviceRunSessionId: getDeviceRunSessionIdOrThrow(env),
@@ -742,14 +750,31 @@ async function startDeviceSessionHostInternalAsync(
try {
const turnArgs = (await turnArgsResult).enforceValue();
const localEgress = !isAndroid ? await readLocalEgressHandoffAsync() : null;
const packageManager = resolveConfiguredPackageManager(env, PackageManager.NPM);
// The latest release comes from the EAS package mirror first, so a release that npm lists
// but does not serve yet does not stop the session. A requested version and a warm server
// keep their npm spec, and `bun x` cannot run a local tarball.
if (packageVersion === undefined && !providedServer && packageManager !== PackageManager.BUN) {
const resolved = await startup.untilAborted(
resolveLatestDevicePackageAsync({
packageName: isAndroid ? EXPO_DEVICE_HUB_PACKAGE_NAME : SERVE_SIM_PACKAGE_NAME,
env,
logger,
signal: startup.signal,
})
);
packageSpec = resolved.packageSpec;
packageDescription = resolved.description;
}
const previewExec = resolvePackageExec(
resolveConfiguredPackageManager(env, PackageManager.NPM),
packageManager,
isAndroid
? createExpoDeviceHubArgs({
port,
device: previewDevice,
turnArgs,
packageVersion,
packageSpec,
recordingDirectory: recording?.directory,
websiteArgs: websiteOriginArgs(env),
frameAncestorArgs: frameAncestorArgs(frameAncestors),
@@ -759,6 +784,7 @@ async function startDeviceSessionHostInternalAsync(
port,
turnArgs,
packageVersion,
packageSpec,
iosSimulatorUdid: previewDevice,
websiteArgs: websiteOriginArgs(env),
frameAncestorArgs: frameAncestorArgs(frameAncestors),
@@ -778,7 +804,7 @@ async function startDeviceSessionHostInternalAsync(
})
);
logger.info(
`Launching ${packageSpec} on ${WEB_PREVIEW_HOST}:${port} via ${previewExec.command}.`
`Launching ${packageDescription} on ${WEB_PREVIEW_HOST}:${port} via ${previewExec.command}.`
);
// Redact these credentials before forwarding process output to build logs.
secrets.push(