diff --git a/packages/react-native/React-Core.podspec b/packages/react-native/React-Core.podspec index 63eb78aeb59..88115a1790e 100644 --- a/packages/react-native/React-Core.podspec +++ b/packages/react-native/React-Core.podspec @@ -51,7 +51,6 @@ Pod::Spec.new do |s| s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = min_supported_versions s.source = source - s.resource_bundle = { "RCTI18nStrings" => ["React/I18n/strings/*.lproj"]} s.compiler_flags = js_engine_flags() s.header_dir = "React" s.weak_framework = "JavaScriptCore" @@ -122,7 +121,15 @@ Pod::Spec.new do |s| s.dependency "React-hermes" end - s.resource_bundles = {'React-Core_privacy' => 'React/Resources/PrivacyInfo.xcprivacy'} + # Both bundles in one declaration: a second `resource_bundle(s) =` would replace + # (not merge) the first. RCTI18nStrings holds React-Core's localized strings + # (loaded by RCTLocalizedString); React-Core_privacy is the privacy manifest. + # (Prebuilt/SwiftPM get both from inside React.xcframework instead — see + # scripts/ios-prebuild/framework-resources.js — but source builds ship them here.) + s.resource_bundles = { + 'RCTI18nStrings' => ['React/I18n/strings/*.lproj'], + 'React-Core_privacy' => 'React/Resources/PrivacyInfo.xcprivacy', + } add_dependency(s, "React-runtimeexecutor", :additional_framework_paths => ["platform/ios"]) add_dependency(s, "React-jsinspector", :framework_name => 'jsinspector_modern') diff --git a/packages/react-native/React/I18n/RCTLocalizedString.mm b/packages/react-native/React/I18n/RCTLocalizedString.mm index 6a09613b77a..df87ea02ea5 100644 --- a/packages/react-native/React/I18n/RCTLocalizedString.mm +++ b/packages/react-native/React/I18n/RCTLocalizedString.mm @@ -7,8 +7,45 @@ #import "RCTLocalizedString.h" +#import + #if !defined(WITH_FBI18N) || !(WITH_FBI18N) +// Anchors resource lookups to the bundle that contains this code: React.framework +// when React Native is consumed prebuilt / via SwiftPM, or the app's main bundle +// for static source builds. +@interface RCTI18nStringsAnchor : NSObject +@end +@implementation RCTI18nStringsAnchor +@end + +// Resolves RCTI18nStrings.bundle wherever it ships: the code's own bundle first +// (prebuilt/SwiftPM embed it inside React.framework), then the app's main bundle +// (source builds copy it there via the podspec resource_bundles). Returns nil +// when absent, so the caller falls back to the untranslated default value. +static NSBundle *RCTI18nStringsBundle(void) +{ + NSBundle *codeBundle = [NSBundle bundleForClass:[RCTI18nStringsAnchor class]]; + NSURL *url = [codeBundle URLForResource:@"RCTI18nStrings" withExtension:@"bundle"]; + if (url != nil) { + return [NSBundle bundleWithURL:url]; + } + NSString *mainPath = [[NSBundle mainBundle] pathForResource:@"RCTI18nStrings" ofType:@"bundle"]; + if (mainPath != nil) { + return [NSBundle bundleWithPath:mainPath]; + } +#if RCT_DEV + // Missing resources are otherwise silent (every lookup falls back to the + // untranslated default and the privacy manifest quietly drops out of the + // app's aggregated privacy report). Called once — the caller caches. + RCTLogWarn( + @"RCTI18nStrings.bundle not found in React.framework or the app bundle. Localized strings will use their " + @"untranslated defaults, and React's PrivacyInfo.xcprivacy may be missing from the app's privacy report. " + @"When consuming the prebuilt React.framework, verify it is embedded into the app with its resources intact."); +#endif + return nil; +} + extern "C" { static NSString *FBTStringByConvertingIntegerToBase64(uint64_t number) @@ -33,8 +70,7 @@ __attribute__((noinline)) uint64_t FBcoreLocalexxHash48(const char *input, uint6 NSString *RCTLocalizedStringFromKey(uint64_t key, NSString *defaultValue) { - static NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"RCTI18nStrings" - ofType:@"bundle"]]; + static NSBundle *bundle = RCTI18nStringsBundle(); if (bundle == nil) { return defaultValue; } else { diff --git a/packages/react-native/scripts/cocoapods/rncore_facades.rb b/packages/react-native/scripts/cocoapods/rncore_facades.rb index fa3b935aed4..2016cff9c1e 100644 --- a/packages/react-native/scripts/cocoapods/rncore_facades.rb +++ b/packages/react-native/scripts/cocoapods/rncore_facades.rb @@ -103,18 +103,19 @@ module RNCoreFacades # call once per `pod install`. # # `react_native_path` locates the real podspecs we mirror. version + subspecs + - # default_subspecs + resources are all DERIVED from the real spec so the facade - # stays graph- and resource-equivalent to the source pod. A facaded pod whose - # real podspec can't be read is a hard error (see load_real_spec) — silently - # shipping an empty facade would hide exactly the drift this guards against. + # default_subspecs are DERIVED from the real spec so the facade stays + # graph-equivalent to the source pod (resources are NOT carried — they live in + # the prebuilt artifact; see the note in the loop). A facaded pod whose real + # podspec can't be read is a hard error (see load_real_spec) — silently shipping + # an empty facade would hide exactly the drift this guards against. def self.generate(react_native_path, install_root, version, ios_version) @@install_root = install_root.to_s abs_base = File.join(@@install_root, FACADE_RELDIR) FileUtils.mkdir_p(abs_base) FACADE_PODS.each do |name, podspec_rel_path| podspec_path = File.join(react_native_path.to_s, podspec_rel_path) - real = load_real_spec(podspec_path, name) podspec_dir = File.dirname(podspec_path) + real = load_real_spec(podspec_path, name) dir = File.join(abs_base, name) FileUtils.mkdir_p(dir) @@ -133,17 +134,11 @@ module RNCoreFacades "dependencies" => { "React-Core-prebuilt" => [] }, } - # Preserve non-code RESOURCES (privacy manifest, i18n bundles, ...). They - # don't shadow headers, and React-Core-prebuilt doesn't vend them, so the - # facade must carry them or prebuilt installs lose them. The matched - # files are COPIED into the facade dir (like the re-exposed headers): - # CocoaPods file accessors only match globs against files under the pod - # root, so a `..`-escaping glob back into the source tree would silently - # match nothing and the bundles would ship empty. - resource_bundles = derive_resource_bundles(real, podspec_dir, dir) - spec["resource_bundles"] = resource_bundles unless resource_bundles.empty? - resources = derive_resources(real, podspec_dir, dir) - spec["resources"] = resources unless resources.empty? + # NOTE: the facade carries NO resources. The pods' non-code resources + # (e.g. the privacy manifest) are embedded directly in the prebuilt + # React.xcframework by the ios-prebuild compose (see ios-prebuild/framework-resources.js), + # so they reach both CocoaPods-prebuilt and SwiftPM from the artifact — + # the facade only needs to declare the React-Core-prebuilt dependency. # Re-vend the narrow set of angle-only framework headers that community # modules quote-import (see FACADE_REEXPOSED_HEADERS). The header is @@ -190,8 +185,8 @@ module RNCoreFacades # Loads the real podspec so we can mirror its structure. A facaded pod MUST have # a readable real podspec — if it's missing or unparseable we raise rather than - # ship an empty facade, since that would silently drop subspecs/resources (the - # very drift this mechanism exists to prevent). + # ship an empty facade, since that would silently drop subspecs (the very drift + # this mechanism exists to prevent). def self.load_real_spec(path, name) unless File.exist?(path) raise "[RNCoreFacades] Real podspec for facaded pod '#{name}' not found at #{path}. " \ @@ -212,22 +207,6 @@ module RNCoreFacades end private_class_method :derive_subspecs - # Effective resource_bundles of the real spec (e.g. React-Core_privacy), - # copied into the facade dir under resources//. Unions the - # `resource_bundle` (singular) and `resource_bundles` (plural) DSL forms. - def self.derive_resource_bundles(real, podspec_dir, facade_dir) - out = {} - [real.attributes_hash["resource_bundle"], real.attributes_hash["resource_bundles"]].each do |rb| - next unless rb.is_a?(Hash) - rb.each do |bundle, globs| - copied = copy_resources(Array(globs), podspec_dir, facade_dir, File.join("resources", bundle)) - out[bundle] = copied unless copied.empty? - end - end - out - end - private_class_method :derive_resource_bundles - # Copy the re-exposed header(s) into the facade dir (flat) and return the # facade-relative source_files entries. `globs` are resolved against the real # podspec dir. A glob that matches nothing is a hard error: the whole point is @@ -250,36 +229,4 @@ module RNCoreFacades copied.uniq end private_class_method :copy_reexposed_headers - - # Loose `resources` of the real spec, copied into the facade dir. - def self.derive_resources(real, podspec_dir, facade_dir) - copy_resources(Array(real.attributes_hash["resources"]), podspec_dir, facade_dir, "resources") - end - private_class_method :derive_resources - - # Copies everything the resource globs match (files or whole directories, - # e.g. *.lproj bundles) into `//` and returns - # facade-relative paths for the copies. Globs resolve against the real - # podspec dir. A glob that matches nothing is a hard error: the real spec - # declared a resource, so silently dropping it would make the facade drift. - # rm_rf-before-cp_r keeps the snapshot fresh across repeated `pod install`s. - def self.copy_resources(globs, podspec_dir, facade_dir, subdir) - copied = [] - globs.each do |g| - matches = Dir.glob(File.expand_path(g, podspec_dir)) - if matches.empty? - raise "[RNCoreFacades] Resource glob '#{g}' matched no files under #{podspec_dir}. " \ - "Update the facade resource derivation if the podspec layout changed." - end - dest_dir = File.join(facade_dir, subdir) - FileUtils.mkdir_p(dest_dir) - matches.each do |src| - FileUtils.rm_rf(File.join(dest_dir, File.basename(src))) - FileUtils.cp_r(src, dest_dir) - copied << File.join(subdir, File.basename(src)) - end - end - copied.uniq - end - private_class_method :copy_resources end diff --git a/packages/react-native/scripts/ios-prebuild/__tests__/framework-resources-test.js b/packages/react-native/scripts/ios-prebuild/__tests__/framework-resources-test.js new file mode 100644 index 00000000000..05878f8740c --- /dev/null +++ b/packages/react-native/scripts/ios-prebuild/__tests__/framework-resources-test.js @@ -0,0 +1,371 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + * @noflow + */ + +'use strict'; + +const { + buildI18nStringsBundle, + buildReactPrivacyManifest, + collectLprojDirs, + collectReactPrivacyManifestPaths, + i18nBundleInfoPlist, + mergePrivacyManifests, + readPrivacyManifest, + serializePrivacyManifest, +} = require('../framework-resources'); +const {emitReactFrameworkHeaders} = require('../headers-compose'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +// react-native package root (…/scripts/ios-prebuild/__tests__ -> …) +const RN_PATH = path.resolve(__dirname, '..', '..', '..'); + +// Apple privacy manifest fixtures mirroring the real ones shipped by the pods +// baked into React.framework. +const reactCore = { + NSPrivacyAccessedAPITypes: [ + { + NSPrivacyAccessedAPIType: 'NSPrivacyAccessedAPICategoryFileTimestamp', + NSPrivacyAccessedAPITypeReasons: ['C617.1'], + }, + { + NSPrivacyAccessedAPIType: 'NSPrivacyAccessedAPICategoryUserDefaults', + NSPrivacyAccessedAPITypeReasons: ['CA92.1'], + }, + ], + NSPrivacyCollectedDataTypes: [], + NSPrivacyTracking: false, +}; + +const cxxreact = { + NSPrivacyAccessedAPITypes: [ + { + NSPrivacyAccessedAPIType: 'NSPrivacyAccessedAPICategoryFileTimestamp', + NSPrivacyAccessedAPITypeReasons: ['C617.1'], + }, + ], + NSPrivacyCollectedDataTypes: [], + NSPrivacyTracking: false, +}; + +describe('mergePrivacyManifests', () => { + it('returns a valid empty manifest for no inputs', () => { + expect(mergePrivacyManifests([])).toEqual({ + NSPrivacyAccessedAPITypes: [], + NSPrivacyCollectedDataTypes: [], + NSPrivacyTracking: false, + }); + }); + + it('passes a single manifest through unchanged (by value)', () => { + expect(mergePrivacyManifests([reactCore])).toEqual(reactCore); + }); + + it('unions accessed-API categories, deduping reasons per category', () => { + const merged = mergePrivacyManifests([reactCore, cxxreact]); + const byType = Object.fromEntries( + merged.NSPrivacyAccessedAPITypes.map(e => [ + e.NSPrivacyAccessedAPIType, + e.NSPrivacyAccessedAPITypeReasons, + ]), + ); + // FileTimestamp appears in both -> single entry, reason deduped. + expect(merged.NSPrivacyAccessedAPITypes).toHaveLength(2); + expect(byType.NSPrivacyAccessedAPICategoryFileTimestamp).toEqual([ + 'C617.1', + ]); + expect(byType.NSPrivacyAccessedAPICategoryUserDefaults).toEqual(['CA92.1']); + }); + + it('unions reasons across manifests for the same category', () => { + const a = { + NSPrivacyAccessedAPITypes: [ + { + NSPrivacyAccessedAPIType: 'NSPrivacyAccessedAPICategoryUserDefaults', + NSPrivacyAccessedAPITypeReasons: ['CA92.1'], + }, + ], + }; + const b = { + NSPrivacyAccessedAPITypes: [ + { + NSPrivacyAccessedAPIType: 'NSPrivacyAccessedAPICategoryUserDefaults', + NSPrivacyAccessedAPITypeReasons: ['1C8F.1'], + }, + ], + }; + const merged = mergePrivacyManifests([a, b]); + expect(merged.NSPrivacyAccessedAPITypes).toHaveLength(1); + expect( + merged.NSPrivacyAccessedAPITypes[0].NSPrivacyAccessedAPITypeReasons.sort(), + ).toEqual(['1C8F.1', 'CA92.1']); + }); + + it('ORs NSPrivacyTracking and unions tracking domains', () => { + const a = {NSPrivacyTracking: false, NSPrivacyTrackingDomains: ['a.com']}; + const b = { + NSPrivacyTracking: true, + NSPrivacyTrackingDomains: ['a.com', 'b.com'], + }; + const merged = mergePrivacyManifests([a, b]); + expect(merged.NSPrivacyTracking).toBe(true); + expect(merged.NSPrivacyTrackingDomains.sort()).toEqual(['a.com', 'b.com']); + }); + + it('unions collected data types, deduping structurally-equal entries', () => { + const entry = { + NSPrivacyCollectedDataType: 'NSPrivacyCollectedDataTypeCrashData', + NSPrivacyCollectedDataTypeLinked: false, + }; + const merged = mergePrivacyManifests([ + {NSPrivacyCollectedDataTypes: [entry]}, + {NSPrivacyCollectedDataTypes: [{...entry}]}, + ]); + expect(merged.NSPrivacyCollectedDataTypes).toHaveLength(1); + }); + + it('dedups collected data types regardless of source key order', () => { + // Same dict, different key order (order comes from each plist) must dedup. + const merged = mergePrivacyManifests([ + { + NSPrivacyCollectedDataTypes: [ + { + NSPrivacyCollectedDataType: 'NSPrivacyCollectedDataTypeCrashData', + NSPrivacyCollectedDataTypeLinked: false, + }, + ], + }, + { + NSPrivacyCollectedDataTypes: [ + { + NSPrivacyCollectedDataTypeLinked: false, + NSPrivacyCollectedDataType: 'NSPrivacyCollectedDataTypeCrashData', + }, + ], + }, + ]); + expect(merged.NSPrivacyCollectedDataTypes).toHaveLength(1); + }); + + it('does not fabricate a reasons key when the source omitted it', () => { + const merged = mergePrivacyManifests([ + { + NSPrivacyAccessedAPITypes: [ + {NSPrivacyAccessedAPIType: 'NSPrivacyAccessedAPICategoryOther'}, + ], + }, + ]); + const entry = merged.NSPrivacyAccessedAPITypes[0]; + expect(entry.NSPrivacyAccessedAPIType).toBe( + 'NSPrivacyAccessedAPICategoryOther', + ); + expect('NSPrivacyAccessedAPITypeReasons' in entry).toBe(false); + }); +}); + +describe('serialize/read privacy-manifest round-trip', () => { + it('serialize -> readPrivacyManifest yields the same object (guards the plist.build byte shape)', () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'privacy-rt-')); + const file = path.join(tmp, 'PrivacyInfo.xcprivacy'); + try { + fs.writeFileSync(file, serializePrivacyManifest(reactCore)); + expect(readPrivacyManifest(file)).toEqual(reactCore); + } finally { + fs.rmSync(tmp, {recursive: true, force: true}); + } + }); +}); + +describe('collectReactPrivacyManifestPaths drift gate', () => { + let tmp; + + beforeEach(() => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'privacy-gate-')); + }); + + afterEach(() => { + fs.rmSync(tmp, {recursive: true, force: true}); + }); + + function writeManifest(rel) { + const file = path.join(tmp, rel); + fs.mkdirSync(path.dirname(file), {recursive: true}); + fs.writeFileSync(file, serializePrivacyManifest(reactCore)); + return file; + } + + it('throws when a manifest under the privacy roots is not allowlisted (a new pod must be a conscious decision)', () => { + writeManifest('React/Resources/PrivacyInfo.xcprivacy'); + writeManifest('Libraries/SomeNewPod/PrivacyInfo.xcprivacy'); + expect(() => collectReactPrivacyManifestPaths(tmp)).toThrow(/SomeNewPod/); + expect(() => collectReactPrivacyManifestPaths(tmp)).toThrow( + /REACT_PRIVACY_MANIFESTS/, + ); + }); + + it('returns the found subset of allowlisted manifests (partial trees stay valid)', () => { + const file = writeManifest('React/Resources/PrivacyInfo.xcprivacy'); + expect(collectReactPrivacyManifestPaths(tmp)).toEqual([file]); + }); + + it('returns [] for a tree with no manifests', () => { + expect(collectReactPrivacyManifestPaths(tmp)).toEqual([]); + }); +}); + +describe('buildReactPrivacyManifest (against the real source tree)', () => { + it('discovers React-core PrivacyInfo.xcprivacy files (not third-party deps)', () => { + const paths = collectReactPrivacyManifestPaths(RN_PATH); + expect(paths.length).toBeGreaterThan(0); + // third-party-podspecs manifests belong to ReactNativeDependencies, not React.framework + expect(paths.some(p => p.includes('third-party-podspecs'))).toBe(false); + // React-Core's manifest is the canonical one that must be present + expect( + paths.some(p => p.endsWith('React/Resources/PrivacyInfo.xcprivacy')), + ).toBe(true); + }); + + it('merges them into one manifest covering the known React-core API usages', () => { + const merged = buildReactPrivacyManifest(RN_PATH); + expect(merged).not.toBeNull(); + const categories = (merged?.NSPrivacyAccessedAPITypes ?? []).map( + e => e.NSPrivacyAccessedAPIType, + ); + // FileTimestamp + UserDefaults are declared by React-Core; both must survive the merge. + expect(categories).toContain('NSPrivacyAccessedAPICategoryFileTimestamp'); + expect(categories).toContain('NSPrivacyAccessedAPICategoryUserDefaults'); + // No category should be duplicated after merging. + expect(new Set(categories).size).toBe(categories.length); + }); +}); + +describe('i18nBundleInfoPlist', () => { + it('is a valid resource-bundle Info.plist dict', () => { + const info = i18nBundleInfoPlist(); + expect(info.CFBundlePackageType).toBe('BNDL'); + expect(info.CFBundleName).toBe('RCTI18nStrings'); + expect(typeof info.CFBundleIdentifier).toBe('string'); + expect(info.CFBundleIdentifier.length).toBeGreaterThan(0); + expect(typeof info.CFBundleDevelopmentRegion).toBe('string'); + // Versioned so Apple validation tooling doesn't warn on a version-less bundle. + expect(info.CFBundleShortVersionString).toBeDefined(); + expect(info.CFBundleVersion).toBeDefined(); + }); +}); + +describe('collectLprojDirs (against the real source tree)', () => { + it('finds the React i18n .lproj locale dirs', () => { + const dirs = collectLprojDirs(RN_PATH); + expect(dirs.length).toBeGreaterThan(0); + expect(dirs.every(d => d.endsWith('.lproj'))).toBe(true); + // English is the canonical base locale and must be present. + expect(dirs.some(d => path.basename(d) === 'en.lproj')).toBe(true); + }); +}); + +describe('buildI18nStringsBundle', () => { + let tmp; + + beforeEach(() => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'i18n-bundle-')); + }); + + afterEach(() => { + fs.rmSync(tmp, {recursive: true, force: true}); + }); + + it('builds RCTI18nStrings.bundle with the .lproj dirs and an Info.plist', () => { + const out = path.join(tmp, 'RCTI18nStrings.bundle'); + const count = buildI18nStringsBundle(RN_PATH, out); + + expect(count).toBeGreaterThan(0); + expect(fs.existsSync(path.join(out, 'Info.plist'))).toBe(true); + expect(fs.existsSync(path.join(out, 'en.lproj'))).toBe(true); + // the copied locale carries its actual strings file(s) + expect(fs.readdirSync(path.join(out, 'en.lproj')).length).toBeGreaterThan( + 0, + ); + // count matches the number of .lproj dirs copied + const copied = fs.readdirSync(out).filter(e => e.endsWith('.lproj')); + expect(copied.length).toBe(count); + }); + + it('returns 0 and writes nothing when there are no .lproj dirs', () => { + const emptyRn = fs.mkdtempSync(path.join(os.tmpdir(), 'empty-rn-')); + const out = path.join(tmp, 'RCTI18nStrings.bundle'); + const count = buildI18nStringsBundle(emptyRn, out); + expect(count).toBe(0); + expect(fs.existsSync(out)).toBe(false); + fs.rmSync(emptyRn, {recursive: true, force: true}); + }); +}); + +describe('emitReactFrameworkHeaders resource landing (integration)', () => { + let tmp; + let rnRoot; + let xcfw; + + beforeEach(() => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'emit-res-')); + + // Minimal fake source tree: one privacy manifest + one locale. + rnRoot = path.join(tmp, 'rn'); + const privacyDir = path.join(rnRoot, 'React', 'Resources'); + fs.mkdirSync(privacyDir, {recursive: true}); + fs.writeFileSync( + path.join(privacyDir, 'PrivacyInfo.xcprivacy'), + serializePrivacyManifest(reactCore), + ); + const lproj = path.join(rnRoot, 'React', 'I18n', 'strings', 'en.lproj'); + fs.mkdirSync(lproj, {recursive: true}); + fs.writeFileSync( + path.join(lproj, 'Localizable.strings'), + '"key" = "value";\n', + ); + + // Two-slice xcframework, each carrying an empty React.framework. + xcfw = path.join(tmp, 'React.xcframework'); + for (const slice of ['ios-arm64', 'ios-arm64_x86_64-simulator']) { + fs.mkdirSync(path.join(xcfw, slice, 'React.framework'), { + recursive: true, + }); + } + }); + + afterEach(() => { + fs.rmSync(tmp, {recursive: true, force: true}); + }); + + it('lands PrivacyInfo.xcprivacy and RCTI18nStrings.bundle into EVERY slice', () => { + // Empty header plan — this test targets the non-header resources only. + emitReactFrameworkHeaders( + xcfw, + { + react: [], + umbrella: [], + privateReactHeaders: {modular: [], textual: []}, + }, + rnRoot, + ); + + for (const slice of ['ios-arm64', 'ios-arm64_x86_64-simulator']) { + const fwk = path.join(xcfw, slice, 'React.framework'); + expect(fs.existsSync(path.join(fwk, 'PrivacyInfo.xcprivacy'))).toBe(true); + const bundle = path.join(fwk, 'RCTI18nStrings.bundle'); + expect(fs.existsSync(path.join(bundle, 'Info.plist'))).toBe(true); + expect(fs.existsSync(path.join(bundle, 'en.lproj'))).toBe(true); + // The composed module map is present too (proves the slice was rewritten). + expect(fs.existsSync(path.join(fwk, 'Modules', 'module.modulemap'))).toBe( + true, + ); + } + }); +}); diff --git a/packages/react-native/scripts/ios-prebuild/framework-resources.js b/packages/react-native/scripts/ios-prebuild/framework-resources.js new file mode 100644 index 00000000000..41e70bc1389 --- /dev/null +++ b/packages/react-native/scripts/ios-prebuild/framework-resources.js @@ -0,0 +1,306 @@ +/** + * 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 + * @format + */ + +/** + * Non-header resources that the prebuild embeds into React.framework so the + * prebuilt artifact is self-describing for both CocoaPods-prebuilt and SwiftPM. + * + * In source builds each pod ships these via its podspec `resource_bundles`. In + * the prebuilt path the source pods aren't installed (CocoaPods facades) / not + * present (SwiftPM), so we reproduce them from the source tree at compose time: + * + * - Privacy manifest: the pods baked into React.framework each ship a + * PrivacyInfo.xcprivacy; we merge them into ONE manifest at the framework + * root, where Xcode's privacy-report aggregation picks it up (no runtime). + * - RCTI18nStrings: React-Core's localized strings (React/I18n/strings/*.lproj) + * rebuilt as RCTI18nStrings.bundle inside the framework, where the + * framework-aware RCTLocalizedString loader resolves them via bundleForClass:. + */ + +const fs = require('fs'); +const path = require('path'); +const plist = require('plist'); + +// Source roots whose pods compile into React.framework. third-party-podspecs is +// intentionally excluded — those (boost/glog/RCT-Folly) live in +// ReactNativeDependencies.xcframework and are aggregated there. +const REACT_PRIVACY_ROOTS = ['React', 'ReactCommon', 'Libraries', 'ReactApple']; + +// The privacy manifests of the pods that compile INTO React.framework — +// an EXPLICIT allowlist, not a glob: a PrivacyInfo.xcprivacy that appears +// under REACT_PRIVACY_ROOTS without being listed here fails the prebuild, +// forcing a conscious decision. A pod whose sources compile into +// React.framework belongs on this list; a pod that ships as its OWN framework +// must NOT have its manifest folded into React.framework's aggregate +// (over-declaration in the app's privacy report). +const REACT_PRIVACY_MANIFESTS = [ + path.join('React', 'Resources', 'PrivacyInfo.xcprivacy'), + path.join('ReactCommon', 'cxxreact', 'PrivacyInfo.xcprivacy'), + path.join('ReactCommon', 'react', 'timing', 'PrivacyInfo.xcprivacy'), +]; + +// Where React-Core's localized strings live, relative to the package root. +const STRINGS_REL = path.join('React', 'I18n', 'strings'); + +/*:: +type AccessedAPIType = { + NSPrivacyAccessedAPIType: string, + NSPrivacyAccessedAPITypeReasons?: Array, + ... +}; +type PrivacyManifest = { + NSPrivacyAccessedAPITypes?: Array, + NSPrivacyCollectedDataTypes?: Array, + NSPrivacyTracking?: boolean, + NSPrivacyTrackingDomains?: Array, + ... +}; +*/ + +// --------------------------------------------------------------------------- +// Privacy manifest +// --------------------------------------------------------------------------- + +// Recursively sorts object keys so structurally-equal values serialize +// identically regardless of source key order (arrays keep their order). +function canonicalize(value /*: unknown */) /*: unknown */ { + if (Array.isArray(value)) { + return value.map(canonicalize); + } + if (value != null && typeof value === 'object') { + const out /*: {[string]: unknown} */ = {}; + for (const k of Object.keys(value).sort()) { + out[k] = canonicalize(value[k]); + } + return out; + } + return value; +} + +/** + * Merges Apple privacy manifests into one. Pure; operates on parsed plist + * objects. Semantics: + * - NSPrivacyAccessedAPITypes: keyed by category; reasons unioned (deduped). + * - NSPrivacyCollectedDataTypes: unioned, deduped structurally. + * - NSPrivacyTrackingDomains: unioned (deduped); omitted when empty. + * - NSPrivacyTracking: logical OR. + */ +function mergePrivacyManifests( + manifests /*: Array */, +) /*: PrivacyManifest */ { + const reasonsByType /*: Map> */ = new Map(); + // Categories where at least one source actually declared the reasons key, so + // a source that omitted it doesn't get a fabricated empty-array key on the way + // out (keeps "a single manifest passes through unchanged" honest). + const typeHadReasonsKey /*: Set */ = new Set(); + const typeOrder /*: Array */ = []; + const trackingDomains /*: Set */ = new Set(); + const collected /*: Array */ = []; + const collectedSeen /*: Set */ = new Set(); + let tracking = false; + + for (const manifest of manifests) { + if (manifest == null) { + continue; + } + for (const entry of manifest.NSPrivacyAccessedAPITypes ?? []) { + const category = entry.NSPrivacyAccessedAPIType; + if (!reasonsByType.has(category)) { + reasonsByType.set(category, []); + typeOrder.push(category); + } + const entryReasons = entry.NSPrivacyAccessedAPITypeReasons; + if (entryReasons != null) { + typeHadReasonsKey.add(category); + const reasons = reasonsByType.get(category); + if (reasons != null) { + for (const reason of entryReasons) { + if (!reasons.includes(reason)) { + reasons.push(reason); + } + } + } + } + } + for (const domain of manifest.NSPrivacyTrackingDomains ?? []) { + trackingDomains.add(domain); + } + for (const dataType of manifest.NSPrivacyCollectedDataTypes ?? []) { + // Canonicalize (sort object keys recursively) before keying so two pods + // declaring the same data-type dict in different key order still dedup. + // The `?? ''` is unreachable at runtime (canonicalize of a plist dict + // never yields undefined) — it exists purely because Flow types + // JSON.stringify as `string | void`. + const key = JSON.stringify(canonicalize(dataType)) ?? ''; + if (!collectedSeen.has(key)) { + collectedSeen.add(key); + collected.push(dataType); + } + } + if (manifest.NSPrivacyTracking === true) { + tracking = true; + } + } + + const merged /*: PrivacyManifest */ = { + NSPrivacyAccessedAPITypes: typeOrder.map(category => { + const entry /*: AccessedAPIType */ = { + NSPrivacyAccessedAPIType: category, + }; + if (typeHadReasonsKey.has(category)) { + entry.NSPrivacyAccessedAPITypeReasons = + reasonsByType.get(category) ?? []; + } + return entry; + }), + NSPrivacyCollectedDataTypes: collected, + NSPrivacyTracking: tracking, + }; + if (trackingDomains.size > 0) { + merged.NSPrivacyTrackingDomains = Array.from(trackingDomains); + } + return merged; +} + +/** Parses a single `PrivacyInfo.xcprivacy` (plist) file into an object. */ +function readPrivacyManifest(filePath /*: string */) /*: PrivacyManifest */ { + // $FlowFixMe[incompatible-return] plist.parse returns a loose PlistValue. + return plist.parse(fs.readFileSync(filePath, 'utf8')); +} + +/** + * Finds every `PrivacyInfo.xcprivacy` under the React-core source roots of + * `reactNativePath` (excluding third-party deps). Sorted for deterministic output. + */ +function collectReactPrivacyManifestPaths( + reactNativePath /*: string */, +) /*: Array */ { + const found /*: Array */ = []; + for (const root of REACT_PRIVACY_ROOTS) { + const dir = path.join(reactNativePath, root); + if (!fs.existsSync(dir)) { + continue; + } + for (const rel of fs.readdirSync(dir, {recursive: true})) { + if (path.basename(String(rel)) === 'PrivacyInfo.xcprivacy') { + found.push(path.join(root, String(rel))); + } + } + } + const unlisted = found.filter(rel => !REACT_PRIVACY_MANIFESTS.includes(rel)); + if (unlisted.length > 0) { + throw new Error( + 'React.framework privacy-manifest drift: found PrivacyInfo.xcprivacy ' + + 'file(s) under the React privacy roots that are not allowlisted:\n' + + unlisted.map(rel => ` ${rel}`).join('\n') + + '\nIf the owning pod compiles into React.framework, add the path to ' + + 'REACT_PRIVACY_MANIFESTS in framework-resources.js. If it ships as ' + + 'its own framework, its manifest must NOT be folded into ' + + "React.framework's aggregate — relocate it out of the privacy roots " + + 'or exclude it explicitly.', + ); + } + // A listed-but-absent manifest is legal (partial fixture trees; upstream + // deletions surface as under-declaration exactly like source builds would). + // A MOVED manifest cannot slip through: its new location is unlisted. + return found.map(rel => path.join(reactNativePath, rel)).sort(); +} + +/** + * Builds the aggregated React.framework privacy manifest from the source pods, + * or null when there are none. + */ +function buildReactPrivacyManifest( + reactNativePath /*: string */, +) /*: ?PrivacyManifest */ { + const paths = collectReactPrivacyManifestPaths(reactNativePath); + if (paths.length === 0) { + return null; + } + return mergePrivacyManifests(paths.map(readPrivacyManifest)); +} + +/** Serializes a manifest object back to a plist XML string. */ +function serializePrivacyManifest( + manifest /*: PrivacyManifest */, +) /*: string */ { + return plist.build(manifest); +} + +// --------------------------------------------------------------------------- +// RCTI18nStrings bundle +// --------------------------------------------------------------------------- + +/** The Info.plist contents that make the copied .lproj dirs load as an NSBundle. */ +function i18nBundleInfoPlist() /*: {[string]: string} */ { + return { + CFBundleDevelopmentRegion: 'en', + CFBundleIdentifier: 'org.reactnative.RCTI18nStrings', + CFBundleInfoDictionaryVersion: '6.0', + CFBundleName: 'RCTI18nStrings', + CFBundlePackageType: 'BNDL', + // Present so Apple validation tooling doesn't warn on a version-less bundle. + CFBundleShortVersionString: '1.0', + CFBundleVersion: '1', + }; +} + +/** Absolute paths of the React i18n `.lproj` locale dirs, sorted. */ +function collectLprojDirs(reactNativePath /*: string */) /*: Array */ { + const stringsDir = path.join(reactNativePath, STRINGS_REL); + if (!fs.existsSync(stringsDir)) { + return []; + } + return fs + .readdirSync(stringsDir, {withFileTypes: true}) + .filter(e => e.isDirectory() && String(e.name).endsWith('.lproj')) + .map(e => path.join(stringsDir, String(e.name))) + .sort(); +} + +/** + * Builds `RCTI18nStrings.bundle` at `outBundlePath` from the React i18n .lproj + * dirs + an Info.plist. Returns the number of locales copied (0 when there are + * none, in which case nothing is written). + */ +function buildI18nStringsBundle( + reactNativePath /*: string */, + outBundlePath /*: string */, +) /*: number */ { + const lprojDirs = collectLprojDirs(reactNativePath); + if (lprojDirs.length === 0) { + return 0; + } + fs.rmSync(outBundlePath, {recursive: true, force: true}); + fs.mkdirSync(outBundlePath, {recursive: true}); + for (const lproj of lprojDirs) { + fs.cpSync(lproj, path.join(outBundlePath, path.basename(lproj)), { + recursive: true, + }); + } + fs.writeFileSync( + path.join(outBundlePath, 'Info.plist'), + plist.build(i18nBundleInfoPlist()), + ); + return lprojDirs.length; +} + +module.exports = { + // privacy manifest + mergePrivacyManifests, + readPrivacyManifest, + collectReactPrivacyManifestPaths, + buildReactPrivacyManifest, + serializePrivacyManifest, + // RCTI18nStrings bundle + i18nBundleInfoPlist, + collectLprojDirs, + buildI18nStringsBundle, +}; diff --git a/packages/react-native/scripts/ios-prebuild/headers-compose.js b/packages/react-native/scripts/ios-prebuild/headers-compose.js index 23b4af4441e..a67e74216e2 100644 --- a/packages/react-native/scripts/ios-prebuild/headers-compose.js +++ b/packages/react-native/scripts/ios-prebuild/headers-compose.js @@ -17,6 +17,12 @@ * byte-identical output either way. */ +const { + buildI18nStringsBundle, + buildReactPrivacyManifest, + collectLprojDirs, + serializePrivacyManifest, +} = require('./framework-resources'); const {computeInventory} = require('./headers-inventory'); const { DEPS_NAMESPACES, @@ -138,6 +144,28 @@ function emitReactFrameworkHeaders( const slices = fs .readdirSync(xcfwPath) .filter(d => fs.existsSync(path.join(xcfwPath, d, 'React.framework'))); + + // Aggregate the privacy manifests of the pods baked into React.framework into + // one root-level PrivacyInfo.xcprivacy, so the prebuilt artifact carries them + // for both CocoaPods-prebuilt and SwiftPM (source builds get them from the + // podspecs instead). Built once, embedded per slice. + const privacyManifest = buildReactPrivacyManifest(rnRoot); + + // Build RCTI18nStrings.bundle ONCE into a temp stage, then clone it into each + // slice below — mirrors the privacy manifest (computed once, embedded per + // slice) instead of rebuilding the bundle inside the slice loop. The stage is + // only created when there are locales to bundle. + let i18nStage = null; + let i18nBundleStage = null; + let i18nLocales = 0; + if (collectLprojDirs(rnRoot).length > 0) { + i18nStage = fs.mkdtempSync( + path.join(path.dirname(xcfwPath), '.i18n-stage-'), + ); + i18nBundleStage = path.join(i18nStage, 'RCTI18nStrings.bundle'); + i18nLocales = buildI18nStringsBundle(rnRoot, i18nBundleStage); + } + for (const slice of slices) { const fwk = path.join(xcfwPath, slice, 'React.framework'); fs.rmSync(path.join(fwk, 'Headers'), {recursive: true, force: true}); @@ -148,11 +176,29 @@ function emitReactFrameworkHeaders( path.join(fwk, 'Modules', 'module.modulemap'), renderReactModuleMap(plan.privateReactHeaders), ); + if (privacyManifest != null) { + fs.writeFileSync( + path.join(fwk, 'PrivacyInfo.xcprivacy'), + serializePrivacyManifest(privacyManifest), + ); + } + // Clone the prebuilt RCTI18nStrings.bundle so the framework-aware + // RCTLocalizedString loader resolves React-Core's strings in prebuilt/SPM. + if (i18nLocales > 0 && i18nBundleStage != null) { + const dest = path.join(fwk, 'RCTI18nStrings.bundle'); + fs.rmSync(dest, {recursive: true, force: true}); + execFileSync('/bin/cp', [CP_FLAGS, i18nBundleStage, dest]); + } } fs.rmSync(stage, {recursive: true, force: true}); + if (i18nStage != null) { + fs.rmSync(i18nStage, {recursive: true, force: true}); + } console.log( `headers-compose: React.framework spec layout -> ${slices.join(', ')} ` + - `(${plan.react.length} headers, umbrella ${plan.umbrella.length})`, + `(${plan.react.length} headers, umbrella ${plan.umbrella.length}` + + `${privacyManifest != null ? ', +PrivacyInfo.xcprivacy' : ''}` + + `${i18nLocales > 0 ? `, +RCTI18nStrings.bundle (${i18nLocales} locales)` : ''})`, ); }