SwiftPM: move injected build settings and build scripts out of project.pbxproj (#58834)

Port of 6a2c7c2734 (#58834) to 0.88-stable. This is not a plain cherry-pick: the commit on main also moves the C++ stable API opt-ins from #59043 into the generated xcconfig, and #59043 is not on 0.88-stable. This port is the reviewed version of #58834 from before it was rebased onto #59043. Everything else is the same as the commit on main.

Summary:
`npx react-native spm add` and `spm update` edit the app's `project.pbxproj`. Today they write React Native's build settings and the full text of two build scripts into that file. Some of these values change with every React Native version. So a routine `spm update` gives a `project.pbxproj` diff, and teams get merge conflicts in a file that is hard to read.

This PR moves those values out of `project.pbxproj` into files that React Native generates next to it:

- `ReactNativeSPM/ReactNativeSPM.xcconfig` holds the build settings. Each app build configuration uses it as its base configuration.
- `ReactNativeSPM/Scripts/sync-autolinking.sh` and `ReactNativeSPM/Scripts/embed-flavored-frameworks.sh` hold the script bodies. The build phases in `project.pbxproj` only run these files.

The result: when a version bump does not change the set of packages or plugin frameworks, `spm update` gives no `project.pbxproj` diff. The changes go to the generated files.

Commit the `ReactNativeSPM/` directory with the project. Xcode reads these files before the build starts, so they must exist on a fresh clone. They are not in the ignored `build/` directory for that reason.

`project.pbxproj` still holds the package references, the product dependencies, and the build phases. Xcode has no other place for them.

`REACT_NATIVE_PATH` also changes. It is now `$(SRCROOT)/<path>` through `node_modules/react-native`. Before, with pnpm, it could be the resolved `.pnpm/react-native@<version>_<hash>` path. That path is specific to one machine, and it was committed.

### Limits

- The "no diff" result applies only when packages are referenced by local path. In remote mode, the package version in `project.pbxproj` still changes on each bump.
- When you add or remove a plugin framework, the input and output paths of the embed phase in `project.pbxproj` still change. Xcode requires these paths in the project file.
- `spm add` and `spm update` now refuse a target in two new cases, with a message that tells you what to do:
  - A configuration already uses a different xcconfig file as its base, and that file does not `#include` the generated one. React Native does not edit xcconfig files that it does not own. The message gives the exact `#include` line to add to your file. After you add it, `spm` accepts the configuration and leaves its base unchanged.
  - The target sets a list setting that the generated file also sets, without `$(inherited)`. The target value would hide the React Native value. The message names the settings to fix.
- Configuration names that contain spaces or `]` are not escaped in the `[config=<name>]` conditions.
- A configuration that you add in Xcode after `spm update` (for example, a copy of Release named "Staging") gets the release flavor until the next `spm update` adds its own condition.

### Existing apps

No manual migration is necessary. On the next `spm update`, React Native removes the build settings that it wrote before (it records them in its marker file), then writes the xcconfig file.

### Details for reviewers

- `generate-spm-xcodeproj.js`:
  - `generateReactNativeXcconfig()` writes the settings. Flavor-specific settings (`RN_SPM_FLAVOR`, `SWIFT_ACTIVE_COMPILATION_CONDITIONS`) use Xcode's `[config=<name>]` conditions, with the real configuration names from the project. One file serves all configurations.
  - `mergeReactBuildSettings()` is removed.
  - An unconditioned `RN_SPM_FLAVOR = release` comes before the `[config=<name>]` lines, as the fallback for configurations that the file does not list.
  - `generatedScriptWrapper()` writes the stable build-phase text. If the script file is missing, the build fails with a message to run `npx react-native spm update`. The embed script is an input path of its phase, so Xcode runs the phase again when the script changes.
  - `planInjection()` follows the `#include` chain of a configuration's base xcconfig. Each path resolves from the folder of the file that contains it, and a cycle stops the walk. The configurations that include the generated file are recorded in the marker as `xcconfig.includedByConfigUuids`.
  - The CocoaPods template sets `REACT_NATIVE_PATH` relative to `${PODS_ROOT}`. A target value outranks an xcconfig value, so injection removes that one value. Deinit does not put it back, because the value resolves to an empty path when CocoaPods is not used.
  - `linkedReactNativeRoot()` finds the `node_modules/react-native` link that resolves to the real React Native directory, to build the stable path.
  - `injectSpmIntoPbxproj()` now takes `{fromAppRoot, fromSrcRoot}` as its third argument.
  - Deinit removes the base-configuration references, the file reference, and the generated files. If a configuration uses a different xcconfig that may include the generated one, deinit keeps the generated file and logs why.
- `xcconfig-files.js` (new): xcconfig path resolution and `#include` parsing, moved out of `ios-deployment-target.js` so both files share it. `ios-deployment-target.js` behaves as before.
- `spm-pbxproj.js`: `ensureScalarField()` takes an `{after}` option, to put `baseConfigurationReference` at the correct position.

## Changelog:

[IOS] [CHANGED] - SwiftPM: `spm add` and `spm update` write React Native's build settings to `ReactNativeSPM/ReactNativeSPM.xcconfig` and its build scripts to `ReactNativeSPM/Scripts/`, so a version bump no longer changes `project.pbxproj`. A configuration that uses its own xcconfig must now `#include` the generated file, and a target setting that hides React Native's value must add `$(inherited)`. `spm` prints the exact fix in both cases.

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

Test Plan:
```
yarn jest --no-cache -i packages/react-native/scripts/spm
```

Result on this 0.88-stable port branch: 22 suites and 1099 tests pass (0.88-stable before the 5 ports: 21 suites, 1005 tests). The new tests failed before the change.

New tests:

- `inject-spm-xcodeproj-test.js`: a version bump (new React Native path and new framework slice data) gives a byte-identical `project.pbxproj`. Other tests check that each configuration uses the generated xcconfig, that a `${PODS_ROOT}`-based `REACT_NATIVE_PATH` is removed, that a user xcconfig is accepted when its `#include` chain reaches the generated file and refused otherwise, that the refusal gives the exact `#include` line, and that the embed script is an input of its phase.
- `remove-spm-injection-test.js`: a list setting without `$(inherited)` is refused. Settings from an older injection move into the xcconfig on the next update. Deinit removes the xcconfig reference and the generated files, keeps a base configuration that the user changed, and keeps the generated xcconfig while a user xcconfig may include it. A user xcconfig that includes the generated one survives add → sync → deinit unchanged. pnpm layouts give `$(SRCROOT)/…/node_modules/react-native`. A nearer `node_modules/react-native` that is a different install is skipped.
- `generate-spm-xcodeproj-test.js` and `spm-pbxproj-test.js`: the xcconfig content and the `{after}` option.

Also run:

- `flow focus-check` (flow-bin 0.331.0, as 0.88-stable pins) on the changed files: no errors in them.
- `prettier --check` and `eslint --max-warnings 0` on the changed files: no problems.
- CI on this PR: `test_ios_spm_helloworld`, `test_ios_spm_newapp` and `test_ios_spm_rntester` (Debug and Release) run `spm add` and a full `xcodebuild` with the generated xcconfig. Not run locally.

Not tested:

- An Xcode project in a subdirectory of the app root (`--xcodeproj`). The generated files are written relative to the app root. This case was also not supported before this change.

Ported from commit 6a2c7c2734, without the #59043 changes.
This commit is contained in:
Christian Falch committed 2026-10-21 17:28:11 +02:00
1 parent 0f95088438
commit 27150439fb
9 files changed
+1843 -570

No files matched your search

@@ -113,15 +113,15 @@ zero-arg path also implies `--deintegrate` (the safe-gate). So
From the JS root of a standard RN app (sibling `ios/` subdir), the command
redirects into `ios/` and prints a banner.
| Action | Description |
| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `add` | Inject SwiftPM packages (package refs, build settings, the Sync build phase) into the existing `.xcodeproj`, in place. Idempotent. Default on first run. `--deintegrate` first runs `pod deintegrate` + strips React Native from the Podfile. |
| `update` | Re-run the pipeline and refresh the existing injection. Default once a project is injected. |
| `deinit` | The inverse of `add`: surgically remove only what `add` injected (recorded in `.spm-injected.json`) and drop the marker. Git-recoverable; no prompt. Some edits it does not undo — see [Files the tool touches](#files-the-tool-touches). |
| `scaffold` | Generate `Package.swift` into `node_modules/<dep>/` for community RN libraries that ship only a podspec. |
| `sync` (advanced) | Lightweight resync invoked by the Xcode auto-sync hooks. Regenerates invariant codegen and autolinking output only. Not for humans. |
| `codegen` (advanced) | Run codegen and install the SwiftPM codegen template only. |
| `download` (advanced) | Download/check xcframework artifacts only. |
| Action | Description |
| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `add` | Inject SwiftPM packages (package refs, the base reference to `ReactNativeSPM/ReactNativeSPM.xcconfig`, the Sync build phase) into the existing `.xcodeproj`, in place. Idempotent. Default on first run. `--deintegrate` first runs `pod deintegrate` + strips React Native from the Podfile. |
| `update` | Re-run the pipeline and refresh the existing injection. Default once a project is injected. |
| `deinit` | The inverse of `add`: surgically remove only what `add` injected (recorded in `.spm-injected.json`) and drop the marker. Git-recoverable; no prompt. Some edits it does not undo — see [Files the tool touches](#files-the-tool-touches). |
| `scaffold` | Generate `Package.swift` into `node_modules/<dep>/` for community RN libraries that ship only a podspec. |
| `sync` (advanced) | Lightweight resync invoked by the Xcode auto-sync hooks. Regenerates invariant codegen and autolinking output only. Not for humans. |
| `codegen` (advanced) | Run codegen and install the SwiftPM codegen template only. |
| `download` (advanced) | Download/check xcframework artifacts only. |
## CLI Options
@@ -214,8 +214,9 @@ frameworks are deliberately kept out of the package graph. Instead:
- `spm add` downloads and validates **both** flavors into immutable app-local
slots.
- It injects SDK/architecture-qualified Xcode settings that link the exact
selected binaries.
- It writes SDK/architecture-qualified Xcode settings to
`ReactNativeSPM/ReactNativeSPM.xcconfig`. They link the exact selected
binaries.
- It adds one phase that copies and signs the selected frameworks into the app.
Configurations containing `debug` or `development` select Debug; every other
@@ -223,15 +224,19 @@ configuration selects Release. Selection uses only generated build settings and
standard macOS tools. Builds do not run Node, mutate symlinks, regenerate the
package graph, or require a second build.
The xcconfig sets `RN_SPM_FLAVOR` for each configuration by name. A
configuration added later, e.g. duplicated in Xcode, falls back to release until
you run `npx react-native spm update`.
Those debug-flavored configurations also get `DEBUG` in
`SWIFT_ACTIVE_COMPILATION_CONDITIONS`, injected as `("$(inherited)", DEBUG)`
when the setting is absent. Only this makes Swift's `#if DEBUG` true
`SWIFT_ACTIVE_COMPILATION_CONDITIONS`, set in the xcconfig as
`$(inherited) DEBUG`. Only this makes Swift's `#if DEBUG` true
(`GCC_PREPROCESSOR_DEFINITIONS` reaches C/ObjC/C++ only). `AppDelegate.swift`'s
`bundleURL()` branches on it to load from Metro instead of a bundled
`main.jsbundle`. CocoaPods injects it at `pod install` time, so this keeps
SwiftPM apps at parity. An existing value is left alone only if it already
contains `DEBUG`. Otherwise `DEBUG` is appended, and a scalar value is promoted
to an array (see [Files the tool touches](#files-the-tool-touches)).
SwiftPM apps at parity. `add` and `update` refuse a target value without
`$(inherited)`, because it would hide this one (see
[Build settings](#build-settings)).
### iOS deployment target
@@ -260,14 +265,16 @@ Paths are relative to the Xcode project directory (`ios/`) unless noted.
### In your repo — committed
| Path | Written by | What happens | Undone by `deinit`? |
| --------------------------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `MyApp.xcodeproj/project.pbxproj` | `add`, `update`, `scaffold` | SwiftPM package refs, the React build settings, the Sync build phase, and the flavored-framework embed phase are added; a re-run is a no-op. A `${PODS_ROOT}`-anchored `REACT_NATIVE_PATH` is replaced with the SwiftPM path. `add` also removes the template's unused `JavaScriptCore.framework` reference, and `add --deintegrate` removes an empty `Pods` group. | Yes — exactly what was injected, per the marker, including the original `REACT_NATIVE_PATH` (one exception below). The removed `JavaScriptCore.framework` reference and `Pods` group are **not** restored. |
| `MyApp.xcodeproj/.spm-injected.json` | `add`, `update`, `scaffold` | Created. Three roles: it records every edit made — including the pre-injection value of any build setting rewritten — so removal is surgical and re-runs stay idempotent; it records the frameworks the project links (`linkedFrameworks`), which the build-time sync compares with the frameworks plugins provide; and it **pins configuration** later runs and Xcode builds must reuse (see the two pins below). | Yes — deleted, and the pins go with it |
| `MyApp.xcodeproj/xcshareddata/xcschemes/*.xcscheme` | `add`, `update`, `scaffold` | The sync pre-action is added to the scheme that builds your target; a shared scheme is created if there is none. Commit this or teammates lose the pre-action. | Yes — a scheme `add` created is deleted only if it is still byte-identical to the generated one; otherwise only the pre-action is stripped |
| `.gitignore` | `add` only | Created if absent, else appended: a `# SPM – auto-generated at build time` block adding `Package.resolved`, `build/generated/`, `build/xcframeworks/`, `.build/`. | **No** — the block is left behind |
| `Podfile` | `add --deintegrate` | Only the lines containing the React Native directives (`use_react_native!`, `use_native_modules!`, `prepare_react_native_project!`) are stripped. Your own `pod '…'` lines are preserved. The argument lines of a multi-line `use_react_native!(` call and `react_native_post_install(...)` remain — remove them by hand before `pod install`. | **No** — re-add the directives yourself to go back to CocoaPods |
| `Pods/`, `Pods-*.xcconfig`, `[CP]` phases | `add --deintegrate` | Removed by `pod deintegrate`. The `.xcworkspace` referencing them is left on disk. | **No** — run `pod install` to restore |
| Path | Written by | What happens | Undone by `deinit`? |
| --------------------------------------------------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `MyApp.xcodeproj/project.pbxproj` | `add`, `update`, `scaffold` | SwiftPM package refs, a reference to `ReactNativeSPM/ReactNativeSPM.xcconfig` set as the base configuration of each app configuration, the Sync build phase, and the flavored-framework embed phase are added. The two phases run their scripts from `ReactNativeSPM/Scripts/`. A re-run is a no-op. A `${PODS_ROOT}`-anchored `REACT_NATIVE_PATH` is removed, so the xcconfig's SwiftPM path applies. `add` also removes the template's unused `JavaScriptCore.framework` reference, and `add --deintegrate` removes an empty `Pods` group. | Yes — exactly what was injected, per the marker. The removed `REACT_NATIVE_PATH`, `JavaScriptCore.framework` reference, and `Pods` group are **not** restored. |
| `MyApp.xcodeproj/.spm-injected.json` | `add`, `update`, `scaffold` | Created. Three roles: it records every edit made — including which configurations it based on the generated xcconfig — so removal is surgical and re-runs stay idempotent; it records the frameworks the project links (`linkedFrameworks`), which the build-time sync compares with the frameworks plugins provide; and it **pins configuration** later runs and Xcode builds must reuse (see the two pins below). | Yes — deleted, and the pins go with it |
| `ReactNativeSPM/ReactNativeSPM.xcconfig` | `add`, `update`, `scaffold` | Regenerated on each run and written when its content changes. Holds the React build settings: search paths, linker flags, `REACT_NATIVE_PATH`, the C++ standard, each configuration's flavor (`RN_SPM_FLAVOR`), and `DEBUG` for Swift on debug configurations (see [Build settings](#build-settings)). **Commit it.** Xcode reads it before any build phase runs, so a build cannot regenerate it. If it is missing, run `npx react-native spm update` and commit it. | Yes — deleted, unless a configuration is based on an xcconfig of your own, which may `#include` it. Then the file is kept, and `deinit` names those configurations. |
| `ReactNativeSPM/Scripts/` | `add`, `update`, `scaffold` | Regenerated on each run and written when their content changes: `sync-autolinking.sh` and `embed-flavored-frameworks.sh`, the scripts the Sync and embed phases run. Plugin script phases keep their scripts in `project.pbxproj`. **Commit it.** When a script is missing, its phase fails the build with `error: <path> is missing. Run 'npx react-native spm update' to generate it.` | Yes — both scripts are deleted |
| `MyApp.xcodeproj/xcshareddata/xcschemes/*.xcscheme` | `add`, `update`, `scaffold` | The sync pre-action is added to the scheme that builds your target; a shared scheme is created if there is none. Commit this or teammates lose the pre-action. | Yes — a scheme `add` created is deleted only if it is still byte-identical to the generated one; otherwise only the pre-action is stripped |
| `.gitignore` | `add` only | Created if absent, else appended: a `# SPM – auto-generated at build time` block adding `Package.resolved`, `build/generated/`, `build/xcframeworks/`, `.build/`. | **No** — the block is left behind |
| `Podfile` | `add --deintegrate` | Only the lines containing the React Native directives (`use_react_native!`, `use_native_modules!`, `prepare_react_native_project!`) are stripped. Your own `pod '…'` lines are preserved. The argument lines of a multi-line `use_react_native!(` call and `react_native_post_install(...)` remain — remove them by hand before `pod install`. | **No** — re-add the directives yourself to go back to CocoaPods |
| `Pods/`, `Pods-*.xcconfig`, `[CP]` phases | `add --deintegrate` | Removed by `pod deintegrate`. The `.xcworkspace` referencing them is left on disk. | **No** — run `pod install` to restore |
The two pins are the `--version` pin (`artifactsVersionOverride`, see
[Pinning the React Native version](#pinning-the-react-native-version)) and the
@@ -298,24 +305,32 @@ every other byte of your project — signing, capabilities, your own Build Phase
— stays untouched. The injected refs point at three stable sub-package paths
under `build/`. So adding or removing community deps changes only the
sub-package contents (gitignored) and never re-injects. `deinit` leaves the
project byte-identical to its pre-`add` state, with the exceptions above and one
more, described next.
project byte-identical to its pre-`add` state, with the exceptions above.
**Build settings that already exist** are edited in place. `add` merges into
five array settings: `HEADER_SEARCH_PATHS`, `OTHER_LDFLAGS`,
`FRAMEWORK_SEARCH_PATHS`, `LD_RUNPATH_SEARCH_PATHS`, and (on debug
configurations) `SWIFT_ACTIVE_COMPILATION_CONDITIONS`. Each keeps the shape it
was written in: Xcode's multi-line form, or the compact one-line form that hand
edits and other generators (XcodeGen, Tuist) emit.
### Build settings
A setting that exists as a plain _scalar_ is promoted to a `( … )` array. An
Xcode-authored target can carry that shape, e.g.
`LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";` written
as a scalar rather than a list. `add` records the pre-injection value in the
marker. `deinit` restores it by rewriting the whole field, because once folded
together, the injected members and your own are indistinguishable. So **members
you add to a promoted array by hand afterwards are lost**. That applies to
`update` too, which reverts to the recorded baseline before re-injecting.
The React build settings live in `ReactNativeSPM/ReactNativeSPM.xcconfig`, not
in `project.pbxproj`. Each app configuration is based on that file. Its list
settings start with `$(inherited)`. `add` and `update` refuse two setups, and
the error names the fix:
- **A configuration already based on an xcconfig of your own.** React Native
does not edit xcconfig files it does not own. Add
`#include "<path>/ReactNativeSPM.xcconfig"` to your file instead, with the
path relative to the folder that holds your file, and re-run. `#include`
chains are followed. The configuration then keeps your file as its base.
- **A list setting the target sets without `$(inherited)`.** These are
`HEADER_SEARCH_PATHS`, `OTHER_LDFLAGS`, `FRAMEWORK_SEARCH_PATHS`,
`LD_RUNPATH_SEARCH_PATHS`, and on debug configurations
`SWIFT_ACTIVE_COMPILATION_CONDITIONS`. A target's own value outranks the
xcconfig, so it would hide React Native's values. Add `$(inherited)` and
re-run.
A project set up by an earlier version carries these settings in
`project.pbxproj`. The next `update` or `deinit` reverses the edits the marker
recorded. It removes the settings that version added and puts back any value it
replaced. An array that version promoted from a scalar goes back to its original
value, so **members you added to it by hand are lost**.
## Environment variables
@@ -362,6 +377,11 @@ On an already-injected project this routes to `update`. It fetches the
xcframework artifacts into the shared cache if they aren't present, and
regenerates `build/xcframeworks` + `build/generated`.
`ReactNativeSPM/` is not under `build/`. It is committed with the project, so a
fresh clone already has it (see
[In your repo — committed](#in-your-repo--committed)). `update` rewrites it when
its content changes.
**Automate it** with a `postinstall` hook. It runs as part of the `npm install`
/ `yarn install` your CI already does before `xcodebuild`:
@@ -642,6 +662,12 @@ react-native spm deinit # surgically removes everything `add` injected
pod install # then, to restore CocoaPods
```
`deinit` removes each configuration's base reference to
`ReactNativeSPM/ReactNativeSPM.xcconfig` and deletes the generated scripts. It
deletes the xcconfig too, unless a configuration is based on an xcconfig of your
own. That file may `#include` it, so `deinit` keeps it and names those
configurations. Remove the `#include` and the file yourself.
To reset the regenerable build state without un-injecting, delete the gitignored
dirs and re-run:
@@ -659,6 +685,7 @@ across apps; refresh it with `react-native spm update --download force`.
| Problem | Fix |
| ---------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `xcodebuild` fails: "Could not resolve package dependencies … `build/generated/autolinking` doesn't exist" | Fresh clone — run `npx react-native spm` once before building (see [Fresh clones & CI](#fresh-clones--ci)) |
| Build fails: `error: …/ReactNativeSPM/Scripts/<name>.sh is missing` | `ReactNativeSPM/` was not committed. Run `npx react-native spm update`, then commit `ReactNativeSPM/` |
| `spm add` fails: "CocoaPods-integrated project" | Re-run `spm add --deintegrate` (runs `pod deintegrate` + strips RN from the Podfile), or `pod deintegrate` yourself first. |
| `spm add` fails: "no .xcodeproj found" | Create an app first (`npx @react-native-community/cli init`) or make a project in Xcode, then `spm add`. |
| `spm add` fails: "multiple .xcodeproj found" | Pass `--xcodeproj <path>` (and `--productName <target>` if multiple app targets). |
@@ -683,21 +710,24 @@ across apps; refresh it with `react-native spm update --download force`.
`react-native spm add` and `react-native spm update` orchestrate these steps:
| Step | Script | Output |
| -------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------- |
| 1. CLI config | `spm/generate-spm-autolinking-config.js` | `build/generated/autolinking/autolinking.json` |
| 2. Codegen | `generate-codegen-artifacts.js` | `build/generated/ios/` |
| 3. Autolinking | `spm/generate-spm-autolinking.js` | `build/generated/autolinking/Package.swift` |
| 4. Download | `spm/download-spm-artifacts.js` | Complete Debug and Release cache slots |
| 5. Package | `spm/generate-spm-package.js` | Immutable flavor slots, central manifest, canonical `ReactHeaders`, and invariant `Package.swift` |
| 6. Inject | `spm/generate-spm-xcodeproj.js` | Invariant SwiftPM products plus configuration-qualified linker settings and the embed/sign phase |
| Auto-sync | `spm/sync-spm-autolinking.js` | Re-runs invariant codegen/autolinking output only at Xcode build time |
| Step | Script | Output |
| -------------- | ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1. CLI config | `spm/generate-spm-autolinking-config.js` | `build/generated/autolinking/autolinking.json` |
| 2. Codegen | `generate-codegen-artifacts.js` | `build/generated/ios/` |
| 3. Autolinking | `spm/generate-spm-autolinking.js` | `build/generated/autolinking/Package.swift` |
| 4. Download | `spm/download-spm-artifacts.js` | Complete Debug and Release cache slots |
| 5. Package | `spm/generate-spm-package.js` | Immutable flavor slots, central manifest, canonical `ReactHeaders`, and invariant `Package.swift` |
| 6. Inject | `spm/generate-spm-xcodeproj.js` | Invariant SwiftPM products and the embed/sign phase in the project, plus `ReactNativeSPM/` with the configuration-qualified linker settings and the phase scripts |
| Auto-sync | `spm/sync-spm-autolinking.js` | Re-runs invariant codegen/autolinking output only at Xcode build time |
### Directory Layout
```text
my-app/ios/
MyApp.xcodeproj/ <-- committed (your project; SwiftPM injected in place, carries .spm-injected.json)
ReactNativeSPM/ <-- committed, rewritten by add/update
ReactNativeSPM.xcconfig <-- React build settings; base configuration of the app configurations
Scripts/ <-- scripts the Sync and embed phases run
Podfile <-- kept; `--deintegrate` only strips the React Native lines (CocoaPods coexistence is best-effort)
build/
generated/
@@ -741,7 +771,7 @@ autolinking up to date without manual re-runs of `react-native spm`:
| Hook | Where | Role |
| ---------------------------------- | ------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| Scheme pre-action | The app's **shared** scheme (`xcshareddata/xcschemes/`), under `BuildAction` → `PreActions` | Fires earlier in the build than a build phase can, so it is the one that normally does the re-sync. |
| `Sync SPM Autolinking` build phase | `.xcodeproj`, prepended before `Sources` | **Safety net** for builds that bypass the scheme (and for a scheme whose pre-action was stripped). |
| `Sync SPM Autolinking` build phase | `.xcodeproj`, prepended before `Sources`; runs `ReactNativeSPM/Scripts/sync-autolinking.sh` | **Safety net** for builds that bypass the scheme (and for a scheme whose pre-action was stripped). |
The hooks keep an _existing_ set of generated packages current. They do not
create the first one: see [Fresh clones & CI](#fresh-clones--ci).
@@ -17,6 +17,7 @@ const {
buildSyncAutolinkingScript,
flavorForBuildConfiguration,
frameworkConditionalSettings,
generateReactNativeXcconfig,
generateXcscheme,
readScriptPhasesManifest,
} = require('../generate-spm-xcodeproj');
@@ -604,6 +605,99 @@ describe('configuration-driven framework settings', () => {
});
});
describe('generateReactNativeXcconfig', () => {
const DEVICE_ONLY = {...FRAMEWORK, slices: [FRAMEWORK.slices[0]]};
it('writes every setting the app target needs, extending inherited lists', () => {
expect(
generateReactNativeXcconfig(
['Debug', 'Release'],
'../node_modules/react-native',
[DEVICE_ONLY],
),
).toBe(
`// Generated by React Native on every \`spm add\` and \`spm update\`.
// Do not edit: changes are overwritten.
CLANG_CXX_LANGUAGE_STANDARD = c++20
REACT_NATIVE_PATH = $(SRCROOT)/../node_modules/react-native
HEADER_SEARCH_PATHS = $(inherited) "$(SRCROOT)/build/generated/autolinking/headers"
OTHER_LDFLAGS = $(inherited) -ObjC "$(RN_SPM_REACT_BINARY)"
FRAMEWORK_SEARCH_PATHS = $(inherited) "$(RN_SPM_REACT_SEARCH_PATH)"
LD_RUNPATH_SEARCH_PATHS = $(inherited) @executable_path/Frameworks
RN_SPM_FLAVOR = release
RN_SPM_FLAVOR[config=Debug] = debug
SWIFT_ACTIVE_COMPILATION_CONDITIONS[config=Debug] = $(inherited) DEBUG
RN_SPM_FLAVOR[config=Release] = release
RN_SPM_REACT_FRAMEWORK[sdk=iphoneos*] = $(SRCROOT)/build/xcframeworks/$(RN_SPM_FLAVOR)/React.xcframework/ios-arm64/React.framework
RN_SPM_REACT_BINARY[sdk=iphoneos*] = $(SRCROOT)/build/xcframeworks/$(RN_SPM_FLAVOR)/React.xcframework/ios-arm64/React.framework/React
RN_SPM_REACT_SEARCH_PATH[sdk=iphoneos*] = $(SRCROOT)/build/xcframeworks/$(RN_SPM_FLAVOR)/React.xcframework/ios-arm64
`,
);
});
it('anchors REACT_NATIVE_PATH on SRCROOT itself when react-native sits there', () => {
expect(generateReactNativeXcconfig(['Debug'], '', [FRAMEWORK])).toContain(
'\nREACT_NATIVE_PATH = $(SRCROOT)\n',
);
});
it("conditions the flavor on the project's own configuration names", () => {
const xcconfig = generateReactNativeXcconfig(
['Development', 'Staging'],
'../node_modules/react-native',
[FRAMEWORK],
);
expect(xcconfig).toContain('RN_SPM_FLAVOR[config=Development] = debug\n');
expect(xcconfig).toContain(
'SWIFT_ACTIVE_COMPILATION_CONDITIONS[config=Development] = $(inherited) DEBUG\n',
);
expect(xcconfig).toContain('RN_SPM_FLAVOR[config=Staging] = release\n');
expect(xcconfig).not.toContain(
'SWIFT_ACTIVE_COMPILATION_CONDITIONS[config=Staging]',
);
expect(xcconfig).not.toMatch(/\[config=(Debug|Release)\]/);
});
// A configuration duplicated in Xcode keeps the base reference but has no
// line of its own until the next sync, and an unset flavor would resolve
// every framework path to nothing.
it('falls back to the release flavor for a configuration it does not list', () => {
const lines = generateReactNativeXcconfig(
['Debug', 'Release'],
'../node_modules/react-native',
[FRAMEWORK],
).split('\n');
const fallback = lines.indexOf('RN_SPM_FLAVOR = release');
expect(fallback).toBeGreaterThan(-1);
expect(fallback).toBeLessThan(
lines.findIndex(line => line.startsWith('RN_SPM_FLAVOR[config=')),
);
expect(
lines.some(line =>
line.startsWith('SWIFT_ACTIVE_COMPILATION_CONDITIONS ='),
),
).toBe(false);
});
it('writes no plist quoting around conditional keys or path values', () => {
const xcconfig = generateReactNativeXcconfig(
['Debug'],
'../node_modules/react-native',
[FRAMEWORK],
);
expect(xcconfig).toContain(
'\nRN_SPM_REACT_BINARY[sdk=iphonesimulator*] = $(SRCROOT)/',
);
expect(xcconfig).toContain('\nRN_SPM_REACT_SEARCH_PATH[sdk=macosx*] = ');
expect(xcconfig).not.toMatch(/^"/m);
expect(xcconfig).not.toContain('= "$(SRCROOT)/build/xcframeworks');
});
});
describe('embed framework phase script', () => {
const script = buildEmbedFrameworksScript([FRAMEWORK]);
@@ -12,11 +12,15 @@
const {
buildPhaseOrder,
buildSyncAutolinkingScript,
generateReactNativeXcconfig,
injectSpmIntoPbxproj,
planInjection,
} = require('../generate-spm-xcodeproj');
const {findField, findObjectByUuid, quoteIfNeeded} = require('../spm-pbxproj');
const {isBalanced} = require('./pbxproj-oracles');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const PLAIN = fs.readFileSync(
@@ -56,17 +60,41 @@ function buildSettingsOf(text, configUuid) {
);
return text.slice(open, text.indexOf('};', open));
}
// Derive a variant whose app-target configs already carry HEADER_SEARCH_PATHS,
// set to any valid pbxproj value: a plain scalar (which injection promotes to an
// array) or an array injection appends to.
function withHeaderSearchPaths(value) {
// Seed a whole `KEY = value;` field into both app-target configs.
function withAppSetting(field) {
return PLAIN.replaceAll(
'PRODUCT_BUNDLE_IDENTIFIER = com.example.MyApp;',
`HEADER_SEARCH_PATHS = ${value};\n\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = com.example.MyApp;`,
`${field}\n\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = com.example.MyApp;`,
);
}
function withHeaderSearchPaths(value) {
return withAppSetting(`HEADER_SEARCH_PATHS = ${value};`);
}
// The app target's Debug config already based on an xcconfig of the user's own.
const FOREIGN_XCCONFIG = PLAIN.replace(
DEBUG_CONFIG_HEAD,
'AA0000000000000000000901 /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbaseConfigurationReference = CC0000000000000000000001 /* App.xcconfig */;\n\t\t\tbuildSettings = {',
).replace(
'/* End PBXFileReference section */',
'\t\tCC0000000000000000000001 /* App.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Config/App.xcconfig; sourceTree = "<group>"; };\n/* End PBXFileReference section */',
);
const XCCONFIG_PATH = 'ReactNativeSPM/ReactNativeSPM.xcconfig';
const SYNC_SCRIPT_PATH = 'ReactNativeSPM/Scripts/sync-autolinking.sh';
const EMBED_SCRIPT_PATH = 'ReactNativeSPM/Scripts/embed-flavored-frameworks.sh';
// The raw (still plist-quoted) shellScript value of the phase labelled `label`.
function shellScriptOf(text, label) {
const uuid = new RegExp(`([0-9A-F]{24}) /\\* ${label} \\*/ = \\{`).exec(
text,
)[1];
return findField(text, findObjectByUuid(text, uuid), 'shellScript').value;
}
const RN_PATH = '../node_modules/react-native';
const RN_PATHS = {fromAppRoot: RN_PATH, fromSrcRoot: RN_PATH};
const TEST_FRAMEWORKS = [
{
id: 'react',
@@ -117,7 +145,7 @@ function inject(
frameworksPhaseUuid: plan.frameworksPhaseUuid,
sourcesPhaseUuid: plan.sourcesPhaseUuid,
},
RN_PATH,
RN_PATHS,
remote,
generatedSources,
TEST_FRAMEWORKS,
@@ -179,6 +207,233 @@ describe('planInjection', () => {
expect(plan.ok).toBe(false);
expect(plan.reason).toMatch(/no application target/);
});
// The generated xcconfig sits below the target's own settings, so a list
// setting the target sets without $(inherited) hides React Native's.
it.each([
['HEADER_SEARCH_PATHS', '"$(SRCROOT)/Vendor"'],
['OTHER_LDFLAGS', '(\n\t\t\t\t\t"-lc++",\n\t\t\t\t)'],
['FRAMEWORK_SEARCH_PATHS', '""'],
['LD_RUNPATH_SEARCH_PATHS', '"@executable_path/Frameworks"'],
])('refuses %s set without $(inherited), naming it', (key, value) => {
const plan = planInjection(withAppSetting(`${key} = ${value};`), {});
expect(plan.ok).toBe(false);
expect(plan.reason).toContain(`${key} (Debug, Release)`);
expect(plan.reason).toContain('$(inherited)');
});
it('refuses SWIFT_ACTIVE_COMPILATION_CONDITIONS without $(inherited) on a debug configuration', () => {
const plan = planInjection(withDebugCondition(PLAIN, 'MY_FLAG'), {});
expect(plan.ok).toBe(false);
expect(plan.reason).toContain(
'SWIFT_ACTIVE_COMPILATION_CONDITIONS (Debug)',
);
});
it('accepts SWIFT_ACTIVE_COMPILATION_CONDITIONS without $(inherited) on a release configuration, which gets none', () => {
const releaseHead = DEBUG_CONFIG_HEAD.replace(
'AA0000000000000000000901 /* Debug */',
'AA00000000000000000000A2 /* Release */',
);
const text = PLAIN.replace(
releaseHead,
`${releaseHead}\n\t\t\t\tSWIFT_ACTIVE_COMPILATION_CONDITIONS = MY_FLAG;`,
);
expect(text).not.toBe(PLAIN);
expect(planInjection(text, {}).ok).toBe(true);
});
it.each([
['a scalar', '"$(inherited) $(SRCROOT)/Vendor"'],
[
'an array',
'(\n\t\t\t\t\t"$(inherited)",\n\t\t\t\t\t"$(SRCROOT)/Vendor",\n\t\t\t\t)',
],
['the brace form', '"${inherited} $(SRCROOT)/Vendor"'],
])(
'accepts a list setting that keeps $(inherited) in %s',
(_label, value) => {
expect(planInjection(withHeaderSearchPaths(value), {}).ok).toBe(true);
},
);
it("refuses a configuration already based on the user's own xcconfig", () => {
const plan = planInjection(FOREIGN_XCCONFIG, {});
expect(plan.ok).toBe(false);
expect(plan.reason).toContain('Debug');
expect(plan.reason).toContain('Config/App.xcconfig');
expect(plan.reason).toContain('#include');
expect(plan.reason).toContain(XCCONFIG_PATH);
});
it('accepts a project it already based on the generated xcconfig', () => {
expect(planInjection(inject(PLAIN).text, {}).ok).toBe(true);
});
});
// FOREIGN_XCCONFIG with the reference inside a `Config` group, the way Xcode
// files an xcconfig dragged into a folder of the navigator.
const FOREIGN_XCCONFIG_IN_GROUP = FOREIGN_XCCONFIG.replace(
'path = Config/App.xcconfig;',
'path = App.xcconfig;',
)
.replace(
'\t\t\t\tAA00000000000000000000F1 /* Products */,\n',
'\t\t\t\tAA00000000000000000000F1 /* Products */,\n\t\t\t\tCC0000000000000000000002 /* Config */,\n',
)
.replace(
'/* End PBXGroup section */',
'\t\tCC0000000000000000000002 /* Config */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tCC0000000000000000000001 /* App.xcconfig */,\n\t\t\t);\n\t\t\tpath = Config;\n\t\t\tsourceTree = "<group>";\n\t\t};\n/* End PBXGroup section */',
);
describe("planInjection — a configuration based on the user's own xcconfig", () => {
let roots = [];
afterEach(() => {
for (const root of roots) {
fs.rmSync(root, {recursive: true, force: true});
}
roots = [];
});
// An app root (== SRCROOT) holding `files`, app-root-relative path → content.
function appRootWith(files) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'spm-include-'));
roots.push(root);
for (const [relPath, content] of Object.entries(files)) {
fs.mkdirSync(path.dirname(path.join(root, relPath)), {recursive: true});
fs.writeFileSync(path.join(root, relPath), content, 'utf8');
}
return root;
}
function plan(files, text = FOREIGN_XCCONFIG) {
const root = appRootWith(files);
return planInjection(text, {appRoot: root, srcRoot: root});
}
const INCLUDES_GENERATED = `#include "../${XCCONFIG_PATH}"\n`;
it('accepts it when the xcconfig #includes the generated one', () => {
const result = plan({'Config/App.xcconfig': INCLUDES_GENERATED});
expect(result.ok).toBe(true);
expect(result.includedByConfigUuids).toEqual([APP_DEBUG_CONFIG]);
});
it('includes no configuration it bases on the generated xcconfig itself', () => {
expect(planInjection(PLAIN, {}).includedByConfigUuids).toEqual([]);
});
it('finds an xcconfig filed under a navigator group', () => {
expect(
plan(
{'Config/App.xcconfig': INCLUDES_GENERATED},
FOREIGN_XCCONFIG_IN_GROUP,
).ok,
).toBe(true);
});
it('follows #include? chains, each path relative to the file that holds it', () => {
expect(
plan({
'Config/App.xcconfig':
'// Shared settings\n#include? "Shared/Base.xcconfig"\n',
'Config/Shared/Base.xcconfig': `#include "../../${XCCONFIG_PATH}"\n`,
}).ok,
).toBe(true);
});
it.each([
[
'a path relative to the project directory',
`#include "${XCCONFIG_PATH}"\n`,
],
['a commented-out include', `// ${INCLUDES_GENERATED}`],
['an include of a file that is missing', '#include? "Missing.xcconfig"\n'],
])('refuses %s', (_label, content) => {
expect(plan({'Config/App.xcconfig': content}).ok).toBe(false);
});
it('refuses an include cycle that never reaches the generated xcconfig', () => {
const result = plan({
'Config/App.xcconfig': '#include "Base.xcconfig"\n',
'Config/Base.xcconfig': '#include "App.xcconfig"\n',
});
expect(result.ok).toBe(false);
});
it('still refuses a list setting without $(inherited) on it', () => {
const result = plan(
{'Config/App.xcconfig': INCLUDES_GENERATED},
FOREIGN_XCCONFIG.replaceAll(
'PRODUCT_BUNDLE_IDENTIFIER = com.example.MyApp;',
'HEADER_SEARCH_PATHS = /vendor;\n\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = com.example.MyApp;',
),
);
expect(result.ok).toBe(false);
expect(result.reason).toContain('HEADER_SEARCH_PATHS (Debug, Release)');
});
it('names the exact line to add, relative to the xcconfig that needs it', () => {
const result = plan({'Config/App.xcconfig': 'MY_SETTING = 1\n'});
expect(result.ok).toBe(false);
expect(result.reason).toContain(
`#include "../${XCCONFIG_PATH}" to Config/App.xcconfig`,
);
expect(result.reason).not.toContain('project directory');
});
it('says the path is relative to the xcconfig when it cannot find the file', () => {
const result = plan({});
expect(result.ok).toBe(false);
expect(result.reason).toContain(
`#include ${XCCONFIG_PATH} from Config/App.xcconfig`,
);
expect(result.reason).toContain(
'relative to the folder that holds Config/App.xcconfig',
);
expect(result.reason).not.toContain('project directory');
});
it("keeps the user's base and records the configuration as including the generated xcconfig", () => {
const root = appRootWith({'Config/App.xcconfig': INCLUDES_GENERATED});
const accepted = planInjection(FOREIGN_XCCONFIG, {
appRoot: root,
srcRoot: root,
});
const {text, xcconfig, generatedFiles} = injectSpmIntoPbxproj(
FOREIGN_XCCONFIG,
{
rootUuid: accepted.rootUuid,
targetUuid: accepted.target.uuid,
configUuids: accepted.configUuids,
includedByConfigUuids: accepted.includedByConfigUuids,
frameworksPhaseUuid: accepted.frameworksPhaseUuid,
sourcesPhaseUuid: accepted.sourcesPhaseUuid,
},
RN_PATHS,
null,
[],
TEST_FRAMEWORKS,
);
const baseOf = configUuid =>
findField(
text,
findObjectByUuid(text, configUuid),
'baseConfigurationReference',
)?.value;
expect(baseOf(APP_DEBUG_CONFIG)).toBe(
'CC0000000000000000000001 /* App.xcconfig */',
);
expect(baseOf(APP_RELEASE_CONFIG)).toBe(
`${xcconfig.fileRefUuid} /* ReactNativeSPM.xcconfig */`,
);
expect(xcconfig.configUuids).toEqual([APP_RELEASE_CONFIG]);
expect(xcconfig.includedByConfigUuids).toEqual([APP_DEBUG_CONFIG]);
expect(text).toContain(`path = ${XCCONFIG_PATH};`);
expect(generatedFiles[XCCONFIG_PATH]).toContain(
'RN_SPM_FLAVOR[config=Debug] = debug\n',
);
});
});
describe('injectSpmIntoPbxproj — Tier 1 (SPM graph)', () => {
@@ -225,71 +480,153 @@ describe('injectSpmIntoPbxproj — Tier 1 (SPM graph)', () => {
});
describe('injectSpmIntoPbxproj — Tier 2 (build settings + phase)', () => {
it('merges React build settings into BOTH build configurations', () => {
const PROJECT_DEBUG_CONFIG = 'AA0000000000000000000701';
const PROJECT_RELEASE_CONFIG = 'AA0000000000000000000801';
const ALL_CONFIGS = [
PROJECT_DEBUG_CONFIG,
PROJECT_RELEASE_CONFIG,
APP_DEBUG_CONFIG,
APP_RELEASE_CONFIG,
];
const appSettingsOf = text =>
[APP_DEBUG_CONFIG, APP_RELEASE_CONFIG].map(config =>
buildSettingsOf(text, config),
);
// React Native installed elsewhere, with `frameworks` in place of the
// default ones — what a later `spm update` sees.
const injectRelocated = frameworks => {
const plan = planInjection(PLAIN, {});
const relocated = '../../elsewhere/react-native';
return injectSpmIntoPbxproj(
PLAIN,
{
rootUuid: plan.rootUuid,
targetUuid: plan.target.uuid,
configUuids: plan.configUuids,
frameworksPhaseUuid: plan.frameworksPhaseUuid,
sourcesPhaseUuid: plan.sourcesPhaseUuid,
},
{fromAppRoot: relocated, fromSrcRoot: relocated},
null,
[],
frameworks,
[],
);
};
// A routine `spm update` must not touch project.pbxproj, so none of these may
// live in it — they are the ones whose values follow the installed frameworks.
it('writes no React build setting into any configuration', () => {
const {text} = inject(PLAIN);
expect(text.match(/-ObjC/g)).toHaveLength(2);
expect(text.match(/REACT_NATIVE_PATH = /g)).toHaveLength(2);
expect(text).not.toContain('fmodule-map-file=');
expect(text).toContain('build/generated/autolinking/headers');
expect(text.match(/CLANG_CXX_LANGUAGE_STANDARD = "c\+\+20"/g)).toHaveLength(
2,
for (const config of ALL_CONFIGS) {
const settings = buildSettingsOf(text, config);
expect(settings).toBe(buildSettingsOf(PLAIN, config));
expect(settings).not.toMatch(
/RN_SPM_|OTHER_LDFLAGS|FRAMEWORK_SEARCH_PATHS|HEADER_SEARCH_PATHS|LD_RUNPATH_SEARCH_PATHS|SWIFT_ACTIVE_COMPILATION_CONDITIONS|CLANG_CXX_LANGUAGE_STANDARD|REACT_NATIVE_PATH/,
);
}
});
it('bases every app configuration on the generated xcconfig, next to isa', () => {
const {text, injectedUuids, xcconfig} = inject(PLAIN);
const ref =
/baseConfigurationReference = ([0-9A-F]{24}) \/\* ReactNativeSPM\.xcconfig \*\/;/.exec(
text,
)[1];
for (const [config, name] of [
[APP_DEBUG_CONFIG, 'Debug'],
[APP_RELEASE_CONFIG, 'Release'],
]) {
expect(text).toContain(
`${config} /* ${name} */ = {\n\t\t\tisa = XCBuildConfiguration;\n` +
`\t\t\tbaseConfigurationReference = ${ref} /* ReactNativeSPM.xcconfig */;\n` +
'\t\t\tbuildSettings = {',
);
}
expect(text.match(/baseConfigurationReference = /g)).toHaveLength(2);
expect(xcconfig.configUuids).toEqual([
APP_DEBUG_CONFIG,
APP_RELEASE_CONFIG,
]);
const fileRef = findObjectByUuid(text, ref);
const field = key => findField(text, fileRef, key)?.value;
expect(field('isa')).toBe('PBXFileReference');
expect(field('lastKnownFileType')).toBe('text.xcconfig');
expect(field('name')).toBe('ReactNativeSPM.xcconfig');
expect(field('path')).toBe(XCCONFIG_PATH);
expect(field('sourceTree')).toBe('SOURCE_ROOT');
expect(injectedUuids).toContain(ref);
// Visible in the navigator, at the top of the project.
const mainGroup = findObjectByUuid(text, 'AA00000000000000000000E1');
expect(findField(text, mainGroup, 'children').value).toContain(
`${ref} /* ReactNativeSPM.xcconfig */,`,
);
});
it('returns the xcconfig generated for the configurations based on it', () => {
const {generatedFiles} = inject(PLAIN);
expect(generatedFiles[XCCONFIG_PATH]).toBe(
generateReactNativeXcconfig(
['Debug', 'Release'],
RN_PATH,
TEST_FRAMEWORKS,
),
);
expect(text).toContain('RN_SPM_FLAVOR = debug');
expect(text).toContain('RN_SPM_FLAVOR = release');
expect(text).toContain('RN_SPM_REACT_BINARY[sdk=iphoneos*]');
expect(text).toContain('RN_SPM_REACT_BINARY[sdk=iphonesimulator*]');
expect(text).toContain('$(RN_SPM_REACT_BINARY)');
});
// An absolute hermesc path is machine-specific, and the app commits its
// project.pbxproj. react-native-xcode.sh resolves hermesc through
// react-native's own dependency graph at build time instead.
it('never writes HERMES_CLI_PATH into either configuration', () => {
const {text, buildSettingChanges} = inject(PLAIN);
it('never writes HERMES_CLI_PATH, into the project or a generated file', () => {
const {text, generatedFiles} = inject(PLAIN);
expect(text).not.toContain('HERMES_CLI_PATH');
expect(
buildSettingChanges.flatMap(change => change.createdScalars ?? []),
).not.toContain('HERMES_CLI_PATH');
for (const content of Object.values(generatedFiles)) {
expect(content).not.toContain('HERMES_CLI_PATH');
}
});
// Swift's `#if DEBUG` — which AppDelegate.swift's bundleURL() uses to pick the
// Metro URL — is gated by this setting alone. CocoaPods injects it at `pod
// install`; an SPM app has to get it here or a Debug build looks for a
// main.jsbundle it never built.
it('sets SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG on the debug config only', () => {
const {text} = inject(PLAIN);
const debugSettings = buildSettingsOf(text, APP_DEBUG_CONFIG);
expect(debugSettings).toMatch(
/SWIFT_ACTIVE_COMPILATION_CONDITIONS = \(\s*"\$\(inherited\)",\s*DEBUG,\s*\)/,
);
expect(buildSettingsOf(text, APP_RELEASE_CONFIG)).not.toContain(
it.each([
['HEADER_SEARCH_PATHS', withHeaderSearchPaths('"$(inherited)"')],
[
'HEADER_SEARCH_PATHS',
withHeaderSearchPaths('(\n\t\t\t\t\t"$(inherited)",\n\t\t\t\t)'),
],
[
'SWIFT_ACTIVE_COMPILATION_CONDITIONS',
);
});
it('leaves a config that already sets DEBUG (scalar form) untouched', () => {
const {text} = inject(withDebugCondition(PLAIN, '"$(inherited) DEBUG"'));
// Not promoted to an array, not re-appended — DEBUG is already there.
expect(buildSettingsOf(text, APP_DEBUG_CONFIG)).toContain(
'SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) DEBUG";',
);
expect(text.match(/\bDEBUG\b/g)).toHaveLength(1);
});
it("adds DEBUG alongside the user's own compilation conditions", () => {
const {text} = inject(
withDebugCondition(PLAIN, '"$(inherited) MY_DEBUG_UI"'),
],
])("leaves the configuration's own %s untouched", (_key, before) => {
expect(appSettingsOf(inject(before).text)).toEqual(appSettingsOf(before));
});
// The CocoaPods template anchors REACT_NATIVE_PATH on ${PODS_ROOT}, which
// resolves empty once CocoaPods is gone, and a target's own value outranks
// any xcconfig — so it has to leave the project for the xcconfig's to apply.
it('removes a ${PODS_ROOT}-anchored REACT_NATIVE_PATH so the xcconfig value applies', () => {
const before = withAppSetting(
'REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native";',
);
// MY_DEBUG_UI must not be mistaken for DEBUG by a substring check.
const debugSettings = buildSettingsOf(text, APP_DEBUG_CONFIG);
expect(debugSettings).toContain('"$(inherited) MY_DEBUG_UI"');
expect(debugSettings).toMatch(/^\s*DEBUG,$/m);
const {text, xcconfig, generatedFiles} = inject(before);
expect(appSettingsOf(text)).toEqual(appSettingsOf(PLAIN));
expect(xcconfig.removedPodsRootReactNativePath).toBe(true);
expect(generatedFiles[XCCONFIG_PATH]).toContain(
`\nREACT_NATIVE_PATH = $(SRCROOT)/${RN_PATH}\n`,
);
});
it("keeps a REACT_NATIVE_PATH of the project's own", () => {
const before = withAppSetting(
'REACT_NATIVE_PATH = ../../node_modules/react-native;',
);
const {text, xcconfig} = inject(before);
expect(appSettingsOf(text)).toEqual(appSettingsOf(before));
expect(xcconfig.removedPodsRootReactNativePath).toBe(false);
});
it('prepends the Sync SPM Autolinking build phase', () => {
const {text} = inject(PLAIN);
expect(text).toContain('Sync SPM Autolinking');
expect(text).toContain('npx react-native spm sync');
// It runs before Sources.
const syncIdx = text.indexOf('Sync SPM Autolinking */,');
const sourcesIdx = text.indexOf('Sources */,');
@@ -297,6 +634,57 @@ describe('injectSpmIntoPbxproj — Tier 2 (build settings + phase)', () => {
expect(syncIdx).toBeLessThan(sourcesIdx);
});
// The script bodies change whenever React Native's do, so they live in
// generated files; the phase only carries a wrapper that never changes.
it.each([
['Sync SPM Autolinking', SYNC_SCRIPT_PATH, 'npx react-native spm sync'],
[
'Embed React Native Flavored Frameworks',
EMBED_SCRIPT_PATH,
'copy_and_sign "${RN_SPM_REACT_FRAMEWORK:-}" "React.framework"',
],
])('runs the %s script from %s', (label, scriptPath, bodyLine) => {
const {text, generatedFiles} = inject(PLAIN);
const wrapper = shellScriptOf(text, label);
expect(wrapper).toContain(`$SRCROOT/${scriptPath}`);
expect(wrapper).toContain('spm update');
expect(text).not.toContain(quoteIfNeeded(bodyLine).slice(1, -1));
expect(text).not.toContain('set -euo pipefail');
expect(generatedFiles[scriptPath]).toContain(bodyLine);
});
it('keeps the script wrappers identical across React Native versions and frameworks', () => {
const {text} = inject(PLAIN);
const other = injectRelocated([]).text;
for (const label of [
'Sync SPM Autolinking',
'Embed React Native Flavored Frameworks',
]) {
expect(shellScriptOf(other, label)).toBe(shellScriptOf(text, label));
}
});
// A routine `spm update` must leave project.pbxproj alone while the
// frameworks keep their ids and names: slice paths and architectures land
// only in the generated xcconfig.
it('produces a byte-identical project.pbxproj across a version bump (path + slice content change)', () => {
const bumped = TEST_FRAMEWORKS.map(framework => ({
...framework,
slices: framework.slices.map(slice => ({
...slice,
architectures: [...slice.architectures, 'arm64e'],
libraryIdentifier: `${slice.libraryIdentifier}_arm64e`,
binaryPath: 'React.framework/Versions/Current/React',
})),
}));
const before = inject(PLAIN);
const after = injectRelocated(bumped);
expect(after.generatedFiles[XCCONFIG_PATH]).not.toBe(
before.generatedFiles[XCCONFIG_PATH],
);
expect(after.text).toBe(before.text);
});
it('runs every injected shell-script build phase under bash, not /bin/sh', () => {
// Their bodies start with `set -euo pipefail`, which a non-bash /bin/sh
// (e.g. dash) rejects at runtime.
@@ -326,50 +714,6 @@ describe('injectSpmIntoPbxproj — Tier 2 (build settings + phase)', () => {
);
});
it.each([
[
'"$(inherited)"',
['"$(inherited)"', '"$(SRCROOT)/build/generated/autolinking/headers"'],
],
[
'"$(inherited) $(SRCROOT)/vendor/include"',
[
'"$(inherited)"',
'"$(inherited) $(SRCROOT)/vendor/include"',
'"$(SRCROOT)/build/generated/autolinking/headers"',
],
],
])(
'promotes a pre-existing HEADER_SEARCH_PATHS scalar (%s) to an array, keeping its value and one $(inherited)',
(scalar, expectedMembers) => {
const {text} = inject(withHeaderSearchPaths(scalar));
const arrays = [
...text.matchAll(/HEADER_SEARCH_PATHS = \(\n([\s\S]*?)\t+\);/g),
].map(m =>
m[1]
.split('\n')
.map(line => line.trim().replace(/,$/, ''))
.filter(member => member.length > 0),
);
// Both app-target configs (Debug + Release).
expect(arrays).toEqual([expectedMembers, expectedMembers]);
},
);
it('appends to a pre-existing ONE-LINE HEADER_SEARCH_PATHS array in place', () => {
const {text} = inject(withHeaderSearchPaths('("$(inherited)", )'));
expect(isBalanced(text)).toBe(true);
const arrays = [
...text.matchAll(/HEADER_SEARCH_PATHS = \(([^\n]*)\);/g),
].map(m => m[1]);
// Both app-target configs, each keeping the one-line shape it was written in.
expect(arrays).toEqual(
Array(2).fill(
'"$(inherited)", "$(SRCROOT)/build/generated/autolinking/headers", ',
),
);
});
it('adds one generated embed phase immediately after Frameworks', () => {
const {text} = inject(PLAIN);
expect(text).not.toContain('Fix SPM Embedded Flavor');
@@ -386,6 +730,19 @@ describe('injectSpmIntoPbxproj — Tier 2 (build settings + phase)', () => {
'$(TARGET_BUILD_DIR)/$(FRAMEWORKS_FOLDER_PATH)/React.framework',
);
});
// The phase only runs the script file, so the file has to be an input for
// Xcode to re-run the phase when the file alone changes.
it('lists its script file among the embed phase inputs', () => {
const {text} = inject(PLAIN);
const uuid =
/([0-9A-F]{24}) \/\* Embed React Native Flavored Frameworks \*\/ = \{/.exec(
text,
)[1];
expect(
findField(text, findObjectByUuid(text, uuid), 'inputPaths').value,
).toContain(`${quoteIfNeeded(`$(SRCROOT)/${EMBED_SCRIPT_PATH}`)},`);
});
});
describe('injectSpmIntoPbxproj — Tier 3 (plugin generated sources)', () => {
@@ -445,7 +802,7 @@ describe('injectSpmIntoPbxproj — Tier 3 (plugin generated sources)', () => {
frameworksPhaseUuid: plan.frameworksPhaseUuid,
sourcesPhaseUuid: plan.sourcesPhaseUuid,
},
RN_PATH,
RN_PATHS,
null,
[PROVIDER_SOURCE],
TEST_FRAMEWORKS,
@@ -484,7 +841,7 @@ describe('injectSpmIntoPbxproj — Tier 3 (plugin generated sources)', () => {
frameworksPhaseUuid: plan.frameworksPhaseUuid,
sourcesPhaseUuid: plan.sourcesPhaseUuid,
},
RN_PATH,
RN_PATHS,
null,
[PROVIDER_SOURCE],
TEST_FRAMEWORKS,
@@ -1118,22 +1475,24 @@ describe('injectSpmIntoPbxproj — invariants', () => {
});
it('is idempotent — a second injection is a byte-for-byte no-op', () => {
const first = inject(PLAIN).text;
const plan = planInjection(first, {});
const first = inject(PLAIN);
const plan = planInjection(first.text, {});
const second = injectSpmIntoPbxproj(
first,
first.text,
{
rootUuid: plan.rootUuid,
targetUuid: plan.target.uuid,
configUuids: plan.configUuids,
frameworksPhaseUuid: plan.frameworksPhaseUuid,
},
RN_PATH,
RN_PATHS,
null,
[],
TEST_FRAMEWORKS,
).text;
expect(second).toBe(first);
);
expect(second.text).toBe(first.text);
expect(second.generatedFiles).toEqual(first.generatedFiles);
expect(second.xcconfig).toEqual(first.xcconfig);
});
it('keeps the diff small — only adds lines, never removes original ones', () => {
@@ -1150,15 +1509,13 @@ describe('injectSpmIntoPbxproj — invariants', () => {
expect(added).toBeLessThan(220);
});
it('refreshes a stale shellScript on re-injection', () => {
it('replaces an inline script body from an earlier version with the wrapper', () => {
const first = inject(PLAIN).text;
// Simulate an earlier run whose generated script has since changed (e.g.
// fixed dispatch logic) by corrupting a substring of the baked-in script.
const stale = first.replace(
'npx react-native spm sync',
'STALE_OLD_SYNC_COMMAND',
shellScriptOf(first, 'Sync SPM Autolinking'),
quoteIfNeeded(buildSyncAutolinkingScript(RN_PATH)),
);
expect(stale).not.toBe(first);
expect(stale).toContain('npx react-native spm sync');
const plan = planInjection(stale, {});
const second = injectSpmIntoPbxproj(
stale,
@@ -1168,14 +1525,11 @@ describe('injectSpmIntoPbxproj — invariants', () => {
configUuids: plan.configUuids,
frameworksPhaseUuid: plan.frameworksPhaseUuid,
},
RN_PATH,
RN_PATHS,
null,
[],
TEST_FRAMEWORKS,
).text;
// The stale marker is gone and the current script is restored.
expect(second).not.toContain('STALE_OLD_SYNC_COMMAND');
expect(second).toContain('npx react-native spm sync');
expect(second).toBe(first);
});
@@ -76,6 +76,11 @@ function scaffoldApp(pbxproj /*: string */ = PLAIN) {
);
const rnRoot = path.join(appRoot, 'node_modules', 'react-native');
fs.mkdirSync(rnRoot, {recursive: true});
seedArtifacts(appRoot);
return {appRoot, xcodeprojPath, rnRoot};
}
function seedArtifacts(appRoot /*: string */) {
const artifactRoot = path.join(appRoot, 'build', 'xcframeworks');
fs.mkdirSync(artifactRoot, {recursive: true});
fs.writeFileSync(
@@ -83,7 +88,6 @@ function scaffoldApp(pbxproj /*: string */ = PLAIN) {
JSON.stringify({version: 1, frameworks: []}),
);
fs.writeFileSync(path.join(artifactRoot, '.artifact-stamp'), 'test\n');
return {appRoot, xcodeprojPath, rnRoot};
}
// The hoisted `hermes-compiler` layout a real installed app has: the package
@@ -167,6 +171,57 @@ function readMarker(xcodeprojPath) {
return JSON.parse(markerTextOf(xcodeprojPath));
}
const XCCONFIG_REL = 'ReactNativeSPM/ReactNativeSPM.xcconfig';
const GENERATED_FILES = [
XCCONFIG_REL,
'ReactNativeSPM/Scripts/sync-autolinking.sh',
'ReactNativeSPM/Scripts/embed-flavored-frameworks.sh',
];
function generatedFileContents(appRoot) {
return GENERATED_FILES.map(file =>
fs.existsSync(path.join(appRoot, file))
? fs.readFileSync(path.join(appRoot, file), 'utf8')
: null,
);
}
const APP_DEBUG_CONFIG = 'AA0000000000000000000901';
// The app target's Debug configuration based on Config/App.xcconfig, an
// xcconfig of the user's own.
const FOREIGN_XCCONFIG = PLAIN.replace(
`${APP_DEBUG_CONFIG} /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n`,
`${APP_DEBUG_CONFIG} /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbaseConfigurationReference = CC0000000000000000000001 /* App.xcconfig */;\n`,
).replace(
'/* End PBXFileReference section */',
'\t\tCC0000000000000000000001 /* App.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Config/App.xcconfig; sourceTree = "<group>"; };\n/* End PBXFileReference section */',
);
function writeUserXcconfig(appRoot, content) {
fs.mkdirSync(path.join(appRoot, 'Config'), {recursive: true});
fs.writeFileSync(path.join(appRoot, 'Config', 'App.xcconfig'), content);
}
// What re-basing Debug on the user's own xcconfig in Xcode does after `add`.
function rebaseDebugOnUserXcconfig(xcodeprojPath) {
const text = pbxprojOf(xcodeprojPath);
const start = text.indexOf(`${APP_DEBUG_CONFIG} /* Debug */ = {`);
const end = text.indexOf('buildSettings', start);
fs.writeFileSync(
path.join(xcodeprojPath, 'project.pbxproj'),
text.slice(0, start) +
text
.slice(start, end)
.replace(
/baseConfigurationReference = [0-9A-F]{24} \/\* ReactNativeSPM\.xcconfig \*\//,
'baseConfigurationReference = CC0000000000000000000001 /* App.xcconfig */',
) +
text.slice(end),
'utf8',
);
}
function schemePathOf(xcodeprojPath) {
return path.join(
xcodeprojPath,
@@ -204,11 +259,120 @@ describe('injectSpmIntoExistingXcodeproj — HERMES_CLI_PATH', () => {
expect(pbxprojOf(xcodeprojPath)).not.toContain('HERMES_CLI_PATH');
expect(pbxprojOf(xcodeprojPath)).not.toContain(hermesc);
for (const file of GENERATED_FILES) {
expect(fs.readFileSync(path.join(appRoot, file), 'utf8')).not.toContain(
'HERMES_CLI_PATH',
);
}
expect(markerTextOf(xcodeprojPath)).not.toContain('HERMES_CLI_PATH');
});
});
// pnpm's layout: the project's node_modules/react-native links into a store
// directory named after the version and dependency hash, and the Xcode project
// sits one level down, in ios/. Config commands report the store path.
function scaffoldPnpmApp() {
const projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'spm-pnpm-'));
scaffoldedAppRoots.push(projectRoot);
const nodeModules = path.join(projectRoot, 'node_modules');
const store = path.join(
nodeModules,
'.pnpm',
'react-native@0.87.0_abc123',
'node_modules',
'react-native',
);
fs.mkdirSync(store, {recursive: true});
fs.symlinkSync(
path.relative(nodeModules, store),
path.join(nodeModules, 'react-native'),
);
const appRoot = path.join(projectRoot, 'ios');
const xcodeprojPath = path.join(appRoot, 'MyApp.xcodeproj');
fs.mkdirSync(xcodeprojPath, {recursive: true});
fs.writeFileSync(path.join(xcodeprojPath, 'project.pbxproj'), PLAIN, 'utf8');
seedArtifacts(appRoot);
return {appRoot, xcodeprojPath, rnRoot: fs.realpathSync(store)};
}
// The xcconfig, scripts and scheme are committed, so they must name
// react-native the way the app resolves it, not by its store location.
describe('injectSpmIntoExistingXcodeproj — REACT_NATIVE_PATH', () => {
it('writes the node_modules link, not the pnpm store path', () => {
const {appRoot, xcodeprojPath, rnRoot} = scaffoldPnpmApp();
expect(rnRoot).toContain('.pnpm');
expect(
readMarker(xcodeprojPath).buildSettingChanges.flatMap(
change => change.createdScalars ?? [],
),
).not.toContain('HERMES_CLI_PATH');
injectSpmIntoExistingXcodeproj({
appRoot,
reactNativeRoot: rnRoot,
xcodeprojPath,
}).status,
).toBe('injected');
const generated = generatedFileContents(appRoot);
const [xcconfig, syncScript] = generated;
expect(xcconfig).toContain(
'\nREACT_NATIVE_PATH = $(SRCROOT)/../node_modules/react-native\n',
);
expect(syncScript).toContain('RN_DIR="../node_modules/react-native"');
for (const content of [
...generated,
fs.readFileSync(schemePathOf(xcodeprojPath), 'utf8'),
]) {
expect(content).not.toContain('.pnpm');
}
});
it('prefers the nearest node_modules link to react-native', () => {
const {appRoot, xcodeprojPath, rnRoot} = scaffoldPnpmApp();
fs.mkdirSync(path.join(appRoot, 'node_modules'));
fs.symlinkSync(rnRoot, path.join(appRoot, 'node_modules', 'react-native'));
injectSpmIntoExistingXcodeproj({
appRoot,
reactNativeRoot: rnRoot,
xcodeprojPath,
});
expect(fs.readFileSync(path.join(appRoot, XCCONFIG_REL), 'utf8')).toContain(
'\nREACT_NATIVE_PATH = $(SRCROOT)/node_modules/react-native\n',
);
});
it('skips a nearer node_modules/react-native that is another install', () => {
const {appRoot, xcodeprojPath, rnRoot} = scaffoldPnpmApp();
fs.mkdirSync(path.join(appRoot, 'node_modules', 'react-native'), {
recursive: true,
});
injectSpmIntoExistingXcodeproj({
appRoot,
reactNativeRoot: rnRoot,
xcodeprojPath,
});
expect(fs.readFileSync(path.join(appRoot, XCCONFIG_REL), 'utf8')).toContain(
'\nREACT_NATIVE_PATH = $(SRCROOT)/../node_modules/react-native\n',
);
});
it('falls back to the given path when no node_modules link resolves to it', () => {
const {appRoot, xcodeprojPath} = scaffoldApp();
const vendored = path.join(appRoot, 'vendor', 'react-native');
fs.mkdirSync(vendored, {recursive: true});
injectSpmIntoExistingXcodeproj({
appRoot,
reactNativeRoot: vendored,
xcodeprojPath,
});
const [xcconfig, syncScript] = generatedFileContents(appRoot);
expect(xcconfig).toContain(
'\nREACT_NATIVE_PATH = $(SRCROOT)/vendor/react-native\n',
);
expect(syncScript).toContain('RN_DIR="vendor/react-native"');
});
});
@@ -228,11 +392,15 @@ describe('removeSpmInjection — the surgical inverse of add', () => {
expect(fs.existsSync(path.join(xcodeprojPath, SPM_INJECTED_MARKER))).toBe(
true,
);
expect(generatedFileContents(appRoot)).not.toContain(null);
const removed = removeSpmInjection({appRoot, xcodeprojPath});
expect(removed.status).toBe('removed');
// Byte-identical to the pre-add pbxproj.
expect(pbxprojOf(xcodeprojPath)).toBe(before);
expect(generatedFileContents(appRoot)).toEqual(
GENERATED_FILES.map(() => null),
);
// Marker is gone.
expect(fs.existsSync(path.join(xcodeprojPath, SPM_INJECTED_MARKER))).toBe(
false,
@@ -258,12 +426,14 @@ describe('removeSpmInjection — the surgical inverse of add', () => {
sync();
const injected = pbxprojOf(xcodeprojPath);
const marker = markerTextOf(xcodeprojPath);
const files = generatedFileContents(appRoot);
const schemePath = schemePathOf(xcodeprojPath);
expect(fs.existsSync(schemePath)).toBe(true);
sync();
// The re-sync changed neither the project…
// The re-sync changed neither the project, nor the files it generates…
expect(pbxprojOf(xcodeprojPath)).toBe(injected);
expect(generatedFileContents(appRoot)).toEqual(files);
// …nor the record of what has to be undone.
expect(markerTextOf(xcodeprojPath)).toBe(marker);
@@ -374,6 +544,267 @@ describe('removeSpmInjection — the surgical inverse of add', () => {
expect(removed.status).toBe('removed');
expect(pbxprojOf(xcodeprojPath)).toBe(before);
});
it('keeps a base configuration the user re-pointed after add, and the xcconfig it may include', () => {
const {appRoot, xcodeprojPath, rnRoot} = scaffoldApp();
injectSpmIntoExistingXcodeproj({
appRoot,
reactNativeRoot: rnRoot,
xcodeprojPath,
});
const repointed = pbxprojOf(xcodeprojPath).replace(
/baseConfigurationReference = [0-9A-F]{24} \/\* ReactNativeSPM\.xcconfig \*\//g,
'baseConfigurationReference = CC0000000000000000000001 /* App.xcconfig */',
);
fs.writeFileSync(
path.join(xcodeprojPath, 'project.pbxproj'),
repointed,
'utf8',
);
expect(removeSpmInjection({appRoot, xcodeprojPath}).status).toBe('removed');
expect(
pbxprojOf(xcodeprojPath).match(
/baseConfigurationReference = CC0000000000000000000001 \/\* App\.xcconfig \*\/;/g,
),
).toHaveLength(2);
expect(fs.existsSync(path.join(appRoot, XCCONFIG_REL))).toBe(true);
});
it('keeps the xcconfig while one configuration is re-based on a user xcconfig, removing the scripts', () => {
const {appRoot, xcodeprojPath, rnRoot} = scaffoldApp();
injectSpmIntoExistingXcodeproj({
appRoot,
reactNativeRoot: rnRoot,
xcodeprojPath,
});
rebaseDebugOnUserXcconfig(xcodeprojPath);
const logSpy = jest.spyOn(console, 'log').mockImplementation(() => {});
removeSpmInjection({appRoot, xcodeprojPath});
const logged = logSpy.mock.calls.map(([line]) => line).join('\n');
logSpy.mockRestore();
expect(pbxprojOf(xcodeprojPath)).toContain(
'baseConfigurationReference = CC0000000000000000000001 /* App.xcconfig */;',
);
expect(pbxprojOf(xcodeprojPath)).not.toContain('ReactNativeSPM.xcconfig');
expect(
generatedFileContents(appRoot).map(content => content != null),
).toEqual([true, false, false]);
expect(logged).toContain(`Kept ${XCCONFIG_REL}`);
});
it('accepts a user xcconfig that #includes the generated one, across syncs and deinit', () => {
const {appRoot, xcodeprojPath, rnRoot} = scaffoldApp(FOREIGN_XCCONFIG);
writeUserXcconfig(appRoot, `#include "../${XCCONFIG_REL}"\n`);
const sync = () =>
injectSpmIntoExistingXcodeproj({
appRoot,
reactNativeRoot: rnRoot,
xcodeprojPath,
});
expect(sync().status).toBe('injected');
const injected = pbxprojOf(xcodeprojPath);
expect(readMarker(xcodeprojPath).xcconfig.includedByConfigUuids).toEqual([
APP_DEBUG_CONFIG,
]);
expect(sync().status).toBe('injected');
expect(pbxprojOf(xcodeprojPath)).toBe(injected);
removeSpmInjection({appRoot, xcodeprojPath});
expect(pbxprojOf(xcodeprojPath)).toBe(FOREIGN_XCCONFIG);
expect(fs.existsSync(path.join(appRoot, XCCONFIG_REL))).toBe(true);
});
it('keeps the xcconfig a recorded configuration included, even once its base is gone', () => {
const {appRoot, xcodeprojPath, rnRoot} = scaffoldApp(FOREIGN_XCCONFIG);
writeUserXcconfig(appRoot, `#include "../${XCCONFIG_REL}"\n`);
injectSpmIntoExistingXcodeproj({
appRoot,
reactNativeRoot: rnRoot,
xcodeprojPath,
});
fs.writeFileSync(
path.join(xcodeprojPath, 'project.pbxproj'),
pbxprojOf(xcodeprojPath).replace(
'\t\t\tbaseConfigurationReference = CC0000000000000000000001 /* App.xcconfig */;\n',
'',
),
'utf8',
);
removeSpmInjection({appRoot, xcodeprojPath});
expect(fs.existsSync(path.join(appRoot, XCCONFIG_REL))).toBe(true);
});
it('deletes the xcconfig for a marker written before includes were recorded', () => {
const {appRoot, xcodeprojPath, rnRoot} = scaffoldApp();
injectSpmIntoExistingXcodeproj({
appRoot,
reactNativeRoot: rnRoot,
xcodeprojPath,
});
const marker = readMarker(xcodeprojPath);
delete marker.xcconfig.includedByConfigUuids;
fs.writeFileSync(
path.join(xcodeprojPath, SPM_INJECTED_MARKER),
JSON.stringify(marker, null, 2) + '\n',
);
removeSpmInjection({appRoot, xcodeprojPath});
expect(pbxprojOf(xcodeprojPath)).toBe(PLAIN);
expect(generatedFileContents(appRoot)).toEqual(
GENERATED_FILES.map(() => null),
);
});
// A ${PODS_ROOT}-anchored value resolves empty without CocoaPods, so putting
// it back would only restore a broken setting.
it('does not restore the ${PODS_ROOT}-anchored REACT_NATIVE_PATH it removed', () => {
const {appRoot, xcodeprojPath, rnRoot} = scaffoldApp(
withSetting(
'REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native";',
),
);
injectSpmIntoExistingXcodeproj({
appRoot,
reactNativeRoot: rnRoot,
xcodeprojPath,
});
expect(pbxprojOf(xcodeprojPath)).not.toContain('PODS_ROOT');
expect(
readMarker(xcodeprojPath).xcconfig.removedPodsRootReactNativePath,
).toBe(true);
// Sticky: the update that follows no longer sees the value it removed.
injectSpmIntoExistingXcodeproj({
appRoot,
reactNativeRoot: rnRoot,
xcodeprojPath,
});
expect(
readMarker(xcodeprojPath).xcconfig.removedPodsRootReactNativePath,
).toBe(true);
removeSpmInjection({appRoot, xcodeprojPath});
expect(pbxprojOf(xcodeprojPath)).toBe(PLAIN);
});
it('refuses a setting without $(inherited) and leaves the project untouched', () => {
const {appRoot, xcodeprojPath, rnRoot} = scaffoldApp(
withSetting('HEADER_SEARCH_PATHS = ;'),
);
const before = pbxprojOf(xcodeprojPath);
const result = injectSpmIntoExistingXcodeproj({
appRoot,
reactNativeRoot: rnRoot,
xcodeprojPath,
});
expect(result.status).toBe('refused');
expect(result.reason).toContain('HEADER_SEARCH_PATHS (Debug, Release)');
expect(pbxprojOf(xcodeprojPath)).toBe(before);
expect(fs.existsSync(path.join(xcodeprojPath, SPM_INJECTED_MARKER))).toBe(
false,
);
expect(generatedFileContents(appRoot)).toEqual(
GENERATED_FILES.map(() => null),
);
});
});
// ---------------------------------------------------------------------------
// A project injected before the settings moved to the generated xcconfig
// carries them in project.pbxproj, recorded per configuration in the marker's
// `buildSettingChanges`. The next sync reverses that record first, so the
// project moves over on its own.
// ---------------------------------------------------------------------------
describe('a project injected with settings in project.pbxproj', () => {
const DEBUG = 'AA0000000000000000000901';
const RELEASE = 'AA00000000000000000000A2';
function scaffoldLegacyApp(fields, change) {
const app = scaffoldApp(
fields.length > 0 ? withSetting(fields.join('\n\t\t\t\t')) : PLAIN,
);
fs.writeFileSync(
path.join(app.xcodeprojPath, SPM_INJECTED_MARKER),
JSON.stringify({
target: 'MyApp',
targetUuid: 'AA0000000000000000000301',
injectedUuids: [],
createdArrayFields: [],
buildSettingChanges: [DEBUG, RELEASE].map(configUuid => ({
configUuid,
createdArrayKeys: [],
appendedArrayValues: {},
createdScalars: [],
...change,
})),
}),
);
return app;
}
it('moves them into the generated xcconfig on the next sync', () => {
const {appRoot, xcodeprojPath, rnRoot} = scaffoldLegacyApp(
[
'OTHER_LDFLAGS = (\n\t\t\t\t\t"$(inherited)",\n\t\t\t\t\t"-ObjC",\n\t\t\t\t);',
'REACT_NATIVE_PATH = ../node_modules/react-native;',
'RN_SPM_FLAVOR = debug;',
],
{
createdArrayKeys: ['OTHER_LDFLAGS'],
createdScalars: ['REACT_NATIVE_PATH', 'RN_SPM_FLAVOR'],
},
);
expect(
injectSpmIntoExistingXcodeproj({
appRoot,
reactNativeRoot: rnRoot,
xcodeprojPath,
}).status,
).toBe('injected');
const migrated = pbxprojOf(xcodeprojPath);
expect(migrated).not.toMatch(
/OTHER_LDFLAGS|REACT_NATIVE_PATH|RN_SPM_FLAVOR/,
);
expect(migrated.match(/baseConfigurationReference = /g)).toHaveLength(2);
expect(readMarker(xcodeprojPath)).not.toHaveProperty('buildSettingChanges');
removeSpmInjection({appRoot, xcodeprojPath});
expect(pbxprojOf(xcodeprojPath)).toBe(PLAIN);
});
// The setting the user had before the promotion lacks $(inherited), which
// only shows once the promotion is reversed.
it('refuses when reversing a promotion leaves a setting without $(inherited)', () => {
const {appRoot, xcodeprojPath, rnRoot} = scaffoldLegacyApp(
[
'OTHER_LDFLAGS = (\n\t\t\t\t\t"$(inherited)",\n\t\t\t\t\t"-lc++",\n\t\t\t\t\t"-ObjC",\n\t\t\t\t);',
],
{promotedArrayScalars: {OTHER_LDFLAGS: '"-lc++"'}},
);
const result = injectSpmIntoExistingXcodeproj({
appRoot,
reactNativeRoot: rnRoot,
xcodeprojPath,
});
expect(result.status).toBe('refused');
expect(result.reason).toContain('OTHER_LDFLAGS (Debug, Release)');
});
it('does not resurrect a promoted setting the user has since deleted', () => {
const {appRoot, xcodeprojPath} = scaffoldLegacyApp([], {
promotedArrayScalars: {
HEADER_SEARCH_PATHS: '"$(inherited) $(SRCROOT)/vendor/include"',
},
});
removeSpmInjection({appRoot, xcodeprojPath});
expect(pbxprojOf(xcodeprojPath)).toBe(PLAIN);
});
});
// ---------------------------------------------------------------------------
@@ -1325,10 +1756,9 @@ describe.each(Object.entries(PRE_EXISTING_HEADER_SEARCH_PATHS))(
// findField's token for a BARE scalar ends AT the `;`, so it includes any
// whitespace before it. Deinit must put those bytes back exactly, not a
// tidied-up version of them.
describe.each([
'HEADER_SEARCH_PATHS = $(inherited) ; /* note */',
'HEADER_SEARCH_PATHS = ;',
])('removeSpmInjection with the untrimmed scalar `%s`', field => {
describe('removeSpmInjection with an untrimmed scalar', () => {
const field = 'HEADER_SEARCH_PATHS = $(inherited) ; /* note */';
it('restores it byte-for-byte', () => {
const {appRoot, xcodeprojPath, rnRoot} = scaffoldApp(withSetting(field));
const before = pbxprojOf(xcodeprojPath);
@@ -1345,12 +1775,10 @@ describe.each([
});
});
describe('a scalar array setting injection has nothing to add to', () => {
describe("a list setting of the project's own that keeps $(inherited)", () => {
const SCALAR = 'FRAMEWORK_SEARCH_PATHS = "$(inherited)";';
const EDITED = 'FRAMEWORK_SEARCH_PATHS = "$(inherited) $(SRCROOT)/Vendor";';
// The fixture's flavored-frameworks manifest is empty, so
// FRAMEWORK_SEARCH_PATHS is injected with no values at all.
it('is left untouched, unrecorded, and survives a later user edit', () => {
const {appRoot, xcodeprojPath, rnRoot} = scaffoldApp(withSetting(SCALAR));
@@ -1363,11 +1791,7 @@ describe('a scalar array setting injection has nothing to add to', () => {
const injected = pbxprojOf(xcodeprojPath);
expect(injected).toContain(SCALAR);
expect(injected).not.toMatch(/FRAMEWORK_SEARCH_PATHS = \(/);
for (const change of readMarker(xcodeprojPath).buildSettingChanges) {
expect(change.promotedArrayScalars ?? {}).not.toHaveProperty(
'FRAMEWORK_SEARCH_PATHS',
);
}
expect(markerTextOf(xcodeprojPath)).not.toContain('FRAMEWORK_SEARCH_PATHS');
fs.writeFileSync(
path.join(xcodeprojPath, 'project.pbxproj'),
@@ -1381,70 +1805,3 @@ describe('a scalar array setting injection has nothing to add to', () => {
expect(after).not.toContain(SCALAR);
});
});
describe('a promoted array setting the user deleted after add', () => {
const SCALAR = '"$(inherited) $(SRCROOT)/vendor/include"';
it('is not resurrected by deinit', () => {
const {appRoot, xcodeprojPath, rnRoot} = scaffoldApp(
withHeaderSearchPaths(SCALAR),
);
const before = pbxprojOf(xcodeprojPath);
injectSpmIntoExistingXcodeproj({
appRoot,
reactNativeRoot: rnRoot,
xcodeprojPath,
});
const deleted = pbxprojOf(xcodeprojPath).replace(
/\n\t+HEADER_SEARCH_PATHS = \(\n[\s\S]*?\n\t+\);/g,
'',
);
expect(deleted).not.toContain('HEADER_SEARCH_PATHS');
fs.writeFileSync(
path.join(xcodeprojPath, 'project.pbxproj'),
deleted,
'utf8',
);
removeSpmInjection({appRoot, xcodeprojPath});
// Everything else is back to its pre-injection bytes; only the setting the
// user deleted stays gone.
expect(pbxprojOf(xcodeprojPath)).toBe(
before.replaceAll(`\n\t\t\t\tHEADER_SEARCH_PATHS = ${SCALAR};`, ''),
);
});
});
// `deinit` removes appendedArrayValues before it restores promotedArrayScalars,
// so recording a key under both happens to come out right today: the scalar
// restore rewrites the whole value last. That makes the exclusivity below
// invisible to a round-trip test, which is why it is asserted on the marker
// directly — reversing those two loops would otherwise silently start removing
// array members from an already-restored scalar.
describe('a promoted scalar is recorded once, not twice', () => {
it('records promotedArrayScalars and not appendedArrayValues for the key', () => {
const {appRoot, xcodeprojPath, rnRoot} = scaffoldApp(
withHeaderSearchPaths('"$(inherited) $(SRCROOT)/vendor/include"'),
);
injectSpmIntoExistingXcodeproj({
appRoot,
reactNativeRoot: rnRoot,
xcodeprojPath,
});
const changes = readMarker(xcodeprojPath).buildSettingChanges;
expect(changes.length).toBeGreaterThan(0);
for (const change of changes) {
expect(Object.keys(change.promotedArrayScalars ?? {})).toContain(
'HEADER_SEARCH_PATHS',
);
expect(Object.keys(change.appendedArrayValues ?? {})).not.toContain(
'HEADER_SEARCH_PATHS',
);
}
});
});
@@ -424,6 +424,43 @@ describe('ensureScalarField', () => {
out,
);
});
// Xcode writes an object's fields `isa` first, then alphabetically — landing
// anywhere else plants a diff the next time Xcode saves the project.
it('adds the field directly after `after` when that field exists', () => {
const config = findObjectByUuid(PLAIN_PBXPROJ, 'AA0000000000000000000901');
const out = ensureScalarField(
PLAIN_PBXPROJ,
config,
'baseConfigurationReference',
'DD0000000000000000000101 /* App.xcconfig */',
{after: 'isa'},
);
expect(out).toContain(
'AA0000000000000000000901 /* Debug */ = {\n' +
'\t\t\tisa = XCBuildConfiguration;\n' +
'\t\t\tbaseConfigurationReference = DD0000000000000000000101 /* App.xcconfig */;\n' +
'\t\t\tbuildSettings = {',
);
expect(
removeField(
out,
findObjectByUuid(out, 'AA0000000000000000000901'),
'baseConfigurationReference',
),
).toBe(PLAIN_PBXPROJ);
});
it('falls back to the top of the body when `after` is absent', () => {
const project = findProjectObject(PLAIN_PBXPROJ);
expect(
ensureScalarField(PLAIN_PBXPROJ, project, 'ORGANIZATIONNAME', 'Acme', {
after: 'NO_SUCH_FIELD',
}),
).toBe(
ensureScalarField(PLAIN_PBXPROJ, project, 'ORGANIZATIONNAME', 'Acme'),
);
});
});
describe('setScalarField', () => {
File diff suppressed because it is too large. Load diff
+16 -63
View File
@@ -23,9 +23,12 @@ const {
findField,
findObjectByUuid,
findProjectObject,
forEachObjectInSection,
uuidsInArray,
} = require('./spm-pbxproj');
const {
readXcconfig,
xcconfigIncludePath,
xcconfigReferencePaths,
} = require('./xcconfig-files');
const fs = require('node:fs');
const path = require('node:path');
@@ -87,14 +90,6 @@ function sanitizeIosDeploymentTarget(raw /*: ?string */) /*: string */ {
: MIN_IOS_VERSION_SUPPORTED;
}
function defaultReadFile(absPath /*: string */) /*: ?string */ {
try {
return fs.readFileSync(absPath, 'utf8');
} catch {
return null;
}
}
/**
* `IPHONEOS_DEPLOYMENT_TARGET` as an xcconfig defines it, following `#include`
* lines in place so a later assignment in the includer wins. Null when the file
@@ -116,10 +111,10 @@ function parseXcconfigSetting(
let value /*: ?string */ = null;
for (const rawLine of content.split('\n')) {
const line = rawLine.replace(/\/\/.*$/, '').trim();
const include = line.match(/^#include\??\s+"([^"]+)"/);
if (include != null) {
const includePath = xcconfigIncludePath(absPath, line);
if (includePath != null) {
const included = readXcconfigSetting(
path.resolve(path.dirname(absPath), include[1]),
includePath,
readFile,
visited,
depth + 1,
@@ -154,41 +149,6 @@ function readXcconfigSetting(
: null;
}
/**
* Directory components of the PBXGroup chain holding `uuid`, outermost first —
* how a `"<group>"` file reference's path is anchored to the project dir.
*/
function groupPathPrefix(
text /*: string */,
uuid /*: string */,
) /*: Array<string> */ {
const groups /*: Array<{uuid: string, path: ?string, children: Set<string>}> */ =
[];
forEachObjectInSection(text, 'PBXGroup', ({uuid: groupUuid, ...body}) => {
const children = findField(text, body, 'children');
const groupPath = findField(text, body, 'path');
groups.push({
uuid: groupUuid,
path: groupPath != null ? unquote(groupPath.value) : null,
children: children != null ? uuidsInArray(children.value) : new Set(),
});
});
const parts /*: Array<string> */ = [];
let current = uuid;
for (let i = 0; i < groups.length; i++) {
const parent = groups.find(group => group.children.has(current));
if (parent == null) {
break;
}
if (parent.path != null) {
parts.unshift(parent.path);
}
current = parent.uuid;
}
return parts;
}
/**
* Absolute paths to try for the xcconfig a configuration is based on, in order:
* the reference's own anchoring first, then plain `<srcRoot>/<path>`.
@@ -211,23 +171,16 @@ function xcconfigCandidates(
if (pathField == null) {
return [];
}
const refPath = unquote(pathField.value);
if (path.isAbsolute(refPath)) {
return [refPath];
}
const sourceTreeField = findField(text, ref, 'sourceTree');
const sourceTree =
sourceTreeField != null ? unquote(sourceTreeField.value) : '';
const fallback = path.join(srcRoot, refPath);
if (sourceTree !== '<group>') {
return [fallback];
}
const anchored = path.join(
return xcconfigReferencePaths(
text,
{
uuid: refUuid,
path: unquote(pathField.value),
sourceTree: sourceTreeField != null ? unquote(sourceTreeField.value) : '',
},
srcRoot,
...groupPathPrefix(text, refUuid),
refPath,
);
return anchored === fallback ? [fallback] : [anchored, fallback];
}
function configName(
@@ -300,7 +253,7 @@ function readIosDeploymentTargetFromPbxproj(
) /*: ?string */ {
const ctx /*: XcconfigContext */ = {
srcRoot: opts?.srcRoot,
readFile: opts?.readFile ?? defaultReadFile,
readFile: opts?.readFile ?? readXcconfig,
};
const targetUuid = opts?.targetUuid;
const marked = targetUuid != null ? findObjectByUuid(text, targetUuid) : null;
+8 -3
View File
@@ -530,21 +530,26 @@ function addArrayStringValues(
}
/**
* Add a scalar field after the object's `{` only when ABSENT (never clobbers a
* value the user already set). Returns text unchanged if the key exists.
* Add a scalar field only when ABSENT (never clobbers a value the user already
* set). Returns text unchanged if the key exists. Lands right after the field
* named `after` when the object has one, else after the object's `{`.
*/
function ensureScalarField(
text /*: string */,
obj /*: BodyRange */,
key /*: string */,
value /*: string */,
options /*: {after?: string} */ = {},
) /*: string */ {
if (findField(text, obj, key) != null) {
return text;
}
const fieldIndent = detectFieldIndent(text, obj);
const block = `\n${fieldIndent}${key} = ${value};`;
return text.slice(0, obj.bodyOpen + 1) + block + text.slice(obj.bodyOpen + 1);
const anchor =
options.after != null ? findField(text, obj, options.after) : null;
const at = anchor != null ? anchor.tokenEnd + 1 : obj.bodyOpen + 1;
return text.slice(0, at) + block + text.slice(at);
}
/**
+149
View File
@@ -0,0 +1,149 @@
/**
* 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.
*
* @flow strict-local
* @format
*/
'use strict';
/**
* Where the xcconfig file a project references lives on disk, and the files it
* pulls in through `#include` — resolved the way Xcode resolves them.
*/
const {
findField,
forEachObjectInSection,
uuidsInArray,
} = require('./spm-pbxproj');
const fs = require('node:fs');
const path = require('node:path');
function unquote(value /*: string */) /*: string */ {
return value.replace(/^"|"$/g, '');
}
function readXcconfig(absPath /*: string */) /*: ?string */ {
try {
return fs.readFileSync(absPath, 'utf8');
} catch {
return null;
}
}
/**
* Directory components of the PBXGroup chain holding `uuid`, outermost first —
* how a `"<group>"` file reference's path is anchored to the project dir.
*/
function groupPathPrefix(
text /*: string */,
uuid /*: string */,
) /*: Array<string> */ {
const groups /*: Array<{uuid: string, path: ?string, children: Set<string>}> */ =
[];
forEachObjectInSection(text, 'PBXGroup', ({uuid: groupUuid, ...body}) => {
const children = findField(text, body, 'children');
const groupPath = findField(text, body, 'path');
groups.push({
uuid: groupUuid,
path: groupPath != null ? unquote(groupPath.value) : null,
children: children != null ? uuidsInArray(children.value) : new Set(),
});
});
const parts /*: Array<string> */ = [];
let current = uuid;
for (let i = 0; i < groups.length; i++) {
const parent = groups.find(group => group.children.has(current));
if (parent == null) {
break;
}
if (parent.path != null) {
parts.unshift(parent.path);
}
current = parent.uuid;
}
return parts;
}
/**
* Absolute paths to try for the file a PBXFileReference names, in order: the
* reference's own anchoring first, then plain `<srcRoot>/<path>`. `ref.path`
* and `ref.sourceTree` are unquoted.
*/
function xcconfigReferencePaths(
text /*: string */,
ref /*: {uuid: string, path: string, sourceTree: string} */,
srcRoot /*: string */,
) /*: Array<string> */ {
if (path.isAbsolute(ref.path)) {
return [ref.path];
}
const fallback = path.join(srcRoot, ref.path);
if (ref.sourceTree !== '<group>') {
return [fallback];
}
const anchored = path.join(
srcRoot,
...groupPathPrefix(text, ref.uuid),
ref.path,
);
return anchored === fallback ? [fallback] : [anchored, fallback];
}
/**
* The absolute path an `#include "…"` or `#include? "…"` line of the xcconfig
* at `absPath` names, or null for any other line. Xcode resolves it from the
* folder of the file holding the line.
*/
function xcconfigIncludePath(
absPath /*: string */,
line /*: string */,
) /*: ?string */ {
const include = line
.replace(/\/\/.*$/, '')
.trim()
.match(/^#include\??\s+"([^"]+)"/);
return include != null
? path.resolve(path.dirname(absPath), include[1])
: null;
}
/**
* Whether the xcconfig at `absPath` (holding `content`) pulls in `targetPath`
* through its `#include` chain. An included file that cannot be read ends its
* branch of the chain.
*/
function xcconfigIncludes(
absPath /*: string */,
content /*: string */,
targetPath /*: string */,
visited /*: Set<string> */ = new Set(),
) /*: boolean */ {
visited.add(absPath);
for (const line of content.split('\n')) {
const included = xcconfigIncludePath(absPath, line);
if (included == null || visited.has(included)) {
continue;
}
if (included === path.resolve(targetPath)) {
return true;
}
const next = readXcconfig(included);
if (next != null && xcconfigIncludes(included, next, targetPath, visited)) {
return true;
}
}
return false;
}
module.exports = {
readXcconfig,
xcconfigIncludePath,
xcconfigIncludes,
xcconfigReferencePaths,
};