fix(iOS): keep prebuilt Headers/ in place on a Debug/Release swap (#57814)

Summary:
Fixes https://github.com/react/react-native/issues/57803. An iOS Release build can fail in `PrecompileModule React` with seven `include of non-modular header inside framework module` errors — but only when the build follows a Debug/Release configuration switch.

`replace-rncore-version.js` deleted and recreated `Pods/React-Core-prebuilt/Headers/` on a swap. That directory holds `module.modulemap`, which `rncore.rb` activates on every target through `-fmodule-map-file`. Nothing orders an unrelated target's dependency scan against this script phase, so a scan can run while the module map is missing. The React module is then precompiled without it, and `<yoga/...>`, `<react/...>` and `<RCTDeprecation/...>` resolve non-modularly.

Those headers never needed replacing. The prebuild compose job emits one set of ReactNativeHeaders for both configurations, so they are identical in the Debug and Release tarballs — only the compiled framework differs. This replaces `React.xcframework` and nothing else.

## Changelog:

[IOS] [FIXED] - Keep the prebuilt `Headers/` in place on a Debug/Release configuration switch so the React explicit module still resolves its module map

Pull Request resolved: https://github.com/react/react-native/pull/57814

Test Plan:
The premise, on the published 0.87.0-rc.3 artifacts (`ios-arm64_x86_64-simulator`):

| compared between the Debug and Release tarballs | result |
| --- | --- |
| `ReactNativeHeaders…/Headers/module.modulemap` | identical |
| `React.framework/Modules/module.modulemap` | identical |
| `ReactNativeHeaders…/Headers` tree (`diff -rq`) | 0 differences |
| `React.framework/Headers` tree (`diff -rq`) | 0 differences |

The reproducer from https://github.com/react/react-native/issues/57803, on Xcode 26.3 with CocoaPods 1.15.2:

| build | result |
| --- | --- |
| 0.87.0-rc.3 | **FAIL** — exit 65, 7 errors |
| 0.87.0-rc.3 + this PR | **PASS** — `** BUILD SUCCEEDED **`, 0 errors |

The swap still does its job in the passing build — it logs `Replacing React-Core-prebuilt/React.xcframework`, and the installed binary is the Release one:

```
installed:   55225ccbc283c57c614ff4caf263cb63bad3828240e62cee8893e7001774bd6c
rc3 release: 55225ccbc283c57c614ff4caf263cb63bad3828240e62cee8893e7001774bd6c
rc3 debug:   516215801a6f8a86640aae13c2f2de1bbdb95189edf124e208f528b1497c7e4c
```

A Release→Debug swap was verified the same way. Across a swap, `Headers/module.modulemap` keeps its inode while `React.xcframework` gets a new one.

## Unit tests

Adds a unit test for the script, 4 cases: correct framework installed, `Headers/module.modulemap` untouched, an Expo-generated `React-use-frameworks.modulemap` left in place, and a fail-closed case on a tarball with no `React.xcframework`. The script needed a `require.main === module` guard and one export to be importable.

```
js1 test xplat/js/react-native-github/packages/react-native/scripts/__tests__/replace-rncore-version-test.js
→ 4 passed, 4 total
```

The module-map case is a real regression test, not just a pin. Restoring the pre-fix delete-and-recreate makes it fail on the inode assertion while the other three keep passing:

```
✕ leaves Headers/module.modulemap untouched
  Expected: 735095485
  Received: 735095515
```

That only works because the fixture tarball also ships `ReactNativeHeaders.xcframework`. Without it the pre-fix code throws its fail-closed error before reaching the assertion, so the test would go red for the wrong reason and would not actually be guarding #57803.

The Expo case covers behaviour this diff removes the explicit protection for. The old save-and-restore of `React-use-frameworks.modulemap` (ada39220a0) is unnecessary now that only `React.xcframework` is replaced, but nothing else pins it.

## Argument parsing

`yargs` parsing moved inside the `require.main === module` guard, so importing the module no longer parses `process.argv`. Verified in both directions.

The command line still performs the swap end to end:

```
$ node replace-rncore-version.js -c Release -r <version> -p <podsRoot>
Replacing React-Core-prebuilt/React.xcframework
Updating React-Core-prebuilt/.last_build_configuration with Release
Done replacing React Native prebuilt

installed binary: binary-Release
module.modulemap inode before=735141703 after=735141703
last_build marker: Release
```

Importing with hostile argv (`-c` collides with jest's `--config`) has no side effects:

```
$ node -e "process.argv = ['node','jest','-c','jest.config.js','--version']; require('./replace-rncore-version.js')"
imported OK, exports: replaceRNCoreConfiguration
```

`arc lint` is clean on both files.

Reviewed By: zeyap

Differential Revision: D114735639

Pulled By: fabriziocucci

fbshipit-source-id: 35ead7dae9ce7ad7160005a15ecb3975817ae728
This commit is contained in:
Christian Falch
2026-08-04 20:20:03 +00:00
committed by React Native Bot
parent 329f8640bf
commit 24353daa87
2 changed files with 190 additions and 125 deletions
@@ -0,0 +1,141 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @noflow
*/
'use strict';
const {replaceRNCoreConfiguration} = require('../replace-rncore-version');
const {execFileSync} = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const VERSION = '0.87.0-test';
const SLICE = 'ios-arm64_x86_64-simulator';
const BINARY = path.join(SLICE, 'React.framework', 'React');
function writeFile(filePath, contents) {
fs.mkdirSync(path.dirname(filePath), {recursive: true});
fs.writeFileSync(filePath, contents);
}
function buildTarball(podsRoot, configuration) {
const stage = fs.mkdtempSync(path.join(podsRoot, `stage-${configuration}-`));
writeFile(path.join(stage, 'React.xcframework', 'Info.plist'), '<plist/>');
writeFile(
path.join(stage, 'React.xcframework', BINARY),
`binary-${configuration}`,
);
// The tarball must also ship ReactNativeHeaders: without it the pre-fix code
// throws its fail-closed error before reaching the module map, so the
// regression test below would pass for the wrong reason.
writeFile(
path.join(
stage,
'ReactNativeHeaders.xcframework',
SLICE,
'Headers',
'module.modulemap',
),
'module yoga {}\n',
);
const artifacts = path.join(podsRoot, 'ReactNativeCore-artifacts');
fs.mkdirSync(artifacts, {recursive: true});
execFileSync('tar', [
'-czf',
path.join(
artifacts,
`reactnative-core-${VERSION.toLowerCase()}-${configuration.toLowerCase()}.tar.gz`,
),
'-C',
stage,
'.',
]);
fs.rmSync(stage, {recursive: true, force: true});
}
describe('replaceRNCoreConfiguration', () => {
let podsRoot;
let pod;
let cwd;
beforeEach(() => {
podsRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'rncore-test-'));
pod = path.join(podsRoot, 'React-Core-prebuilt');
// What the podspec prepare_command leaves behind after `pod install`.
writeFile(
path.join(pod, 'Headers', 'module.modulemap'),
'module yoga {}\n',
);
writeFile(path.join(pod, 'React.xcframework', 'Info.plist'), '<plist/>');
writeFile(path.join(pod, 'React.xcframework', BINARY), 'binary-Debug');
buildTarball(podsRoot, 'Release');
cwd = process.cwd();
// The script phase runs with Pods/ as its working directory.
process.chdir(podsRoot);
});
afterEach(() => {
process.chdir(cwd);
fs.rmSync(podsRoot, {recursive: true, force: true});
});
it('installs the framework for the requested configuration', () => {
replaceRNCoreConfiguration('Release', VERSION, podsRoot);
expect(
fs.readFileSync(path.join(pod, 'React.xcframework', BINARY), 'utf8'),
).toBe('binary-Release');
});
// Regression test for #57803: recreating the module map mid-build lets a
// concurrent dependency scan miss it, and the React module then precompiles
// without -fmodule-map-file and fails on non-modular includes.
it('leaves Headers/module.modulemap untouched', () => {
const moduleMap = path.join(pod, 'Headers', 'module.modulemap');
const before = fs.statSync(moduleMap).ino;
const contentsBefore = fs.readFileSync(moduleMap, 'utf8');
replaceRNCoreConfiguration('Release', VERSION, podsRoot);
expect(fs.statSync(moduleMap).ino).toBe(before);
expect(fs.readFileSync(moduleMap, 'utf8')).toBe(contentsBefore);
});
// The swap used to purge every directory and restore this file by hand. It
// now replaces React.xcframework alone, so the file is never disturbed.
it('leaves an Expo-generated React-use-frameworks.modulemap in place', () => {
const expoModuleMap = path.join(pod, 'React-use-frameworks.modulemap');
writeFile(expoModuleMap, 'module React {}\n');
replaceRNCoreConfiguration('Release', VERSION, podsRoot);
expect(fs.readFileSync(expoModuleMap, 'utf8')).toBe('module React {}\n');
});
it('fails when the tarball has no React.xcframework', () => {
const stage = fs.mkdtempSync(path.join(podsRoot, 'stage-bad-'));
writeFile(path.join(stage, 'unrelated.txt'), 'nope');
execFileSync('tar', [
'-czf',
path.join(
podsRoot,
'ReactNativeCore-artifacts',
`reactnative-core-${VERSION.toLowerCase()}-release.tar.gz`,
),
'-C',
stage,
'.',
]);
expect(() =>
replaceRNCoreConfiguration('Release', VERSION, podsRoot),
).toThrow(/Extraction verification failed/);
});
});
+49 -125
View File
@@ -59,7 +59,7 @@ function replaceRNCoreConfiguration(
configuration /*: string */,
version /*: string */,
podsRoot /*: string */,
) {
) /*: void */ {
// Filename comes from rncore.rb
const tarballURLPath = `${podsRoot}/ReactNativeCore-artifacts/reactnative-core-${version.toLowerCase()}-${configuration.toLowerCase()}.tar.gz`;
@@ -73,18 +73,6 @@ function replaceRNCoreConfiguration(
const tmpExtractDir = path.join(tmpDir, 'React-Core-prebuilt');
fs.mkdirSync(tmpExtractDir, {recursive: true});
// Preserve Expo-generated modulemap before replacing directories
const useFrameworksModulemapName = 'React-use-frameworks.modulemap';
const useFrameworksModulemapPath = path.join(
finalLocation,
useFrameworksModulemapName,
);
let savedModulemap = null;
if (fs.existsSync(useFrameworksModulemapPath)) {
console.log('Preserving', useFrameworksModulemapName);
savedModulemap = fs.readFileSync(useFrameworksModulemapPath);
}
try {
console.log('Extracting the tarball to temp dir', tarballURLPath);
const result = spawnSync(
@@ -110,98 +98,30 @@ function replaceRNCoreConfiguration(
);
}
// Delete only directories in finalLocation (e.g. the React.xcframework) -
// not files, so any sibling files written during pod install are preserved.
const dirs = fs
.readdirSync(finalLocation, {withFileTypes: true})
.filter(dirent => dirent.isDirectory());
for (const dirent of dirs) {
const direntName =
typeof dirent.name === 'string' ? dirent.name : dirent.name.toString();
const dirPath = `${finalLocation}/${direntName}`;
console.log('Removing directory', dirPath);
fs.rmSync(dirPath, {force: true, recursive: true});
}
// Move extracted directories from temp to final location
const extractedEntries = fs
.readdirSync(tmpExtractDir, {withFileTypes: true})
.filter(dirent => dirent.isDirectory());
for (const dirent of extractedEntries) {
const direntName =
typeof dirent.name === 'string' ? dirent.name : dirent.name.toString();
const src = path.join(tmpExtractDir, direntName);
const dst = path.join(finalLocation, direntName);
const mvResult = spawnSync('mv', [src, dst], {stdio: 'inherit'});
if (mvResult.status !== 0) {
// Fallback: copy recursively then remove source
console.log(`mv failed for ${direntName}, falling back to cp -R`);
const cpResult = spawnSync('cp', ['-R', src, dst], {
stdio: 'inherit',
});
if (cpResult.status !== 0) {
throw new Error(
`cp fallback failed with exit code ${cpResult.status}`,
);
}
// Replace only the compiled framework. Headers/ is flattened from
// ReactNativeHeaders by the podspec prepare_command, and the prebuild
// compose job emits one set of those headers for both configurations, so a
// config switch leaves them identical. Leaving them alone keeps
// Headers/module.modulemap — which consumers activate through
// -fmodule-map-file — in place for the whole build; deleting and recreating
// it mid-build lets a concurrent dependency scan miss it, and the React
// module then precompiles without it (#57803).
const dest = path.join(finalLocation, 'React.xcframework');
console.log('Replacing', dest);
fs.rmSync(dest, {force: true, recursive: true});
const mvResult = spawnSync('mv', [xcfwPath, dest], {stdio: 'inherit'});
if (mvResult.status !== 0) {
// Fallback: copy recursively then remove source
console.log('mv failed for React.xcframework, falling back to cp -R');
const cpResult = spawnSync('cp', ['-R', xcfwPath, dest], {
stdio: 'inherit',
});
if (cpResult.status !== 0) {
throw new Error(`cp fallback failed with exit code ${cpResult.status}`);
}
}
// The podspec prepare_command flattens ReactNativeHeaders' headers into a
// top-level Headers/ dir, but it does not re-run on a config swap. Mirror
// it here: re-flatten the headers (identical across slices) and drop the
// now-redundant xcframework so $(PODS_ROOT)/React-Core-prebuilt/Headers
// keeps resolving <react/...>, <yoga/...>, etc.
//
// Fail closed when the swapped-in tarball lacks ReactNativeHeaders: the
// directory purge above already deleted the previous Headers/, so
// continuing silently would leave the injected -fmodule-map-file flag
// dangling and break every <react/...> include only on a config switch —
// with no pointer to the version-skewed artifact that caused it.
const rnhXcfw = path.join(finalLocation, 'ReactNativeHeaders.xcframework');
if (!fs.existsSync(rnhXcfw)) {
throw new Error(
`ReactNativeHeaders.xcframework not found in the extracted tarball at ${finalLocation}. ` +
'The downloaded artifact predates the headers-spec layout (or is incomplete); ' +
'use a prebuilt tarball matching this react-native version.',
);
}
const slice = fs
.readdirSync(rnhXcfw, {withFileTypes: true})
.find(
dirent =>
dirent.isDirectory() &&
fs.existsSync(path.join(rnhXcfw, dirent.name.toString(), 'Headers')),
);
if (!slice) {
throw new Error(
`No slice with a Headers directory found inside ${rnhXcfw}.`,
);
}
const headersDest = path.join(finalLocation, 'Headers');
fs.rmSync(headersDest, {force: true, recursive: true});
const cpHeaders = spawnSync(
'cp',
['-R', path.join(rnhXcfw, slice.name.toString(), 'Headers'), headersDest],
{stdio: 'inherit'},
);
if (cpHeaders.status !== 0) {
throw new Error(
`Flattening ReactNativeHeaders failed with exit code ${cpHeaders.status}`,
);
}
fs.rmSync(rnhXcfw, {force: true, recursive: true});
} finally {
// Clean up temp directory
fs.rmSync(tmpDir, {force: true, recursive: true});
// Restore Expo-generated modulemap after directory replacement.
// Runs in finally so it is not skipped if mv/cp partially fails.
if (savedModulemap != null) {
const restoredPath = path.join(finalLocation, useFrameworksModulemapName);
fs.writeFileSync(restoredPath, savedModulemap);
console.log('Restored', useFrameworksModulemapName);
}
}
}
@@ -227,29 +147,33 @@ function main(
console.log('Done replacing React Native prebuilt');
}
// This script is executed in the Pods folder, which is usually not synched to Github, so it should be ok
const argv = yargs
.option('c', {
alias: 'configuration',
description:
'Configuration to use to download the right React-Core prebuilt version. Allowed values are "Debug" and "Release".',
})
.option('r', {
alias: 'reactNativeVersion',
description:
'The Version of React Native associated with the React-Core prebuilt tarball.',
})
.option('p', {
alias: 'podsRoot',
description: 'The path to the Pods root folder',
})
.usage('Usage: $0 -c Debug -r <version> -p <path/to/react-native>').argv;
if (require.main === module) {
// This script is executed in the Pods folder, which is usually not synched to Github, so it should be ok
const argv = yargs
.option('c', {
alias: 'configuration',
description:
'Configuration to use to download the right React-Core prebuilt version. Allowed values are "Debug" and "Release".',
})
.option('r', {
alias: 'reactNativeVersion',
description:
'The Version of React Native associated with the React-Core prebuilt tarball.',
})
.option('p', {
alias: 'podsRoot',
description: 'The path to the Pods root folder',
})
.usage('Usage: $0 -c Debug -r <version> -p <path/to/react-native>').argv;
// $FlowFixMe[prop-missing]
const configuration = argv.configuration;
// $FlowFixMe[prop-missing]
const version = argv.reactNativeVersion;
// $FlowFixMe[prop-missing]
const podsRoot = argv.podsRoot;
// $FlowFixMe[prop-missing]
const configuration = argv.configuration;
// $FlowFixMe[prop-missing]
const version = argv.reactNativeVersion;
// $FlowFixMe[prop-missing]
const podsRoot = argv.podsRoot;
main(configuration, version, podsRoot);
main(configuration, version, podsRoot);
}
module.exports = {replaceRNCoreConfiguration};