Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/npm-token-user-npmrc.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@expo/build-tools': patch
'@expo/worker': patch
---

Put the `NPM_TOKEN` registry credential in the builder's npm user config on EAS Build (`~/.npmrc`, or the file `NPM_CONFIG_USERCONFIG` names), where pnpm 10.34.2+ and 11.5.3+ still expand `${NPM_TOKEN}` (they ignore it in a project-level `.npmrc`). Explain what to change when the project's pnpm version needs a newer Node.js than the build runs, including when eas.json sets `node` or `pnpm`.
25 changes: 25 additions & 0 deletions packages/build-tools/src/buildErrors/__tests__/detectError.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,31 @@ describe(resolveBuildPhaseErrorAsync, () => {
expect(err.trackingCode).toBeUndefined();
});

it('explains that the pnpm version needs a newer Node.js than the build runs', async () => {
const fakeError = new Error();
const err = await resolveBuildPhaseErrorAsync(
fakeError,
[
'Running "pnpm install --frozen-lockfile" in /home/expo/workingdir/build directory',
'warn: This version of pnpm requires at least Node.js v22.13',
'warn: The current version of Node.js is v20.19.4',
'warn: Visit https://r.pnpm.io/comp to see the list of past pnpm versions with respective Node.js version support.',
'Error [ERR_UNKNOWN_BUILTIN_MODULE]: No such built-in module: node:sqlite',
],
{
job: { platform: Platform.ANDROID } as Job,
phase: BuildPhase.INSTALL_DEPENDENCIES,
env: {},
},
'/fake/path'
);
expect(err.errorCode).toBe('EAS_BUILD_PNPM_UNSUPPORTED_NODE_VERSION_ERROR');
expect(err.message).toBe(
'This build uses a pnpm version that requires Node.js 22.13.0 or newer, but runs Node.js 20.19.4. You can fix it by either:\n- setting "node" to "22.13.0" or a newer version in the build profile in eas.json\n- using a pnpm version that supports Node.js 20.19.4: change "packageManager" in package.json if your project sets it, and set "pnpm" in the build profile in eas.json'
);
expect(err.docsUrl).toBe('https://docs.expo.dev/eas/json/');
});

it('detects xcode line error', async () => {
vol.fromJSON({
'/path/to/xcodelogs.log': originalFs.readFileSync(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { errors } from '@expo/eas-build-job';
import nullthrows from 'nullthrows';
import semver from 'semver';

import { ErrorHandler } from './errors.types';

// example log: "warn: This version of pnpm requires at least Node.js v22.13" followed by "warn: The current version of Node.js is v20.19.4"
const PNPM_UNSUPPORTED_NODE_VERSION_REGEXP =
/This version of pnpm requires at least Node\.js v([\d.]+)\n.*The current version of Node\.js is v([\d.]+)/;

function createPnpmUnsupportedNodeVersionError(matchResult: RegExpMatchArray): errors.UserError {
const [, requiredNodeVersion, currentNodeVersion] = matchResult;
const minimumNodeVersion = nullthrows(semver.coerce(requiredNodeVersion)).version;
return new errors.UserError(
'EAS_BUILD_PNPM_UNSUPPORTED_NODE_VERSION_ERROR',
`This build uses a pnpm version that requires Node.js ${minimumNodeVersion} or newer, but runs Node.js ${currentNodeVersion}. You can fix it by either:
- setting "node" to "${minimumNodeVersion}" or a newer version in the build profile in eas.json
- using a pnpm version that supports Node.js ${currentNodeVersion}: change "packageManager" in package.json if your project sets it, and set "pnpm" in the build profile in eas.json`,
{ docsUrl: 'https://docs.expo.dev/eas/json/' }
);
}

export const pnpmUnsupportedNodeVersionErrorHandler: ErrorHandler<errors.UserError> = {
regexp: PNPM_UNSUPPORTED_NODE_VERSION_REGEXP,
createError: createPnpmUnsupportedNodeVersionError,
};

export function detectPnpmUnsupportedNodeVersionError(
output: string
): errors.UserError | undefined {
const match = output.match(PNPM_UNSUPPORTED_NODE_VERSION_REGEXP);
return match ? createPnpmUnsupportedNodeVersionError(match) : undefined;
}
2 changes: 2 additions & 0 deletions packages/build-tools/src/buildErrors/userErrorHandlers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { BuildMode, BuildPhase, Platform, Workflow, errors } from '@expo/eas-build-job';

import { ErrorHandler, XCODE_BUILD_PHASE } from './errors.types';
import { pnpmUnsupportedNodeVersionErrorHandler } from './pnpmUnsupportedNodeVersionError';

import UserError = errors.UserError;

Expand Down Expand Up @@ -211,6 +212,7 @@ You are seeing this error because either:
return undefined;
},
},
pnpmUnsupportedNodeVersionErrorHandler,
{
platform: Platform.IOS,
phase: XCODE_BUILD_PHASE,
Expand Down
7 changes: 6 additions & 1 deletion packages/build-tools/src/common/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,12 @@ export async function setupAsync<TJob extends BuildJob>(
}
);

await setUpNpmrcAsync(ctx, ctx.logger);
await setUpNpmrcAsync({
projectTargetDirectory: ctx.buildDirectory,
workingDirectory: ctx.getReactNativeProjectDirectory(),
env: ctx.env,
logger: ctx.logger,
});
if (ctx.job.platform === Platform.IOS && ctx.env.EAS_BUILD_RUNNER === 'eas-build') {
await deleteXcodeEnvLocalIfExistsAsync(ctx as BuildContext<Ios.Job>);
}
Expand Down
1 change: 1 addition & 0 deletions packages/build-tools/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export { formatSecondsForLog } from './utils/formatDuration';
export { findAndUploadXcodeBuildLogsAsync } from './ios/xcodeBuildLogs';

export { Hook, runHookIfPresent } from './utils/hooks';
export { detectPnpmUnsupportedNodeVersionError } from './buildErrors/pnpmUnsupportedNodeVersionError';

export { parseGradleProfile, formatGradleProfileReport } from './android/gradleProfile';
export type { GradleProfileTask } from './android/gradleProfile';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import spawn from '@expo/turtle-spawn';
import { vol } from 'memfs';

import { createGlobalContextMock } from '../../../__tests__/utils/context';
import { NpmrcAuthTokenLine } from '../../../templates/npmrc';
import { createSetUpNpmrcBuildFunction } from '../useNpmToken';

jest.mock('fs');
jest.mock('@expo/turtle-spawn', () => ({ __esModule: true, default: jest.fn() }));

const projectTargetDirectory = '/workingdir/project';
const homeDirectory = '/home/expo';

describe(createSetUpNpmrcBuildFunction, () => {
beforeEach(async () => {
vol.reset();
await vol.promises.mkdir(projectTargetDirectory, { recursive: true });
await vol.promises.mkdir(homeDirectory, { recursive: true });
jest.mocked(spawn).mockResolvedValue({ stdout: `${homeDirectory}/.npmrc\n` } as never);
});

afterEach(() => {
jest.restoreAllMocks();
});

it('adds the NPM_TOKEN placeholder from the step env to ~/.npmrc on EAS Build', async () => {
const globalCtx = createGlobalContextMock({ projectTargetDirectory });
globalCtx.updateEnv({ NPM_TOKEN: 'npm_secret_token', EAS_BUILD_RUNNER: 'eas-build' });
const step = createSetUpNpmrcBuildFunction().createBuildStepFromFunctionCall(globalCtx, {
callInputs: {},
});

await step.executeAsync();

expect(await vol.promises.readFile(`${homeDirectory}/.npmrc`, 'utf8')).toContain(
NpmrcAuthTokenLine
);
});
});
33 changes: 7 additions & 26 deletions packages/build-tools/src/steps/functions/useNpmToken.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import { BuildFunction } from '@expo/steps';
import fs from 'fs-extra';
import path from 'path';

import { NpmrcTemplate } from '../../templates/npmrc';
import { findPackagerRootDir } from '../../utils/packageManager';
import { setUpNpmrcAsync } from '../../utils/npmrc';

export function createSetUpNpmrcBuildFunction(): BuildFunction {
return new BuildFunction({
Expand All @@ -12,28 +9,12 @@ export function createSetUpNpmrcBuildFunction(): BuildFunction {
name: 'Use NPM_TOKEN',
__metricsId: 'eas/use_npm_token',
fn: async (stepCtx, { env }) => {
const { logger } = stepCtx;
if (env.NPM_TOKEN) {
logger.info('We detected that you set the NPM_TOKEN environment variable');
const projectNpmrcPath = path.join(stepCtx.global.projectTargetDirectory, '.npmrc');
if (await fs.pathExists(projectNpmrcPath)) {
logger.info('.npmrc already exists in your project directory, skipping generation');
} else {
logger.info('Creating .npmrc in your project directory with the following contents:');
logger.info(NpmrcTemplate);
await fs.writeFile(projectNpmrcPath, NpmrcTemplate);
}
} else {
const projectNpmrcPath = path.join(findPackagerRootDir(stepCtx.workingDirectory), '.npmrc');
if (await fs.pathExists(projectNpmrcPath)) {
logger.info(
`.npmrc found at ${path.relative(
stepCtx.global.projectTargetDirectory,
projectNpmrcPath
)}`
);
}
}
await setUpNpmrcAsync({
projectTargetDirectory: stepCtx.global.projectTargetDirectory,
workingDirectory: stepCtx.workingDirectory,
env,
logger: stepCtx.logger,
});
},
});
}
4 changes: 3 additions & 1 deletion packages/build-tools/src/templates/npmrc.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
export const NpmrcTemplate = `//registry.npmjs.org/:_authToken=\${NPM_TOKEN}
export const NpmrcAuthTokenLine = '//registry.npmjs.org/:_authToken=${NPM_TOKEN}';

export const NpmrcTemplate = `${NpmrcAuthTokenLine}
registry=https://registry.npmjs.org/
`;
120 changes: 120 additions & 0 deletions packages/build-tools/src/utils/__tests__/npmrc.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import spawn from '@expo/turtle-spawn';
import { vol } from 'memfs';

import { createMockLogger } from '../../__tests__/utils/logger';
import { NpmrcAuthTokenLine, NpmrcTemplate } from '../../templates/npmrc';
import { setUpNpmrcAsync } from '../npmrc';

jest.mock('fs');
jest.mock('@expo/turtle-spawn', () => ({ __esModule: true, default: jest.fn() }));

const projectTargetDirectory = '/workingdir/build';
const homeDirectory = '/home/expo';

describe(setUpNpmrcAsync, () => {
beforeEach(async () => {
vol.reset();
await vol.promises.mkdir(projectTargetDirectory, { recursive: true });
await vol.promises.mkdir(homeDirectory, { recursive: true });
jest.mocked(spawn).mockResolvedValue({ stdout: `${homeDirectory}/.npmrc\n` } as never);
});

afterEach(() => {
jest.restoreAllMocks();
});

it('adds the NPM_TOKEN placeholder to ~/.npmrc on EAS Build and leaves the project .npmrc alone', async () => {
const projectContents = '//npm.pkg.github.com/:_authToken=${GITHUB_TOKEN}\n';
await vol.promises.writeFile(`${projectTargetDirectory}/.npmrc`, projectContents);
await vol.promises.writeFile(`${homeDirectory}/.npmrc`, 'fund=false');

await setUpNpmrcAsync({
projectTargetDirectory,
workingDirectory: projectTargetDirectory,
env: { NPM_TOKEN: 'npm_secret_token', EAS_BUILD_RUNNER: 'eas-build' },
logger: createMockLogger(),
});

expect(await vol.promises.readFile(`${homeDirectory}/.npmrc`, 'utf8')).toBe(
`fund=false\n${NpmrcAuthTokenLine}\n`
);
expect(await vol.promises.readFile(`${projectTargetDirectory}/.npmrc`, 'utf8')).toBe(
projectContents
);
});

it('adds the NPM_TOKEN placeholder to the user config file npm resolves from the build env', async () => {
await vol.promises.mkdir(`${homeDirectory}/npm`, { recursive: true });
jest.mocked(spawn).mockResolvedValueOnce({ stdout: `${homeDirectory}/npm/npmrc\n` } as never);
const env = {
NPM_TOKEN: 'npm_secret_token',
EAS_BUILD_RUNNER: 'eas-build',
NPM_CONFIG_USERCONFIG: '~/npm/npmrc',
};

await setUpNpmrcAsync({
projectTargetDirectory,
workingDirectory: projectTargetDirectory,
env,
logger: createMockLogger(),
});

expect(spawn).toHaveBeenCalledWith(
'npm',
['config', 'get', 'userconfig'],
expect.objectContaining({ cwd: projectTargetDirectory, env })
);
expect(await vol.promises.readFile(`${homeDirectory}/npm/npmrc`, 'utf8')).toBe(
`\n${NpmrcAuthTokenLine}\n`
);
expect(vol.existsSync(`${homeDirectory}/.npmrc`)).toBe(false);
});

it('creates the project .npmrc and leaves the user npmrc alone on local builds', async () => {
await setUpNpmrcAsync({
projectTargetDirectory,
workingDirectory: projectTargetDirectory,
env: { NPM_TOKEN: 'npm_secret_token', EAS_BUILD_RUNNER: 'local-build-plugin' },
logger: createMockLogger(),
});

expect(await vol.promises.readFile(`${projectTargetDirectory}/.npmrc`, 'utf8')).toBe(
NpmrcTemplate
);
expect(vol.existsSync(`${homeDirectory}/.npmrc`)).toBe(false);
});

it('leaves an existing project .npmrc untouched on local builds', async () => {
const existingContents = 'registry=https://registry.example.com/\n';
await vol.promises.writeFile(`${projectTargetDirectory}/.npmrc`, existingContents);

await setUpNpmrcAsync({
projectTargetDirectory,
workingDirectory: projectTargetDirectory,
env: { NPM_TOKEN: 'npm_secret_token', EAS_BUILD_RUNNER: 'local-build-plugin' },
logger: createMockLogger(),
});

expect(await vol.promises.readFile(`${projectTargetDirectory}/.npmrc`, 'utf8')).toBe(
existingContents
);
});

it('reports an existing .npmrc when NPM_TOKEN is not set', async () => {
const logger = createMockLogger();
await vol.promises.writeFile(
`${projectTargetDirectory}/.npmrc`,
'registry=https://registry.example.com/\n'
);

await setUpNpmrcAsync({
projectTargetDirectory,
workingDirectory: projectTargetDirectory,
env: { EAS_BUILD_RUNNER: 'eas-build' },
logger,
});

expect(logger.info).toHaveBeenCalledWith('.npmrc found at .npmrc');
expect(vol.existsSync(`${homeDirectory}/.npmrc`)).toBe(false);
});
});
Loading
Loading