react-native-tvos 0.88.0-0rc2 → 0.88.1-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/Libraries/Animated/components/AnimatedScrollView.js +2 -2
  2. package/Libraries/AppDelegate/RCTDefaultReactNativeFactoryDelegate.mm +26 -1
  3. package/Libraries/AppDelegate/RCTUIConfiguratorProtocol.h +1 -1
  4. package/Libraries/Components/ActivityIndicator/ActivityIndicator.js +8 -5
  5. package/Libraries/Components/Button.js +4 -2
  6. package/Libraries/Components/Keyboard/KeyboardAvoidingView.js +7 -4
  7. package/Libraries/Components/Pressable/Pressable.js +4 -2
  8. package/Libraries/Components/TextInput/InputAccessoryView.js +8 -6
  9. package/Libraries/Components/TextInput/TextInput.js +5 -5
  10. package/Libraries/Components/Touchable/TouchableWithoutFeedback.js +85 -84
  11. package/Libraries/Components/View/ViewAccessibility.js +8 -4
  12. package/Libraries/Core/ReactNativeVersion.js +2 -2
  13. package/Libraries/Image/ImageProps.js +38 -18
  14. package/Libraries/LogBox/LogBoxNotificationContainer.js +7 -1
  15. package/Libraries/LogBox/UI/LogBoxNotificationDismissButton.js +3 -3
  16. package/Libraries/Modal/Modal.js +4 -2
  17. package/Libraries/StyleSheet/StyleSheet.js +3 -9
  18. package/Libraries/StyleSheet/StyleSheet.js.flow +3 -9
  19. package/Libraries/StyleSheet/StyleSheetTypes.js +12 -9
  20. package/Libraries/StyleSheet/splitLayoutProps.js +6 -6
  21. package/Libraries/Text/Text.js +6 -6
  22. package/React/Base/RCTStatusBarAppearance.h +30 -0
  23. package/React/Base/RCTStatusBarAppearance.mm +66 -0
  24. package/React/Base/RCTVersion.m +2 -2
  25. package/React/CoreModules/RCTStatusBarManager.mm +34 -9
  26. package/React/Fabric/Mounting/ComponentViews/Image/RCTImageComponentView.mm +13 -5
  27. package/React/Fabric/Mounting/ComponentViews/Modal/RCTFabricModalHostViewController.mm +30 -2
  28. package/React/Fabric/Mounting/ComponentViews/Modal/RCTModalHostViewComponentView.mm +9 -0
  29. package/React/Fabric/Mounting/ComponentViews/View/RCTViewComponentView.mm +8 -1
  30. package/ReactAndroid/gradle.properties +1 -1
  31. package/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/ReactNativeVersion.kt +2 -2
  32. package/ReactAndroid/src/main/java/com/facebook/react/uimanager/BaseViewManager.java +16 -2
  33. package/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTypefaceUtils.kt +4 -0
  34. package/ReactAndroid/src/main/java/com/facebook/react/views/text/TextDecorationStyle.kt +32 -4
  35. package/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditText.kt +4 -0
  36. package/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewManager.kt +17 -12
  37. package/ReactAndroid/src/main/res/views/uimanager/values/ids.xml +3 -0
  38. package/ReactApple/RCTSwiftUI/RCTSwiftUIContainerView.swift +4 -0
  39. package/ReactCommon/cxxreact/ReactNativeVersion.h +3 -3
  40. package/ReactCommon/jsi/jsi/decorator.h +64 -0
  41. package/ReactCommon/jsi/jsi/jsi.cpp +2 -4
  42. package/ReactCommon/jsi/jsi/test/testlib.cpp +285 -8
  43. package/ReactCommon/jsi/jsi/test/testlib.h +1 -0
  44. package/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTAttributedTextUtils.mm +2 -1
  45. package/ReactCommon/yoga/yoga/algorithm/CalculateLayout.cpp +6 -2
  46. package/ReactCommon/yoga/yoga/algorithm/PixelGrid.cpp +49 -19
  47. package/package.json +8 -8
  48. package/scripts/cocoapods/utils.rb +51 -0
  49. package/scripts/codegen/templates/Package.swift.spm-template +13 -2
  50. package/scripts/react_native_pods.rb +1 -0
  51. package/scripts/setup-apple-spm.js +10 -5
  52. package/scripts/spm/autolinking-plugins.js +2 -1
  53. package/scripts/spm/flavored-frameworks.js +1 -0
  54. package/scripts/spm/generate-spm-autolinking.js +34 -96
  55. package/scripts/spm/generate-spm-xcodeproj.js +798 -285
  56. package/scripts/spm/ios-deployment-target.js +16 -63
  57. package/scripts/spm/spm-pbxproj.js +8 -3
  58. package/scripts/spm/spm-types.js +2 -15
  59. package/scripts/spm/sync-spm-autolinking.js +57 -23
  60. package/scripts/spm/xcconfig-files.js +149 -0
  61. package/sdks/.hermesv1version +1 -1
  62. package/sdks/hermes-engine/version.properties +1 -1
  63. package/types_DEPRECATED/index.d.ts +1 -0
  64. package/types_DEPRECATED/src/private/assets/AssetRegistry.d.ts +44 -0
  65. package/types_generated/Libraries/Components/ActivityIndicator/ActivityIndicator.d.ts +7 -6
  66. package/types_generated/Libraries/Components/Button.d.ts +30 -29
  67. package/types_generated/Libraries/Components/Keyboard/KeyboardAvoidingView.d.ts +8 -7
  68. package/types_generated/Libraries/Components/Pressable/Pressable.d.ts +6 -5
  69. package/types_generated/Libraries/Components/TextInput/InputAccessoryView.d.ts +7 -6
  70. package/types_generated/Libraries/Components/Touchable/TouchableWithoutFeedback.d.ts +26 -25
  71. package/types_generated/Libraries/Components/View/ViewAccessibility.d.ts +23 -22
  72. package/types_generated/Libraries/Image/ImageProps.d.ts +39 -36
  73. package/types_generated/Libraries/Modal/Modal.d.ts +4 -3
  74. package/types_generated/Libraries/StyleSheet/StyleSheet.d.ts +5 -8
  75. package/types_generated/Libraries/StyleSheet/StyleSheetTypes.d.ts +10 -10
@@ -14,18 +14,23 @@
14
14
  * generate-spm-xcodeproj.js – Surgical, in-place Swift Package Manager
15
15
  * integration toolkit for an existing `<App>.xcodeproj`.
16
16
  *
17
- * `injectSpmIntoExistingXcodeproj` adds the SPM package references, React build
18
- * settings, the "Sync SPM Autolinking" build phase, and a scheme pre-action to
19
- * a user's existing project — purely additively, recording every edit in a
20
- * `.spm-injected.json` marker. `removeSpmInjection` is the exact inverse (used
21
- * by `spm deinit`). Consumed as a library by setup-apple-spm.js; not a CLI.
17
+ * `injectSpmIntoExistingXcodeproj` adds the SPM package references, a generated
18
+ * `.xcconfig` carrying the React build settings, the "Sync SPM Autolinking" build
19
+ * phase, and a scheme pre-action to a user's existing project — purely
20
+ * additively, recording every edit in a `.spm-injected.json` marker.
21
+ * `removeSpmInjection` is the exact inverse (used by `spm deinit`). Consumed as a
22
+ * library by setup-apple-spm.js; not a CLI.
22
23
  */
23
24
 
24
- const {readFlavoredFrameworksManifest} = require('./flavored-frameworks');
25
+ const {
26
+ BUILTIN_FRAMEWORKS,
27
+ FLAVORED_FRAMEWORKS_MANIFEST,
28
+ readFlavoredFrameworksManifest,
29
+ readPluginFrameworks,
30
+ } = require('./flavored-frameworks');
25
31
  const {parseConfigCommandJson} = require('./generate-spm-autolinking-config');
26
32
  const {
27
33
  addArrayMembers,
28
- addArrayStringValues,
29
34
  commentSafe,
30
35
  ensureScalarField,
31
36
  findApplicationTargets,
@@ -49,6 +54,7 @@ const {
49
54
  AUTOLINKED_PACKAGE_NAME,
50
55
  REACT_CODEGEN_APP_PRODUCTS,
51
56
  REACT_CODEGEN_PACKAGE_NAME,
57
+ REACT_CODEGEN_PRODUCTS,
52
58
  REACT_NATIVE_PACKAGE_NAME,
53
59
  REACT_NATIVE_PRODUCTS,
54
60
  isValidScriptPhaseId,
@@ -56,6 +62,11 @@ const {
56
62
  makeLogger,
57
63
  remotePackageConfig,
58
64
  } = require('./spm-utils');
65
+ const {
66
+ readXcconfig,
67
+ xcconfigIncludes,
68
+ xcconfigReferencePaths,
69
+ } = require('./xcconfig-files');
59
70
  const fs = require('node:fs');
60
71
  const path = require('node:path');
61
72
 
@@ -97,6 +108,23 @@ const SPM_SCRIPT_PHASES_MANIFEST = path.join(
97
108
  '.spm-plugin-script-phases.json',
98
109
  );
99
110
 
111
+ // Everything that follows the installed React Native version and frameworks is
112
+ // written to these files on every `spm add`/`update`, so that a routine update
113
+ // leaves project.pbxproj alone — it only references them. Relative to the app
114
+ // root (== SRCROOT). Deliberately NOT under `build/`: that tree holds the SPM
115
+ // package roots (build/xcframeworks, build/generated/autolinking,
116
+ // build/generated/ios) and is gitignored + regenerated by the in-build "Sync
117
+ // SPM Autolinking" phase. These three files are read while Xcode resolves
118
+ // build settings and build-phase scripts — before any build phase has run —
119
+ // so unlike the package roots they cannot be lazily regenerated at build
120
+ // time. They must exist on a fresh clone, so they are committed like
121
+ // project.pbxproj itself.
122
+ const GENERATED_XCCONFIG_PATH = 'ReactNativeSPM/ReactNativeSPM.xcconfig';
123
+ const SYNC_AUTOLINKING_SCRIPT_PATH =
124
+ 'ReactNativeSPM/Scripts/sync-autolinking.sh';
125
+ const EMBED_FRAMEWORKS_SCRIPT_PATH =
126
+ 'ReactNativeSPM/Scripts/embed-flavored-frameworks.sh';
127
+
100
128
  // The single navigator group all injected generated sources are parented under
101
129
  // (created on first use). Its namespacedUUID id + display name.
102
130
  const SPM_GENERATED_SOURCES_GROUP_ID = 'SPMGeneratedSources';
@@ -136,7 +164,9 @@ const SPM_PRODUCT_PACKAGES /*: Array<{product: string, packagePath: string, pack
136
164
  /*::
137
165
  type RemoteCfg = {url: string, version: string, identity: string};
138
166
  // Precise record of the build-setting edits injection made to ONE build config,
139
- // so deinit can reverse exactly those (and nothing the user already had).
167
+ // written by versions that put the React build settings into project.pbxproj
168
+ // directly. Now only read back, so the next sync or deinit can reverse exactly
169
+ // those edits (and nothing the user already had).
140
170
  type BuildSettingChange = {
141
171
  configUuid: string,
142
172
  createdArrayKeys: Array<string>,
@@ -155,6 +185,19 @@ type BuildSettingChange = {
155
185
  // An array field injection CREATED (rather than appended to a pre-existing
156
186
  // one), so deinit removes the whole field and lands byte-identical.
157
187
  type CreatedArrayField = {container: 'project' | 'target', key: string};
188
+ // How the app configurations were based on the generated xcconfig. Deinit
189
+ // clears `baseConfigurationReference` only on these, and only while it still
190
+ // points at `fileRefUuid`. `includedByConfigUuids` keep a base of the user's
191
+ // own whose xcconfig #includes the generated one, so deinit keeps that file;
192
+ // markers written before it existed lack it. `removedPodsRootReactNativePath`
193
+ // is sticky and informational: deinit does not put that value back, because it
194
+ // resolves empty without CocoaPods.
195
+ type XcconfigRecord = {
196
+ fileRefUuid: string,
197
+ configUuids: Array<string>,
198
+ includedByConfigUuids?: Array<string>,
199
+ removedPodsRootReactNativePath: boolean,
200
+ };
158
201
  // A plugin-contributed source, normalized for pbxproj emission. `path` is
159
202
  // SRCROOT-relative when under the app root, else absolute; `sourceTree` is the
160
203
  // matching pbxproj token ('SOURCE_ROOT' or '"<absolute>"').
@@ -354,6 +397,7 @@ function buildConfigurationName(
354
397
  return name.value.replace(/^"|"$/g, '');
355
398
  }
356
399
 
400
+ /** The per-slice framework locations, as xcconfig keys and values. */
357
401
  function frameworkConditionalSettings(
358
402
  frameworks /*: ReadonlyArray<FlavoredFrameworkManifestEntry> */,
359
403
  ) /*: Array<{key: string, value: string}> */ {
@@ -379,17 +423,14 @@ function frameworkConditionalSettings(
379
423
  `${framework.artifactRelativePath}/${slice.libraryIdentifier}`;
380
424
  settings.push(
381
425
  {
382
- key: quoteIfNeeded(`${prefix}_FRAMEWORK${condition}`),
383
- value: quoteIfNeeded(`${root}/${slice.libraryPath}`),
426
+ key: `${prefix}_FRAMEWORK${condition}`,
427
+ value: `${root}/${slice.libraryPath}`,
384
428
  },
385
429
  {
386
- key: quoteIfNeeded(`${prefix}_BINARY${condition}`),
387
- value: quoteIfNeeded(`${root}/${slice.binaryPath}`),
388
- },
389
- {
390
- key: quoteIfNeeded(`${prefix}_SEARCH_PATH${condition}`),
391
- value: quoteIfNeeded(root),
430
+ key: `${prefix}_BINARY${condition}`,
431
+ value: `${root}/${slice.binaryPath}`,
392
432
  },
433
+ {key: `${prefix}_SEARCH_PATH${condition}`, value: root},
393
434
  );
394
435
  };
395
436
  if (slices.length === 1) {
@@ -413,14 +454,16 @@ function frameworkConditionalSettings(
413
454
  return settings;
414
455
  }
415
456
 
416
- function frameworkArrayBuildSettings(
457
+ // List-valued settings, in xcconfig syntax: quotes group a value whose expansion
458
+ // may contain spaces into one list element.
459
+ function frameworkListSettings(
417
460
  frameworks /*: ReadonlyArray<FlavoredFrameworkManifestEntry> */,
418
461
  ) /*: Array<{key: string, values: Array<string>}> */ {
419
462
  return [
420
463
  {
421
464
  key: 'OTHER_LDFLAGS',
422
465
  values: [
423
- '"-ObjC"',
466
+ '-ObjC',
424
467
  ...frameworks.map(
425
468
  framework => `"$(${frameworkSettingPrefix(framework.id)}_BINARY)"`,
426
469
  ),
@@ -434,11 +477,33 @@ function frameworkArrayBuildSettings(
434
477
  },
435
478
  {
436
479
  key: 'LD_RUNPATH_SEARCH_PATHS',
437
- values: ['"@executable_path/Frameworks"'],
480
+ values: ['@executable_path/Frameworks'],
438
481
  },
439
482
  ];
440
483
  }
441
484
 
485
+ function generatedScript(body /*: string */) /*: string */ {
486
+ return `#!/bin/bash
487
+ # Generated by React Native on every \`spm add\` and \`spm update\`.
488
+ # Do not edit: changes are overwritten.
489
+
490
+ ${body}`;
491
+ }
492
+
493
+ // What a build phase runs in place of its generated script, which lives in a
494
+ // file so that the phase itself never changes. The file is committed (see
495
+ // GENERATED_XCCONFIG_PATH's comment) so a fresh clone always has it; the
496
+ // guard below is for the rarer case of a checkout that predates this
497
+ // mechanism, or the file having been deleted by hand.
498
+ function generatedScriptWrapper(scriptPath /*: string */) /*: string */ {
499
+ return `SCRIPT="$SRCROOT/${scriptPath}"
500
+ if [ ! -f "$SCRIPT" ]; then
501
+ echo "error: $SCRIPT is missing. Run 'npx react-native spm update' to generate it."
502
+ exit 1
503
+ fi
504
+ exec /bin/bash "$SCRIPT"`;
505
+ }
506
+
442
507
  function pbxPathList(paths /*: ReadonlyArray<string> */) /*: string */ {
443
508
  if (paths.length === 0) {
444
509
  return '(\n\t\t\t)';
@@ -687,6 +752,9 @@ fi`;
687
752
  // Runtime framework slots are never touched here; add/update owns them.
688
753
  function syncStaleCheckAndDispatch() /*: string */ {
689
754
  return `STAMP="$SRCROOT/build/generated/autolinking/.spm-sync-stamp"
755
+ PLUGIN_MISMATCH="$SRCROOT/build/generated/autolinking/.spm-plugin-mismatch"
756
+ PLUGIN_FRAMEWORKS="$SRCROOT/build/generated/autolinking/.spm-plugin-flavored-frameworks.json"
757
+ MARKER="\${PROJECT_FILE_PATH:-}/${SPM_INJECTED_MARKER}"
690
758
  STALE=0
691
759
 
692
760
  # Find project root (where package.json lives — may be an ancestor of SRCROOT)
@@ -698,10 +766,12 @@ if [ ! -f "$PROJECT_ROOT/package.json" ]; then
698
766
  PROJECT_ROOT="$SRCROOT"
699
767
  fi
700
768
 
701
- # Check 1: dependency inputs (covers app projects after any package manager install)
769
+ # Check 1: dependency inputs (covers app projects after any package manager
770
+ # install), and the marker, which records the frameworks the project links.
702
771
  for INPUT in \\
703
772
  "$PROJECT_ROOT/package.json" \\
704
- "$PROJECT_ROOT/react-native.config.js"; do
773
+ "$PROJECT_ROOT/react-native.config.js" \\
774
+ "$MARKER"; do
705
775
  if [ -f "$INPUT" ] && [ "$INPUT" -nt "$STAMP" ]; then
706
776
  STALE=1
707
777
  break
@@ -785,6 +855,19 @@ if [ "$STALE" -eq 0 ] && [ -f "$WATCH_FILE" ]; then
785
855
  done < "$WATCH_FILE"
786
856
  fi
787
857
 
858
+ # Watched paths that did not exist at the last sync. One that APPEARS (e.g. a
859
+ # plugin's precompiled output folder) forces a re-sync.
860
+ ABSENT_FILE="$SRCROOT/build/generated/autolinking/.spm-sync-watch-absent"
861
+ if [ "$STALE" -eq 0 ] && [ -f "$ABSENT_FILE" ]; then
862
+ while IFS= read -r P; do
863
+ [ -z "$P" ] && continue
864
+ if [ -e "$P" ]; then
865
+ STALE=1
866
+ break
867
+ fi
868
+ done < "$ABSENT_FILE"
869
+ fi
870
+
788
871
  # Check 2: codegen spec files changed via git (covers monorepo after git pull)
789
872
  if [ "$STALE" -eq 0 ] && [ -f "$STAMP" ]; then
790
873
  STAMP_TIME=$(stat -f %m "$STAMP" 2>/dev/null || stat -c %Y "$STAMP" 2>/dev/null || echo 0)
@@ -798,6 +881,20 @@ if [ ! -f "$STAMP" ]; then
798
881
  STALE=1
799
882
  fi
800
883
 
884
+ # The last sync found a plugin framework mismatch and kept its errors. Until an
885
+ # input changes, report them again instead of re-running sync: the scheme
886
+ # pre-action and this build phase would otherwise both run it. spm add/update
887
+ # rewrite the plugin manifest without a sync, so that counts as a change too.
888
+ if [ -f "$PLUGIN_MISMATCH" ]; then
889
+ if [ "$STALE" -eq 0 ] && \\
890
+ [ ! "$MARKER" -nt "$PLUGIN_MISMATCH" ] && \\
891
+ [ ! "$PLUGIN_FRAMEWORKS" -nt "$PLUGIN_MISMATCH" ]; then
892
+ cat "$PLUGIN_MISMATCH" >&2
893
+ exit 1
894
+ fi
895
+ STALE=1
896
+ fi
897
+
801
898
  # Re-sync codegen + autolinking when a dependency input changed. Runtime
802
899
  # framework slots and Xcode linker settings are only changed by spm update.
803
900
  if [ "$STALE" -eq 1 ]; then
@@ -817,7 +914,7 @@ if [ "$STALE" -eq 1 ]; then
817
914
  cd "$SRCROOT"
818
915
  # \`|| RC=$?\` so a non-zero exit is CAPTURED rather than aborting the phase
819
916
  # under \`set -e\` — the whole point is to branch on the code below (2 = fail
820
- # the build with a scaffold hint; other non-zero = warn but don't break).
917
+ # the build; other non-zero = warn but don't break).
821
918
  RC=0
822
919
  if [ -n "$NODE_BINARY" ] && [ -f "$RN_DIR/scripts/setup-apple-spm.js" ]; then
823
920
  # Direct, dependency-free dispatch (no \`npx react-native\`, which needs
@@ -829,10 +926,10 @@ if [ "$STALE" -eq 1 ]; then
829
926
  echo "warning: node/npx not found — skipping SPM sync"
830
927
  fi
831
928
  if [ "$RC" -eq 2 ]; then
832
- # Exit 2 = an autolinked community dependency has no Package.swift. The
833
- # autolinker already printed an \`error:\` line per dep (so Xcode shows them
834
- # and the fix). Fail the build — the developer must run
835
- # \`npx react-native spm scaffold\` from a terminal to generate the manifest.
929
+ # Exit 2 = a problem only a terminal command fixes (e.g. a dependency
930
+ # without Package.swift, or plugin frameworks the project does not link).
931
+ # Sync already printed \`error:\` lines that name the command, so Xcode
932
+ # shows them. Fail the build.
836
933
  exit 1
837
934
  elif [ "$RC" -ne 0 ]; then
838
935
  echo "warning: SPM sync failed — build may use stale codegen/autolinking"
@@ -862,28 +959,21 @@ function buildSyncAutolinkingScript(
862
959
  ${syncStaleCheckAndDispatch()}
863
960
  `;
864
961
  }
865
- // XML-attribute escape (the five named entities). The sync script uses `>`
866
- // and `&` for redirection and bg/and chains, plus `<` for heredocs and
867
- // comparisons — all of which break Xcode's scheme parser if left raw.
962
+ // XML-attribute escape. The sync script uses `>` and `&` for redirection and
963
+ // bg/and chains, plus `<` for heredocs and comparisons — all of which break
964
+ // Xcode's scheme parser if left raw. Raw line breaks and tabs are legal but an
965
+ // XML parser turns them into spaces (XML 1.0 §3.3.3), collapsing the script
966
+ // onto one line, so they are written as character references, as Xcode does.
868
967
  function escapeXmlAttribute(s /*: string */) /*: string */ {
869
968
  return s
870
969
  .replace(/&/g, '&amp;')
871
970
  .replace(/</g, '&lt;')
872
971
  .replace(/>/g, '&gt;')
873
972
  .replace(/"/g, '&quot;')
874
- .replace(/'/g, '&apos;');
875
- }
876
-
877
- // The inverse of escapeXmlAttribute. `&amp;` is expanded LAST so an entity that
878
- // was itself escaped (`&lt;` → `&amp;lt;`) round-trips back to its own text
879
- // rather than to `<`.
880
- function unescapeXmlAttribute(s /*: string */) /*: string */ {
881
- return s
882
- .replace(/&lt;/g, '<')
883
- .replace(/&gt;/g, '>')
884
- .replace(/&quot;/g, '"')
885
- .replace(/&apos;/g, "'")
886
- .replace(/&amp;/g, '&');
973
+ .replace(/'/g, '&apos;')
974
+ .replace(/\r/g, '&#13;')
975
+ .replace(/\n/g, '&#10;')
976
+ .replace(/\t/g, '&#9;');
887
977
  }
888
978
 
889
979
  function generateXcscheme(
@@ -1047,6 +1137,18 @@ function ensureStubPackages(appRoot /*: string */) /*: void */ {
1047
1137
  }
1048
1138
  }
1049
1139
 
1140
+ // Library manifests depend on these products, but the app must not link
1141
+ // them, so they are stubbed here instead of listed in SPM_PRODUCT_PACKAGES.
1142
+ for (const def of byPath.values()) {
1143
+ if (def.packageName === REACT_CODEGEN_PACKAGE_NAME) {
1144
+ for (const product of REACT_CODEGEN_PRODUCTS) {
1145
+ if (!def.products.includes(product)) {
1146
+ def.products.push(product);
1147
+ }
1148
+ }
1149
+ }
1150
+ }
1151
+
1050
1152
  for (const [relPath, def] of byPath) {
1051
1153
  const pkgDir = path.join(appRoot, relPath);
1052
1154
  const pkgSwiftPath = path.join(pkgDir, 'Package.swift');
@@ -1078,24 +1180,25 @@ function ensureStubPackages(appRoot /*: string */) /*: void */ {
1078
1180
  // In-place injection: add SPM packages to a user's EXISTING xcodeproj.
1079
1181
  //
1080
1182
  // This never creates a target or scans sources — it splices the SPM dependency
1081
- // graph, the React build settings, and the sync build phase / scheme pre-action
1082
- // into the project the user already owns, leaving everything else
1183
+ // graph, a reference to the generated xcconfig carrying the React build
1184
+ // settings, and the sync build phase / scheme pre-action into the project the
1185
+ // user already owns, leaving everything else
1083
1186
  // byte-identical. The whole `spm add` / `spm update` xcodeproj strategy, so
1084
1187
  // hand-tuned signing / capabilities / extra targets survive. Fails loud (the
1085
1188
  // caller surfaces the error) when the project is CocoaPods-integrated or its
1086
1189
  // shape can't be safely anchored.
1087
1190
  // ---------------------------------------------------------------------------
1088
1191
 
1089
- // The React build settings the app target needs to compile against the SPM
1090
- // products.
1091
- const INJECTED_ARRAY_SETTINGS = [
1192
+ // The React list settings the app target needs to compile against the SPM
1193
+ // products, in xcconfig syntax.
1194
+ const REACT_LIST_SETTINGS = [
1092
1195
  {
1093
1196
  key: 'HEADER_SEARCH_PATHS',
1094
1197
  values: ['"$(SRCROOT)/build/generated/autolinking/headers"'],
1095
1198
  },
1096
1199
  ];
1097
1200
 
1098
- // Array build settings injected only into debug-flavored configurations.
1201
+ // List settings given only to debug-flavored configurations.
1099
1202
  //
1100
1203
  // Swift's `#if DEBUG` is gated by SWIFT_ACTIVE_COMPILATION_CONDITIONS, NOT by
1101
1204
  // GCC_PREPROCESSOR_DEFINITIONS (which only reaches C/ObjC/C++). The app
@@ -1110,10 +1213,181 @@ const INJECTED_ARRAY_SETTINGS = [
1110
1213
  //
1111
1214
  // Paired with RN_SPM_FLAVOR via flavorForBuildConfiguration, so a config that
1112
1215
  // links the debug xcframeworks also compiles its Swift with DEBUG.
1113
- const DEBUG_ARRAY_SETTINGS = [
1216
+ const DEBUG_LIST_SETTINGS = [
1114
1217
  {key: 'SWIFT_ACTIVE_COMPILATION_CONDITIONS', values: ['DEBUG']},
1115
1218
  ];
1116
1219
 
1220
+ /**
1221
+ * The generated xcconfig every app configuration in `configNames` is based on:
1222
+ * all of the React build settings, shared by every configuration, with the
1223
+ * flavor-specific ones conditioned on each configuration's own name. List
1224
+ * settings extend `$(inherited)`, the project-level value; a target's own
1225
+ * value still outranks all of them (see listSettingsHidingXcconfig).
1226
+ */
1227
+ function generateReactNativeXcconfig(
1228
+ configNames /*: ReadonlyArray<string> */,
1229
+ reactNativePathFromSrcRoot /*: string */,
1230
+ flavoredFrameworks /*: ReadonlyArray<FlavoredFrameworkManifestEntry> */,
1231
+ ) /*: string */ {
1232
+ const listLine = (key /*: string */, values /*: ReadonlyArray<string> */) =>
1233
+ `${key} = ${['$(inherited)', ...values].join(' ')}`;
1234
+ const sections /*: Array<Array<string>> */ = [
1235
+ [
1236
+ '// Generated by React Native on every `spm add` and `spm update`.',
1237
+ '// Do not edit: changes are overwritten.',
1238
+ ],
1239
+ [
1240
+ 'CLANG_CXX_LANGUAGE_STANDARD = c++20',
1241
+ `REACT_NATIVE_PATH = ${['$(SRCROOT)', reactNativePathFromSrcRoot].filter(Boolean).join('/')}`,
1242
+ ],
1243
+ [...REACT_LIST_SETTINGS, ...frameworkListSettings(flavoredFrameworks)]
1244
+ .filter(({values}) => values.length > 0)
1245
+ .map(({key, values}) => listLine(key, values)),
1246
+ [
1247
+ // For a configuration added since the last sync (duplicated in Xcode,
1248
+ // which copies the base reference): flavorForBuildConfiguration's own
1249
+ // fallback, rather than an unset flavor that empties every framework
1250
+ // path.
1251
+ 'RN_SPM_FLAVOR = release',
1252
+ ...configNames.flatMap(name => {
1253
+ const flavor = flavorForBuildConfiguration(name);
1254
+ return [
1255
+ `RN_SPM_FLAVOR[config=${name}] = ${flavor}`,
1256
+ ...(flavor === 'debug' ? DEBUG_LIST_SETTINGS : []).map(
1257
+ ({key, values}) => listLine(`${key}[config=${name}]`, values),
1258
+ ),
1259
+ ];
1260
+ }),
1261
+ ],
1262
+ frameworkConditionalSettings(flavoredFrameworks).map(
1263
+ ({key, value}) => `${key} = ${value}`,
1264
+ ),
1265
+ ];
1266
+ return (
1267
+ sections
1268
+ .filter(lines => lines.length > 0)
1269
+ .map(lines => lines.join('\n'))
1270
+ .join('\n\n') + '\n'
1271
+ );
1272
+ }
1273
+
1274
+ function xcconfigFileRefUuid(rootUuid /*: string */) /*: string */ {
1275
+ return namespacedUUID(rootUuid, 'PBXFileReference', GENERATED_XCCONFIG_PATH);
1276
+ }
1277
+
1278
+ /** A build configuration's `buildSettings` dict, as a body range. */
1279
+ function buildSettingsRange(
1280
+ text /*: string */,
1281
+ configUuid /*: string */,
1282
+ ) /*: ?{bodyOpen: number, bodyClose: number} */ {
1283
+ const config = findObjectByUuid(text, configUuid);
1284
+ const settings =
1285
+ config != null ? findField(text, config, 'buildSettings') : null;
1286
+ return settings != null
1287
+ ? {bodyOpen: settings.valueStart, bodyClose: settings.tokenEnd - 1}
1288
+ : null;
1289
+ }
1290
+
1291
+ /**
1292
+ * The list settings the generated xcconfig sets that a configuration of the
1293
+ * target sets itself without `$(inherited)` — setting → configuration names. A
1294
+ * target's own value outranks the xcconfig it is based on, so each of these
1295
+ * would silently drop the value React Native provides.
1296
+ */
1297
+ function listSettingsHidingXcconfig(
1298
+ text /*: string */,
1299
+ configUuids /*: ReadonlyArray<string> */,
1300
+ ) /*: Map<string, Array<string>> */ {
1301
+ const hiding /*: Map<string, Array<string>> */ = new Map();
1302
+ for (const configUuid of configUuids) {
1303
+ const name = buildConfigurationName(text, configUuid);
1304
+ const settings = buildSettingsRange(text, configUuid);
1305
+ if (settings == null) {
1306
+ continue;
1307
+ }
1308
+ const keys = [
1309
+ ...REACT_LIST_SETTINGS,
1310
+ ...frameworkListSettings([]),
1311
+ ...(flavorForBuildConfiguration(name) === 'debug'
1312
+ ? DEBUG_LIST_SETTINGS
1313
+ : []),
1314
+ ].map(({key}) => key);
1315
+ for (const key of keys) {
1316
+ const field = findField(text, settings, key);
1317
+ if (field != null && !/\$[({]inherited[)}]/.test(field.value)) {
1318
+ hiding.set(key, [...(hiding.get(key) ?? []), name]);
1319
+ }
1320
+ }
1321
+ }
1322
+ return hiding;
1323
+ }
1324
+
1325
+ // Xcode writes a PBXFileReference on one line, which findField can't read.
1326
+ function fileReferenceField(
1327
+ text /*: string */,
1328
+ ref /*: {bodyOpen: number, bodyClose: number, ...} */,
1329
+ key /*: string */,
1330
+ ) /*: ?string */ {
1331
+ const value = new RegExp(
1332
+ `[\\s{;]${key} = ("(?:[^"\\\\]|\\\\.)*"|[^;]*);`,
1333
+ ).exec(text.slice(ref.bodyOpen, ref.bodyClose))?.[1];
1334
+ return value != null ? unquotePlist(value) : null;
1335
+ }
1336
+
1337
+ /**
1338
+ * The app configurations based on an xcconfig other than the generated one —
1339
+ * React Native never edits an xcconfig it does not own, so it cannot base
1340
+ * those configurations on its own. `file` is the reference's path, and
1341
+ * `absPath`/`content` the file on disk when it can be read.
1342
+ */
1343
+ function foreignBaseConfigurations(
1344
+ text /*: string */,
1345
+ configUuids /*: ReadonlyArray<string> */,
1346
+ ownFileRefUuid /*: string */,
1347
+ srcRoot /*: ?string */,
1348
+ ) /*: Array<{configUuid: string, config: string, file: string, onDisk: ?{absPath: string, content: string}}> */ {
1349
+ const foreign = [];
1350
+ for (const configUuid of configUuids) {
1351
+ const config = findObjectByUuid(text, configUuid);
1352
+ const base =
1353
+ config != null
1354
+ ? findField(text, config, 'baseConfigurationReference')
1355
+ : null;
1356
+ const refUuid = base?.value.match(/[0-9A-Fa-f]{24}/)?.[0];
1357
+ if (refUuid == null || refUuid === ownFileRefUuid) {
1358
+ continue;
1359
+ }
1360
+ const ref = findObjectByUuid(text, refUuid);
1361
+ const refPath = ref != null ? fileReferenceField(text, ref, 'path') : null;
1362
+ let onDisk /*: ?{absPath: string, content: string} */ = null;
1363
+ if (ref != null && refPath != null && srcRoot != null) {
1364
+ const candidates = xcconfigReferencePaths(
1365
+ text,
1366
+ {
1367
+ uuid: refUuid,
1368
+ path: refPath,
1369
+ sourceTree: fileReferenceField(text, ref, 'sourceTree') ?? '',
1370
+ },
1371
+ srcRoot,
1372
+ );
1373
+ for (const absPath of candidates) {
1374
+ const content = readXcconfig(absPath);
1375
+ if (content != null) {
1376
+ onDisk = {absPath, content};
1377
+ break;
1378
+ }
1379
+ }
1380
+ }
1381
+ foreign.push({
1382
+ configUuid,
1383
+ config: buildConfigurationName(text, configUuid),
1384
+ file: refPath ?? refUuid,
1385
+ onDisk,
1386
+ });
1387
+ }
1388
+ return foreign;
1389
+ }
1390
+
1117
1391
  /** The XCBuildConfiguration UUIDs of a target (via its buildConfigurationList). */
1118
1392
  function targetBuildConfigUuids(
1119
1393
  text /*: string */,
@@ -1157,8 +1431,11 @@ function configUsesPods(
1157
1431
  * the chosen app target + its config/frameworks anchors, or a refusal reason
1158
1432
  * the caller surfaces (fail-loud).
1159
1433
  */
1160
- function planInjection(text /*: string */, opts /*: {appName?: ?string} */) /*:
1161
- | {ok: true, rootUuid: string, target: {uuid: string, name: string, bodyOpen: number, bodyClose: number}, configUuids: Array<string>, frameworksPhaseUuid: string, sourcesPhaseUuid: ?string}
1434
+ function planInjection(
1435
+ text /*: string */,
1436
+ opts /*: {appName?: ?string, appRoot?: ?string, srcRoot?: ?string} */,
1437
+ ) /*:
1438
+ | {ok: true, rootUuid: string, target: {uuid: string, name: string, bodyOpen: number, bodyClose: number}, configUuids: Array<string>, includedByConfigUuids: Array<string>, frameworksPhaseUuid: string, sourcesPhaseUuid: ?string}
1162
1439
  | {ok: false, reason: string} */ {
1163
1440
  const project = findProjectObject(text);
1164
1441
  if (project == null) {
@@ -1201,6 +1478,55 @@ function planInjection(text /*: string */, opts /*: {appName?: ?string} */) /*:
1201
1478
  'supports SPM-only targets',
1202
1479
  };
1203
1480
  }
1481
+ const generatedXcconfig =
1482
+ opts.appRoot != null
1483
+ ? path.resolve(opts.appRoot, GENERATED_XCCONFIG_PATH)
1484
+ : null;
1485
+ const includedByConfigUuids /*: Array<string> */ = [];
1486
+ for (const foreign of foreignBaseConfigurations(
1487
+ text,
1488
+ configUuids,
1489
+ xcconfigFileRefUuid(project.uuid),
1490
+ opts.srcRoot,
1491
+ )) {
1492
+ const {onDisk} = foreign;
1493
+ if (
1494
+ onDisk != null &&
1495
+ generatedXcconfig != null &&
1496
+ xcconfigIncludes(onDisk.absPath, onDisk.content, generatedXcconfig)
1497
+ ) {
1498
+ includedByConfigUuids.push(foreign.configUuid);
1499
+ continue;
1500
+ }
1501
+ const fix =
1502
+ onDisk != null && generatedXcconfig != null
1503
+ ? `add #include "${path
1504
+ .relative(path.dirname(onDisk.absPath), generatedXcconfig)
1505
+ .split(path.sep)
1506
+ .join('/')}" to ${foreign.file} instead`
1507
+ : `#include ${GENERATED_XCCONFIG_PATH} from ${foreign.file} instead, ` +
1508
+ `with the path relative to the folder that holds ${foreign.file}`;
1509
+ return {
1510
+ ok: false,
1511
+ reason:
1512
+ `the ${foreign.config} configuration is already based on ` +
1513
+ `${foreign.file}, and React Native does not edit xcconfig files it ` +
1514
+ `does not own — ${fix}`,
1515
+ };
1516
+ }
1517
+ const hiding = listSettingsHidingXcconfig(text, configUuids);
1518
+ if (hiding.size > 0) {
1519
+ const listed = [...hiding]
1520
+ .map(([key, configs]) => `${key} (${configs.join(', ')})`)
1521
+ .join(', ');
1522
+ return {
1523
+ ok: false,
1524
+ reason:
1525
+ `the target sets ${listed} without $(inherited), which would hide ` +
1526
+ `the values React Native provides in ${GENERATED_XCCONFIG_PATH} — ` +
1527
+ 'add $(inherited) to each and re-run',
1528
+ };
1529
+ }
1204
1530
  // The target's own Frameworks build phase (where product build files link).
1205
1531
  const buildPhases = findField(text, target, 'buildPhases');
1206
1532
  const phaseUuids =
@@ -1241,26 +1567,29 @@ function planInjection(text /*: string */, opts /*: {appName?: ?string} */) /*:
1241
1567
  rootUuid: project.uuid,
1242
1568
  target,
1243
1569
  configUuids,
1570
+ includedByConfigUuids,
1244
1571
  frameworksPhaseUuid,
1245
1572
  sourcesPhaseUuid,
1246
1573
  };
1247
1574
  }
1248
1575
 
1249
1576
  /**
1250
- * Splice the SPM dependency graph + React build settings + sync build phase
1251
- * into `text` and return the modified pbxproj. Pure string transform (no I/O),
1252
- * idempotent: objects already present (by UUID) and array members / settings
1253
- * already applied are skipped, so a second run is a no-op.
1577
+ * Splice the SPM dependency graph, the generated xcconfig reference and the
1578
+ * build phases into `text`, returning the modified pbxproj together with the
1579
+ * files it references (`generatedFiles`, app-root-relative path → content) for
1580
+ * the caller to write. Pure string transform (no I/O), idempotent: objects
1581
+ * already present (by UUID) and array members / fields already applied are
1582
+ * skipped, so a second run is a no-op.
1254
1583
  */
1255
1584
  function injectSpmIntoPbxproj(
1256
1585
  input /*: string */,
1257
- plan /*: {rootUuid: string, targetUuid: string, configUuids: Array<string>, frameworksPhaseUuid: string, sourcesPhaseUuid?: ?string} */,
1258
- reactNativePath /*: string */,
1586
+ plan /*: {rootUuid: string, targetUuid: string, configUuids: Array<string>, includedByConfigUuids?: ?ReadonlyArray<string>, frameworksPhaseUuid: string, sourcesPhaseUuid?: ?string} */,
1587
+ reactNativePaths /*: {fromAppRoot: string, fromSrcRoot: string} */,
1259
1588
  remote /*: ?RemoteCfg */,
1260
1589
  generatedSources /*: ReadonlyArray<GeneratedSource> */ = [],
1261
1590
  flavoredFrameworks /*: ReadonlyArray<FlavoredFrameworkManifestEntry> */ = [],
1262
1591
  scriptPhases /*: ReadonlyArray<PluginScriptPhase> */ = [],
1263
- ) /*: {text: string, injectedUuids: Array<string>, createdArrayFields: Array<CreatedArrayField>, buildSettingChanges: Array<BuildSettingChange>, generatedSourceUuids: {[string]: Array<string>}, scriptPhaseUuids: {[string]: string}} */ {
1592
+ ) /*: {text: string, injectedUuids: Array<string>, createdArrayFields: Array<CreatedArrayField>, xcconfig: XcconfigRecord, generatedFiles: {[string]: string}, generatedSourceUuids: {[string]: Array<string>}, scriptPhaseUuids: {[string]: string}} */ {
1264
1593
  let text = input;
1265
1594
  const mkUuid = (section /*: string */, id /*: string */) =>
1266
1595
  namespacedUUID(plan.rootUuid, section, id);
@@ -1348,30 +1677,81 @@ function injectSpmIntoPbxproj(
1348
1677
  );
1349
1678
  }
1350
1679
 
1351
- // 5. React build settings into every build config (Debug + Release).
1352
- const buildSettingChanges /*: Array<BuildSettingChange> */ = [];
1680
+ // 5. Every app configuration is based on the generated xcconfig, which
1681
+ // carries all React build settings — except one whose own xcconfig
1682
+ // already #includes it. planInjection refused any other base
1683
+ // configuration, so an existing one here is already ours.
1684
+ const xcconfigName = path.basename(GENERATED_XCCONFIG_PATH);
1685
+ const xcconfigRefUuid = xcconfigFileRefUuid(plan.rootUuid);
1686
+ insertObjects('PBXFileReference', [
1687
+ {
1688
+ uuid: xcconfigRefUuid,
1689
+ comment: xcconfigName,
1690
+ fields: {
1691
+ isa: 'PBXFileReference',
1692
+ lastKnownFileType: 'text.xcconfig',
1693
+ name: xcconfigName,
1694
+ path: GENERATED_XCCONFIG_PATH,
1695
+ sourceTree: 'SOURCE_ROOT',
1696
+ },
1697
+ },
1698
+ ]);
1699
+ const xcconfigGroup = mainGroupObject(text);
1700
+ if (xcconfigGroup != null) {
1701
+ text = addArrayMembers(text, xcconfigGroup, 'children', [
1702
+ {uuid: xcconfigRefUuid, comment: xcconfigName},
1703
+ ]);
1704
+ }
1705
+ const includedBy = new Set(plan.includedByConfigUuids ?? []);
1706
+ let removedPodsRootReactNativePath = false;
1353
1707
  for (const configUuid of plan.configUuids) {
1354
- const merged = mergeReactBuildSettings(
1355
- text,
1356
- configUuid,
1357
- buildConfigurationName(text, configUuid),
1358
- reactNativePath,
1359
- flavoredFrameworks,
1360
- );
1361
- text = merged.text;
1362
- buildSettingChanges.push(merged.change);
1708
+ const config = findObjectByUuid(text, configUuid);
1709
+ if (config != null && !includedBy.has(configUuid)) {
1710
+ text = ensureScalarField(
1711
+ text,
1712
+ config,
1713
+ 'baseConfigurationReference',
1714
+ `${xcconfigRefUuid}${uuidComment(xcconfigName)}`,
1715
+ {after: 'isa'},
1716
+ );
1717
+ }
1718
+ // The CocoaPods template's REACT_NATIVE_PATH is ${PODS_ROOT}-anchored, which
1719
+ // resolves empty once CocoaPods is gone — and a target's own value outranks
1720
+ // the xcconfig's, so it has to go for the working one to apply.
1721
+ const settings = buildSettingsRange(text, configUuid);
1722
+ if (
1723
+ settings != null &&
1724
+ findField(text, settings, 'REACT_NATIVE_PATH')?.value.includes(
1725
+ 'PODS_ROOT',
1726
+ ) === true
1727
+ ) {
1728
+ text = removeField(text, settings, 'REACT_NATIVE_PATH');
1729
+ removedPodsRootReactNativePath = true;
1730
+ }
1363
1731
  }
1732
+ const generatedFiles /*: {[string]: string} */ = {
1733
+ [GENERATED_XCCONFIG_PATH]: generateReactNativeXcconfig(
1734
+ plan.configUuids.map(uuid => buildConfigurationName(text, uuid)),
1735
+ reactNativePaths.fromSrcRoot,
1736
+ flavoredFrameworks,
1737
+ ),
1738
+ [SYNC_AUTOLINKING_SCRIPT_PATH]: generatedScript(
1739
+ buildSyncAutolinkingScript(reactNativePaths.fromAppRoot),
1740
+ ),
1741
+ [EMBED_FRAMEWORKS_SCRIPT_PATH]: generatedScript(
1742
+ buildEmbedFrameworksScript(flavoredFrameworks),
1743
+ ),
1744
+ };
1364
1745
 
1365
1746
  // 6. The Sync SPM Autolinking build phase (safety net; the scheme pre-action
1366
1747
  // is what fires before SPM resolution). Prepended so it runs before
1367
1748
  // Sources. We do NOT add a JS-bundle phase — an existing app already
1368
1749
  // bundles JS via its own phase.
1369
- const syncScript = buildSyncAutolinkingScript(reactNativePath);
1370
1750
  const syncPhaseUuid = mkUuid('PBXShellScriptBuildPhase', 'SyncAutolinking');
1371
1751
  const syncEntry = shellScriptPhase(
1372
1752
  syncPhaseUuid,
1373
1753
  'Sync SPM Autolinking',
1374
- syncScript,
1754
+ generatedScriptWrapper(SYNC_AUTOLINKING_SCRIPT_PATH),
1375
1755
  );
1376
1756
  if (!text.includes(syncPhaseUuid)) {
1377
1757
  text = insertObjectsIntoSection(
@@ -1381,11 +1761,11 @@ function injectSpmIntoPbxproj(
1381
1761
  );
1382
1762
  } else {
1383
1763
  // Already injected on a prior run — the phase object owns these fields,
1384
- // so refresh them in place (same quoting used at creation) in case the
1385
- // generated script changed, or a project injected before shellPath moved
1386
- // to bash (see shellScriptPhase) still has the stale value. Byte-identical
1387
- // when neither did; field order and every other byte of the phase are
1388
- // untouched.
1764
+ // so refresh them in place (same quoting used at creation) in case a
1765
+ // project injected before the script moved to its own file still carries
1766
+ // it inline, or one injected before shellPath moved to bash (see
1767
+ // shellScriptPhase) still has the stale value. Byte-identical when neither
1768
+ // did; field order and every other byte of the phase are untouched.
1389
1769
  for (const key of ['shellScript', 'shellPath']) {
1390
1770
  const current = findObjectByUuid(text, syncPhaseUuid);
1391
1771
  if (current != null) {
@@ -1409,9 +1789,9 @@ function injectSpmIntoPbxproj(
1409
1789
  'PBXShellScriptBuildPhase',
1410
1790
  'EmbedFlavoredFrameworks',
1411
1791
  );
1412
- const embedScript = buildEmbedFrameworksScript(flavoredFrameworks);
1413
1792
  const embedInputs = [
1414
1793
  '$(SRCROOT)/build/xcframeworks/.artifact-stamp',
1794
+ `$(SRCROOT)/${EMBED_FRAMEWORKS_SCRIPT_PATH}`,
1415
1795
  ...flavoredFrameworks.map(
1416
1796
  framework => `$(${frameworkSettingPrefix(framework.id)}_FRAMEWORK)`,
1417
1797
  ),
@@ -1423,7 +1803,7 @@ function injectSpmIntoPbxproj(
1423
1803
  const embedEntry = shellScriptPhase(
1424
1804
  embedPhaseUuid,
1425
1805
  'Embed React Native Flavored Frameworks',
1426
- embedScript,
1806
+ generatedScriptWrapper(EMBED_FRAMEWORKS_SCRIPT_PATH),
1427
1807
  {
1428
1808
  inputPaths: pbxPathList(embedInputs),
1429
1809
  outputPaths: pbxPathList(embedOutputs),
@@ -1556,17 +1936,7 @@ function injectSpmIntoPbxproj(
1556
1936
  // to a pre-existing children array, so no createdArrayField is recorded —
1557
1937
  // deinit removes the group's membership via removeArrayMembersByUuid and
1558
1938
  // the group object itself via removeObjectByUuid (groupUuid is injected).
1559
- const proj = findProjectObject(text);
1560
- const mainGroupField =
1561
- proj != null ? findField(text, proj, 'mainGroup') : null;
1562
- const mainGroupMatch =
1563
- mainGroupField != null
1564
- ? mainGroupField.value.match(/[0-9A-Fa-f]{24}/)
1565
- : null;
1566
- const mainGroupObj =
1567
- mainGroupMatch != null
1568
- ? findObjectByUuid(text, mainGroupMatch[0])
1569
- : null;
1939
+ const mainGroupObj = mainGroupObject(text);
1570
1940
  if (mainGroupObj != null) {
1571
1941
  text = addArrayMembers(text, mainGroupObj, 'children', [
1572
1942
  {uuid: groupUuid, comment: SPM_GENERATED_SOURCES_GROUP_NAME},
@@ -1654,12 +2024,28 @@ function injectSpmIntoPbxproj(
1654
2024
  text,
1655
2025
  injectedUuids,
1656
2026
  createdArrayFields,
1657
- buildSettingChanges,
2027
+ xcconfig: {
2028
+ fileRefUuid: xcconfigRefUuid,
2029
+ configUuids: plan.configUuids.filter(uuid => !includedBy.has(uuid)),
2030
+ includedByConfigUuids: [...includedBy],
2031
+ removedPodsRootReactNativePath,
2032
+ },
2033
+ generatedFiles,
1658
2034
  generatedSourceUuids,
1659
2035
  scriptPhaseUuids,
1660
2036
  };
1661
2037
  }
1662
2038
 
2039
+ function mainGroupObject(
2040
+ text /*: string */,
2041
+ ) /*: ?{uuid: string, bodyOpen: number, bodyClose: number} */ {
2042
+ const project = findProjectObject(text);
2043
+ const mainGroup =
2044
+ project != null ? findField(text, project, 'mainGroup') : null;
2045
+ const uuid = mainGroup?.value.match(/[0-9A-Fa-f]{24}/)?.[0];
2046
+ return uuid != null ? findObjectByUuid(text, uuid) : null;
2047
+ }
2048
+
1663
2049
  /** Re-locate an application target by UUID against the current text. */
1664
2050
  function findApplicationTargetByUuid(
1665
2051
  text /*: string */,
@@ -1672,180 +2058,11 @@ function findApplicationTargetByUuid(
1672
2058
  return obj;
1673
2059
  }
1674
2060
 
1675
- /** Strip the surrounding plist quotes from a build-setting token, if any. */
2061
+ /** Strip the surrounding plist quotes from a token, if any. */
1676
2062
  function unquotePlist(s /*: string */) /*: string */ {
1677
2063
  return s.replace(/^"/, '').replace(/"$/, '');
1678
2064
  }
1679
2065
 
1680
- /**
1681
- * The individual values a build setting already carries, unquoted — for both
1682
- * shapes a pbxproj uses: the array form Xcode writes for a multi-value setting
1683
- * (`("$(inherited)", DEBUG)`) and the scalar form the app template and
1684
- * hand-edits use (`"$(inherited) DEBUG"`). Membership, not substring: the
1685
- * latter would read `MY_DEBUG_FLAG` as `DEBUG` already being set and silently
1686
- * skip the injection.
1687
- */
1688
- function buildSettingValueTokens(value /*: string */) /*: Set<string> */ {
1689
- return new Set(
1690
- value
1691
- .split(/[\s,()]+/)
1692
- .filter(Boolean)
1693
- .map(unquotePlist),
1694
- );
1695
- }
1696
-
1697
- /**
1698
- * Merge the React build settings into one XCBuildConfiguration's dict. Returns
1699
- * the modified text plus a precise record of what was actually added — so
1700
- * `deinit` (removeSpmInjection) can reverse exactly these edits, never touching
1701
- * a value the user already had (key insight: ensureScalarField/
1702
- * addArrayStringValues are no-ops / dedupe when a value is already present).
1703
- */
1704
- function mergeReactBuildSettings(
1705
- input /*: string */,
1706
- configUuid /*: string */,
1707
- configurationName /*: string */,
1708
- reactNativePath /*: string */,
1709
- flavoredFrameworks /*: ReadonlyArray<FlavoredFrameworkManifestEntry> */ = [],
1710
- ) /*: {text: string, change: BuildSettingChange} */ {
1711
- let text = input;
1712
- const scalars = [
1713
- {key: 'CLANG_CXX_LANGUAGE_STANDARD', value: '"c++20"'},
1714
- {key: 'REACT_NATIVE_PATH', value: quoteIfNeeded(reactNativePath)},
1715
- ];
1716
- // Re-locate the buildSettings dict before each edit (offsets shift).
1717
- const dict = () => {
1718
- const cfg = findObjectByUuid(text, configUuid);
1719
- if (cfg == null) {
1720
- return null;
1721
- }
1722
- const bs = findField(text, cfg, 'buildSettings');
1723
- if (bs == null) {
1724
- return null;
1725
- }
1726
- return {
1727
- uuid: configUuid,
1728
- bodyOpen: bs.valueStart,
1729
- bodyClose: bs.tokenEnd - 1,
1730
- };
1731
- };
1732
- const createdArrayKeys /*: Array<string> */ = [];
1733
- const appendedArrayValues /*: {[string]: Array<string>} */ = {};
1734
- const promotedArrayScalars /*: {[string]: string} */ = {};
1735
- const createdScalars /*: Array<string> */ = [];
1736
- const arraySettings = [
1737
- ...INJECTED_ARRAY_SETTINGS,
1738
- ...(flavorForBuildConfiguration(configurationName) === 'debug'
1739
- ? DEBUG_ARRAY_SETTINGS
1740
- : []),
1741
- ...frameworkArrayBuildSettings(flavoredFrameworks),
1742
- ];
1743
- for (const {key, values} of arraySettings) {
1744
- const d = dict();
1745
- if (d == null) {
1746
- continue;
1747
- }
1748
- const existing = findField(text, d, key);
1749
- // Non-null only for a scalar addArrayStringValues would promote to an array
1750
- // (same array-vs-scalar test it uses). Kept RAW: findField's token for a
1751
- // bare scalar ends at the `;`, so it carries any whitespace before it, and
1752
- // deinit has to write those bytes back verbatim.
1753
- const priorScalar =
1754
- existing != null && !existing.value.trimStart().startsWith('(')
1755
- ? existing.value
1756
- : null;
1757
- if (existing == null) {
1758
- createdArrayKeys.push(key);
1759
- } else {
1760
- const present = buildSettingValueTokens(existing.value);
1761
- const fresh = values.filter(v => !present.has(unquotePlist(v)));
1762
- if (fresh.length === 0) {
1763
- // Nothing to add. Skip addArrayStringValues entirely: its dedupe is by
1764
- // EXACT array member, so a value the user carries in the scalar form
1765
- // (`SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) DEBUG"`) would
1766
- // otherwise be promoted to an array and re-appended — an edit `deinit`
1767
- // has no record of and so could never reverse.
1768
- continue;
1769
- }
1770
- if (priorScalar == null) {
1771
- appendedArrayValues[key] = fresh;
1772
- }
1773
- }
1774
- const beforeAdd = text;
1775
- text = addArrayStringValues(text, d, key, values);
1776
- // Record only a promotion that actually happened: addArrayStringValues
1777
- // no-ops when `values` is empty or every value is already a member, and a
1778
- // recorded-but-untouched field would have deinit clobber whatever the user
1779
- // has there by then. Restoring the scalar subsumes removing the injected
1780
- // members, so the two records stay mutually exclusive per key.
1781
- if (priorScalar != null && text !== beforeAdd) {
1782
- promotedArrayScalars[key] = priorScalar;
1783
- }
1784
- }
1785
- const replacedScalars /*: {[string]: string} */ = {};
1786
- for (const {key, value} of scalars) {
1787
- const d = dict();
1788
- if (d == null) {
1789
- continue;
1790
- }
1791
- const existing = findField(text, d, key);
1792
- if (existing == null) {
1793
- createdScalars.push(key);
1794
- } else if (
1795
- key === 'REACT_NATIVE_PATH' &&
1796
- existing.value.includes('PODS_ROOT')
1797
- ) {
1798
- // A ${PODS_ROOT}-anchored REACT_NATIVE_PATH (the CocoaPods template
1799
- // default) dangles once CocoaPods is deintegrated: PODS_ROOT resolves
1800
- // empty at build time, so the Bundle React Native code and images
1801
- // phase looks for "/../…/scripts/xcode/with-environment.sh". Replace
1802
- // it with the SPM-computed path, recording the original for deinit.
1803
- replacedScalars[key] = existing.value;
1804
- text = removeField(text, d, key);
1805
- const d2 = dict();
1806
- if (d2 == null) {
1807
- continue;
1808
- }
1809
- text = ensureScalarField(text, d2, key, value);
1810
- continue;
1811
- }
1812
- text = ensureScalarField(text, d, key, value);
1813
- }
1814
- const ownedScalars = [
1815
- {
1816
- key: 'RN_SPM_FLAVOR',
1817
- value: flavorForBuildConfiguration(configurationName),
1818
- },
1819
- ...frameworkConditionalSettings(flavoredFrameworks),
1820
- ];
1821
- for (const {key, value} of ownedScalars) {
1822
- const d = dict();
1823
- if (d == null) {
1824
- continue;
1825
- }
1826
- const existing = findField(text, d, key);
1827
- if (existing == null) {
1828
- createdScalars.push(key);
1829
- } else if (existing.value !== value) {
1830
- replacedScalars[key] = existing.value;
1831
- }
1832
- text = setScalarField(text, d, key, value);
1833
- }
1834
- return {
1835
- text,
1836
- change: {
1837
- configUuid,
1838
- createdArrayKeys,
1839
- appendedArrayValues,
1840
- createdScalars,
1841
- replacedScalars,
1842
- ...(Object.keys(promotedArrayScalars).length > 0
1843
- ? {promotedArrayScalars}
1844
- : {}),
1845
- },
1846
- };
1847
- }
1848
-
1849
2066
  // Write only when content changed (avoids spurious Xcode reloads / git churn).
1850
2067
  function writeIfChanged(
1851
2068
  filePath /*: string */,
@@ -2226,7 +2443,7 @@ function readScriptPhasesManifest(
2226
2443
  */
2227
2444
  function readMarker(
2228
2445
  xcodeprojPath /*: string */,
2229
- ) /*: ?{targetUuid?: ?string, generatedSources?: {[string]: Array<string>}, scriptPhases?: {[string]: string}, artifactsVersionOverride?: ?string, configCommand?: ?Array<string>, buildSettingChanges?: Array<BuildSettingChange>, createdArrayFields?: Array<CreatedArrayField>, scheme?: {file?: ?string, created?: ?boolean}, ...} */ {
2446
+ ) /*: ?{targetUuid?: ?string, generatedSources?: {[string]: Array<string>}, scriptPhases?: {[string]: string}, linkedFrameworks?: Array<{id: string, frameworkName: string}>, artifactsVersionOverride?: ?string, configCommand?: ?Array<string>, buildSettingChanges?: Array<BuildSettingChange>, xcconfig?: XcconfigRecord, createdArrayFields?: Array<CreatedArrayField>, scheme?: {file?: ?string, created?: ?boolean}, ...} */ {
2230
2447
  const markerPath = path.join(xcodeprojPath, SPM_INJECTED_MARKER);
2231
2448
  try {
2232
2449
  // $FlowFixMe[incompatible-return] JSON.parse returns any
@@ -2262,6 +2479,176 @@ function findInjectedXcodeproj(appRoot /*: string */) /*: string | null */ {
2262
2479
  return null;
2263
2480
  }
2264
2481
 
2482
+ class PluginFrameworkMismatchError extends Error {
2483
+ /*:: problems: Array<string>; */
2484
+ constructor(problems /*: Array<string> */) {
2485
+ super(
2486
+ 'The precompiled frameworks that autolinking plugins provide differ ' +
2487
+ 'from the frameworks that the Xcode project links.',
2488
+ );
2489
+ this.name = 'PluginFrameworkMismatchError';
2490
+ this.problems = problems;
2491
+ }
2492
+ }
2493
+
2494
+ /**
2495
+ * The frameworks the project links: the setting prefix of every one, and the
2496
+ * names of the plugin ones. A marker that records them also pairs each plugin
2497
+ * framework's id with its name. For an older marker they come from the embed
2498
+ * phase, which cannot pair them: null without one, and null names when the
2499
+ * frameworks manifest that tells plugin names from built-in ones is missing.
2500
+ */
2501
+ function readLinkedFrameworks(
2502
+ appRoot /*: string */,
2503
+ xcodeprojPath /*: string */,
2504
+ ) /*: ?{
2505
+ settingPrefixes: Set<string>,
2506
+ pluginNames: ?Set<string>,
2507
+ pluginFrameworks?: Array<{id: string, frameworkName: string}>,
2508
+ } */ {
2509
+ const builtinIds = new Set(BUILTIN_FRAMEWORKS.map(({id}) => id));
2510
+ const recorded = readMarker(xcodeprojPath)?.linkedFrameworks;
2511
+ if (recorded != null) {
2512
+ const pluginFrameworks = recorded.filter(
2513
+ framework => !builtinIds.has(framework.id),
2514
+ );
2515
+ return {
2516
+ settingPrefixes: new Set(
2517
+ recorded.map(framework => frameworkSettingPrefix(framework.id)),
2518
+ ),
2519
+ pluginNames: new Set(
2520
+ pluginFrameworks.map(framework => framework.frameworkName),
2521
+ ),
2522
+ pluginFrameworks,
2523
+ };
2524
+ }
2525
+
2526
+ // Markers written before `linkedFrameworks` existed: read the embed phase.
2527
+ const text = fs.readFileSync(
2528
+ path.join(xcodeprojPath, 'project.pbxproj'),
2529
+ 'utf8',
2530
+ );
2531
+ const rootUuid = findProjectObject(text)?.uuid;
2532
+ if (rootUuid == null) {
2533
+ return null;
2534
+ }
2535
+ const embedPhase = findObjectByUuid(
2536
+ text,
2537
+ namespacedUUID(
2538
+ rootUuid,
2539
+ 'PBXShellScriptBuildPhase',
2540
+ 'EmbedFlavoredFrameworks',
2541
+ ),
2542
+ );
2543
+ if (embedPhase == null) {
2544
+ return null;
2545
+ }
2546
+
2547
+ const inputs = findField(text, embedPhase, 'inputPaths')?.value ?? '';
2548
+ const outputs = findField(text, embedPhase, 'outputPaths')?.value ?? '';
2549
+ const settingPrefixes = new Set(
2550
+ Array.from(inputs.matchAll(/\$\((RN_SPM_\w+)_FRAMEWORK\)/g), m => m[1]),
2551
+ );
2552
+ // Built-in framework names come from the staged manifest. Without it, only
2553
+ // setting prefixes are compared: a missing manifest is not a plugin mismatch.
2554
+ if (
2555
+ !fs.existsSync(
2556
+ path.join(appRoot, 'build', 'xcframeworks', FLAVORED_FRAMEWORKS_MANIFEST),
2557
+ )
2558
+ ) {
2559
+ return {settingPrefixes, pluginNames: null};
2560
+ }
2561
+ const builtinNames = new Set(
2562
+ readFlavoredFrameworksManifest(appRoot)
2563
+ .frameworks.filter(framework => builtinIds.has(framework.id))
2564
+ .map(framework => framework.frameworkName),
2565
+ );
2566
+ const pluginNames = new Set(
2567
+ Array.from(outputs.matchAll(/([^/"\n]+)\.framework\b/g), m => m[1]).filter(
2568
+ name => !builtinNames.has(name),
2569
+ ),
2570
+ );
2571
+ return {settingPrefixes, pluginNames};
2572
+ }
2573
+
2574
+ /**
2575
+ * Only `spm add` / `spm update` change what the project links, so the
2576
+ * build-time sync reports a plugin framework mismatch instead of fixing it.
2577
+ * The committed project is the team's contract: every machine precompiles the
2578
+ * frameworks it links.
2579
+ */
2580
+ function assertPluginFrameworksLinked(
2581
+ appRoot /*: string */,
2582
+ env /*: {readonly [string]: ?string} */ = process.env,
2583
+ ) /*: void */ {
2584
+ const builtProjectPath = env.PROJECT_FILE_PATH;
2585
+ const xcodeprojPath =
2586
+ builtProjectPath != null &&
2587
+ builtProjectPath.endsWith('.xcodeproj') &&
2588
+ fs.existsSync(path.join(builtProjectPath, SPM_INJECTED_MARKER))
2589
+ ? builtProjectPath
2590
+ : findInjectedXcodeproj(appRoot);
2591
+ if (xcodeprojPath == null) {
2592
+ return;
2593
+ }
2594
+ const linked = readLinkedFrameworks(appRoot, xcodeprojPath);
2595
+ if (linked == null) {
2596
+ return;
2597
+ }
2598
+
2599
+ const pluginFrameworks = readPluginFrameworks(appRoot);
2600
+ const pairedNames = new Set(
2601
+ pluginFrameworks.map(framework => framework.frameworkName),
2602
+ );
2603
+ const pairKey = (
2604
+ {id, frameworkName} /*: {id: string, frameworkName: string, ...} */,
2605
+ ) => JSON.stringify([id, frameworkName]);
2606
+ const pairedPairs = new Set(pluginFrameworks.map(pairKey));
2607
+ const problems /*: Array<string> */ = [];
2608
+ for (const {id, frameworkName} of pluginFrameworks) {
2609
+ // A name linked under another id is reported once, from the linked side.
2610
+ const notLinked =
2611
+ linked.pluginFrameworks != null
2612
+ ? linked.pluginNames?.has(frameworkName) === false
2613
+ : !linked.settingPrefixes.has(frameworkSettingPrefix(id)) ||
2614
+ linked.pluginNames?.has(frameworkName) === false;
2615
+ if (notLinked) {
2616
+ problems.push(
2617
+ `error: ${frameworkName} (${id}) is a precompiled framework from an autolinking plugin, but the Xcode project does not link it. Run \`npx react-native spm update\` to add ${frameworkName} to the committed project for the whole team.`,
2618
+ );
2619
+ }
2620
+ }
2621
+ if (linked.pluginNames == null) {
2622
+ console.warn(
2623
+ 'warning: Skipped the check for frameworks that the Xcode project links but no plugin provides. The project does not record them in .spm-injected.json, and build/xcframeworks/flavored-frameworks.json is missing. Run `npx react-native spm update` to record them.',
2624
+ );
2625
+ }
2626
+ for (const frameworkName of linked.pluginNames ?? []) {
2627
+ if (!pairedNames.has(frameworkName)) {
2628
+ // Precompiling changes no input the build checks, so the recorded
2629
+ // error stays until sync runs again.
2630
+ problems.push(
2631
+ `error: The Xcode project links ${frameworkName}.framework, but no autolinking plugin provides it on this machine. Running \`npx react-native spm update\` removes ${frameworkName} from the committed project for the whole team. Instead, precompile ${frameworkName}, then run \`npx react-native spm sync\`.`,
2632
+ );
2633
+ }
2634
+ }
2635
+ for (const framework of linked.pluginFrameworks ?? []) {
2636
+ const {id, frameworkName} = framework;
2637
+ if (
2638
+ pairedNames.has(frameworkName) &&
2639
+ !pairedPairs.has(pairKey(framework))
2640
+ ) {
2641
+ problems.push(
2642
+ `error: The Xcode project links ${frameworkName}.framework (${id}), but the autolinking plugin that provides ${frameworkName} gives it a different id. Run \`npx react-native spm update\` to relink ${frameworkName} in the committed project for the whole team.`,
2643
+ );
2644
+ }
2645
+ }
2646
+ if (problems.length > 0) {
2647
+ problems.forEach(problem => console.error(problem));
2648
+ throw new PluginFrameworkMismatchError(problems);
2649
+ }
2650
+ }
2651
+
2265
2652
  /**
2266
2653
  * Read the `artifactsVersionOverride` a previous `spm add --version` / `spm
2267
2654
  * update --version` pinned into the injected xcodeproj's `.spm-injected.json`
@@ -2341,6 +2728,32 @@ function mergeCreatedArrayFields(
2341
2728
  return merged;
2342
2729
  }
2343
2730
 
2731
+ // The react-native dir the app reaches through `node_modules/react-native`, in
2732
+ // the nearest ancestor of `appRoot` where that link resolves to
2733
+ // `reactNativeRoot`. Config commands report the realpath, which under pnpm is a
2734
+ // version- and hash-named store dir that must not end up in committed files.
2735
+ function linkedReactNativeRoot(
2736
+ appRoot /*: string */,
2737
+ reactNativeRoot /*: string */,
2738
+ ) /*: string */ {
2739
+ try {
2740
+ const target = fs.realpathSync(reactNativeRoot);
2741
+ let dir = path.resolve(appRoot);
2742
+ while (true) {
2743
+ const candidate = path.join(dir, 'node_modules', 'react-native');
2744
+ if (fs.existsSync(candidate) && fs.realpathSync(candidate) === target) {
2745
+ return candidate;
2746
+ }
2747
+ const parent = path.dirname(dir);
2748
+ if (parent === dir) {
2749
+ break;
2750
+ }
2751
+ dir = parent;
2752
+ }
2753
+ } catch {}
2754
+ return reactNativeRoot;
2755
+ }
2756
+
2344
2757
  /**
2345
2758
  * Add SPM packages to a user's EXISTING xcodeproj in place. Returns
2346
2759
  * {status: 'injected', target} on success, or {status: 'refused', reason}
@@ -2358,18 +2771,33 @@ function injectSpmIntoExistingXcodeproj(
2358
2771
  };
2359
2772
  }
2360
2773
  const original = fs.readFileSync(pbxprojPath, 'utf8');
2361
- const plan = planInjection(original, {appName: opts.appName});
2774
+ const prevMarker = readMarker(xcodeprojPath);
2775
+ // A project injected before the React build settings moved to the generated
2776
+ // xcconfig carries them in project.pbxproj. Reversing that record first moves
2777
+ // it over, and has to precede planning: a setting the user had without
2778
+ // $(inherited) only shows again once the promotion that added it is undone.
2779
+ const withoutRecordedSettings = removeRecordedBuildSettings(
2780
+ original,
2781
+ prevMarker?.buildSettingChanges ?? [],
2782
+ );
2783
+ const plan = planInjection(withoutRecordedSettings, {
2784
+ appName: opts.appName,
2785
+ appRoot,
2786
+ srcRoot: path.dirname(xcodeprojPath),
2787
+ });
2362
2788
  if (!plan.ok) {
2363
2789
  return {status: 'refused', reason: plan.reason};
2364
2790
  }
2365
- const reactNativePath = path.relative(appRoot, reactNativeRoot);
2791
+ const reactNativeDir = linkedReactNativeRoot(appRoot, reactNativeRoot);
2792
+ const reactNativePaths = {
2793
+ fromAppRoot: path.relative(appRoot, reactNativeDir),
2794
+ fromSrcRoot: path.relative(path.dirname(xcodeprojPath), reactNativeDir),
2795
+ };
2366
2796
  const remote = remotePackageConfig(appRoot);
2367
2797
  const generatedSources = readGeneratedSourcesManifest(appRoot);
2368
2798
  const scriptPhases = readScriptPhasesManifest(appRoot);
2369
2799
  const flavoredFrameworks = readFlavoredFrameworksManifest(appRoot).frameworks;
2370
2800
 
2371
- const prevMarker = readMarker(xcodeprojPath);
2372
-
2373
2801
  // Reconcile generated sources injected on a PRIOR run that are no longer in
2374
2802
  // the manifest (a plugin's entry was dropped, or the plugin was removed).
2375
2803
  // Diff the marker's `generatedSources` map against the current manifest and
@@ -2404,13 +2832,7 @@ function injectSpmIntoExistingXcodeproj(
2404
2832
  staleUuids.push(prevScriptPhases[id]);
2405
2833
  }
2406
2834
  }
2407
- // Re-apply generated settings from a clean recorded baseline. This removes
2408
- // linker entries for plugin frameworks that disappeared and keeps the new
2409
- // marker a complete inverse after an idempotent update.
2410
- let base = removeRecordedBuildSettings(
2411
- original,
2412
- prevMarker?.buildSettingChanges ?? [],
2413
- );
2835
+ let base = withoutRecordedSettings;
2414
2836
  if (staleUuids.length > 0) {
2415
2837
  base = removeArrayMembersByUuid(base, staleUuids);
2416
2838
  for (const u of staleUuids) {
@@ -2422,7 +2844,8 @@ function injectSpmIntoExistingXcodeproj(
2422
2844
  text,
2423
2845
  injectedUuids,
2424
2846
  createdArrayFields,
2425
- buildSettingChanges,
2847
+ xcconfig,
2848
+ generatedFiles,
2426
2849
  generatedSourceUuids,
2427
2850
  scriptPhaseUuids,
2428
2851
  } = injectSpmIntoPbxproj(
@@ -2431,16 +2854,21 @@ function injectSpmIntoExistingXcodeproj(
2431
2854
  rootUuid: plan.rootUuid,
2432
2855
  targetUuid: plan.target.uuid,
2433
2856
  configUuids: plan.configUuids,
2857
+ includedByConfigUuids: plan.includedByConfigUuids,
2434
2858
  frameworksPhaseUuid: plan.frameworksPhaseUuid,
2435
2859
  sourcesPhaseUuid: plan.sourcesPhaseUuid,
2436
2860
  },
2437
- reactNativePath,
2861
+ reactNativePaths,
2438
2862
  remote,
2439
2863
  generatedSources,
2440
2864
  flavoredFrameworks,
2441
2865
  scriptPhases,
2442
2866
  );
2443
2867
 
2868
+ // Before the project, so an open Xcode that reloads it finds them in place.
2869
+ for (const [relPath, content] of Object.entries(generatedFiles)) {
2870
+ writeIfChanged(path.join(appRoot, relPath), content);
2871
+ }
2444
2872
  const changed = writeIfChanged(pbxprojPath, text);
2445
2873
  log(
2446
2874
  changed
@@ -2455,7 +2883,7 @@ function injectSpmIntoExistingXcodeproj(
2455
2883
  projName,
2456
2884
  // The scheme pre-action is SYNC-ONLY (no flavor swap). A pre-action swap
2457
2885
  // could win its race and mask a mismatch from the in-target detector.
2458
- syncScript: buildSchemePreActionScript(reactNativePath),
2886
+ syncScript: buildSchemePreActionScript(reactNativePaths.fromAppRoot),
2459
2887
  });
2460
2888
  log(`Scheme sync pre-action: ${schemeResult.status}`);
2461
2889
 
@@ -2498,13 +2926,25 @@ function injectSpmIntoExistingXcodeproj(
2498
2926
  prevMarker?.createdArrayFields ?? [],
2499
2927
  createdArrayFields,
2500
2928
  ),
2501
- buildSettingChanges,
2929
+ xcconfig: {
2930
+ ...xcconfig,
2931
+ // Sticky: the next sync no longer sees the value this one removed.
2932
+ removedPodsRootReactNativePath:
2933
+ xcconfig.removedPodsRootReactNativePath ||
2934
+ prevMarker?.xcconfig?.removedPodsRootReactNativePath === true,
2935
+ },
2502
2936
  // Normalized path → [fileRefUuid, buildFileUuid]. Read back on the next
2503
2937
  // `update` to reconcile away entries that left the manifest.
2504
2938
  generatedSources: generatedSourceUuids,
2505
2939
  // Plugin phase id → its PBXShellScriptBuildPhase UUID, reconciled the
2506
2940
  // same way.
2507
2941
  scriptPhases: scriptPhaseUuids,
2942
+ // What the embed phase links. The build-time sync compares it with
2943
+ // the frameworks plugins provide, and re-runs when it changes.
2944
+ linkedFrameworks: flavoredFrameworks.map(({id, frameworkName}) => ({
2945
+ id,
2946
+ frameworkName,
2947
+ })),
2508
2948
  artifactsVersionOverride,
2509
2949
  configCommand,
2510
2950
  scheme: {
@@ -2525,8 +2965,9 @@ function injectSpmIntoExistingXcodeproj(
2525
2965
  return {status: 'injected', target: plan.target.name};
2526
2966
  }
2527
2967
 
2528
- /** The sync pre-action's script, unescaped, or null when the scheme has none. */
2529
- function schemePreActionScript(xml /*: string */) /*: ?string */ {
2968
+ // The scheme with the sync pre-action's scriptText emptied, so the compare
2969
+ // ignores how the script was encoded; null when there is no pre-action.
2970
+ function withoutPreActionScript(xml /*: string */) /*: ?string */ {
2530
2971
  const titleIdx = xml.indexOf('title = "Sync SPM Autolinking"');
2531
2972
  if (titleIdx < 0) {
2532
2973
  return null;
@@ -2540,9 +2981,7 @@ function schemePreActionScript(xml /*: string */) /*: ?string */ {
2540
2981
  // escapeXmlAttribute maps a literal `"` to `&quot;`, so the next `"` is always
2541
2982
  // the closing delimiter.
2542
2983
  const valueEnd = xml.indexOf('"', valueStart);
2543
- return valueEnd < 0
2544
- ? null
2545
- : unescapeXmlAttribute(xml.slice(valueStart, valueEnd));
2984
+ return valueEnd < 0 ? null : xml.slice(0, valueStart) + xml.slice(valueEnd);
2546
2985
  }
2547
2986
 
2548
2987
  /**
@@ -2564,10 +3003,9 @@ function isGeneratedScheme(
2564
3003
  targetUuid /*: string */,
2565
3004
  projName /*: string */,
2566
3005
  ) /*: boolean */ {
2567
- const script = schemePreActionScript(xml);
2568
3006
  return (
2569
- script != null &&
2570
- xml === generateXcscheme(appName, targetUuid, projName, script)
3007
+ withoutPreActionScript(xml) ===
3008
+ generateXcscheme(appName, targetUuid, projName, '')
2571
3009
  );
2572
3010
  }
2573
3011
 
@@ -2666,6 +3104,36 @@ function removeRecordedBuildSettings(
2666
3104
  return text;
2667
3105
  }
2668
3106
 
3107
+ /**
3108
+ * The configurations, by name, that may #include the generated xcconfig once
3109
+ * deinit has un-based its own: those based on any other xcconfig, and those
3110
+ * recorded as including it.
3111
+ */
3112
+ function configsThatMayInclude(
3113
+ text /*: string */,
3114
+ targetUuid /*: string */,
3115
+ xcconfig /*: XcconfigRecord */,
3116
+ ) /*: Array<string> */ {
3117
+ const target = findObjectByUuid(text, targetUuid);
3118
+ const rebased = (
3119
+ target != null ? targetBuildConfigUuids(text, target) : []
3120
+ ).filter(uuid => {
3121
+ const config = findObjectByUuid(text, uuid);
3122
+ const base =
3123
+ config != null
3124
+ ? findField(text, config, 'baseConfigurationReference')
3125
+ : null;
3126
+ return base != null && !base.value.includes(xcconfig.fileRefUuid);
3127
+ });
3128
+ return [
3129
+ ...new Set([...rebased, ...(xcconfig.includedByConfigUuids ?? [])]),
3130
+ ].map(uuid =>
3131
+ findObjectByUuid(text, uuid) != null
3132
+ ? buildConfigurationName(text, uuid)
3133
+ : uuid,
3134
+ );
3135
+ }
3136
+
2669
3137
  /**
2670
3138
  * The exact inverse of `add` (injectSpmIntoExistingXcodeproj): using the
2671
3139
  * `.spm-injected.json` marker's precise record of every edit, remove only what
@@ -2719,10 +3187,52 @@ function removeSpmInjection(
2719
3187
  '',
2720
3188
  );
2721
3189
 
2722
- // 2. Reverse the per-config build-setting edits (only what we added).
3190
+ // 2. Un-base the configurations still based on the generated xcconfig, and
3191
+ // delete it only then, and only while no configuration is based on an
3192
+ // xcconfig of the user's own — that file may #include it, as the ones
3193
+ // recorded in `includedByConfigUuids` do. A ${PODS_ROOT}-anchored
3194
+ // REACT_NATIVE_PATH injection removed is deliberately not put back: it
3195
+ // resolves empty without CocoaPods.
3196
+ const xcconfig /*: ?XcconfigRecord */ = marker.xcconfig;
3197
+ let ownsXcconfig = false;
3198
+ if (xcconfig != null) {
3199
+ for (const configUuid of xcconfig.configUuids) {
3200
+ const config = findObjectByUuid(text, configUuid);
3201
+ if (
3202
+ config != null &&
3203
+ findField(text, config, 'baseConfigurationReference')?.value.includes(
3204
+ xcconfig.fileRefUuid,
3205
+ ) === true
3206
+ ) {
3207
+ text = removeField(text, config, 'baseConfigurationReference');
3208
+ ownsXcconfig = true;
3209
+ }
3210
+ }
3211
+ }
3212
+ const includingConfigs =
3213
+ xcconfig != null
3214
+ ? configsThatMayInclude(text, marker.targetUuid, xcconfig)
3215
+ : [];
3216
+ if (includingConfigs.length > 0) {
3217
+ log(
3218
+ `Kept ${GENERATED_XCCONFIG_PATH}: an xcconfig of your own may still ` +
3219
+ `#include it (configurations: ${includingConfigs.join(', ')})`,
3220
+ );
3221
+ }
3222
+ // Settings a project injected before the generated xcconfig still carries
3223
+ // in project.pbxproj (only what we added).
2723
3224
  text = removeRecordedBuildSettings(text, marker.buildSettingChanges ?? []);
2724
3225
  writeIfChanged(pbxprojPath, text);
2725
3226
  log(`Removed SPM injection from ${path.relative(appRoot, pbxprojPath)}`);
3227
+ for (const relPath of [
3228
+ ...(ownsXcconfig && includingConfigs.length === 0
3229
+ ? [GENERATED_XCCONFIG_PATH]
3230
+ : []),
3231
+ SYNC_AUTOLINKING_SCRIPT_PATH,
3232
+ EMBED_FRAMEWORKS_SCRIPT_PATH,
3233
+ ]) {
3234
+ fs.rmSync(path.join(appRoot, relPath), {force: true});
3235
+ }
2726
3236
 
2727
3237
  // 3. Scheme: delete it if injection created it AND still owns its contents,
2728
3238
  // else strip the pre-action and leave the file (see isGeneratedScheme).
@@ -2765,6 +3275,7 @@ module.exports = {
2765
3275
  flavorForBuildConfiguration,
2766
3276
  targetBuildConfigUuids,
2767
3277
  frameworkConditionalSettings,
3278
+ generateReactNativeXcconfig,
2768
3279
  ensureStubPackages,
2769
3280
  buildSpmDependencyGraph,
2770
3281
  spmGraphToEntries,
@@ -2782,5 +3293,7 @@ module.exports = {
2782
3293
  readArtifactsVersionOverride,
2783
3294
  readPinnedConfigCommand,
2784
3295
  readScriptPhasesManifest,
3296
+ assertPluginFrameworksLinked,
3297
+ PluginFrameworkMismatchError,
2785
3298
  SPM_INJECTED_MARKER,
2786
3299
  };