Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/55301 Replace the brief CONTRIBUTING.md with a comprehensive AGENTS.md that provides AI coding assistants with detailed guidance for working with the react-native-compatibility-check package. The new documentation covers the three-stage pipeline architecture, compatibility rules, testing patterns, and design principles that were previously only partially documented. Changelog: [Internal] Reviewed By: makovkastar Differential Revision: D91275922 fbshipit-source-id: 46fa6d887dd62f4f650d3a77468eb3e864275802
7.2 KiB
AGENTS.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Overview
This package is a type checker for React Native's JS/Native boundary. It detects backwards-incompatible changes between JavaScript and Native code to prevent crashes, particularly useful for:
- Local development (detecting when native rebuild is needed)
- Over-the-air (OTA) updates
- Server Components with React Native
The tool operates on JSON schema files generated by @react-native/codegen, making it agnostic to TypeScript/Flow.
Architecture: Three-Stage Pipeline
The compatibility check flows through three distinct stages:
Schema (new) ──┐
├──▶ TypeDiffing ──▶ VersionDiffing ──▶ ErrorFormatting ──▶ Output
Schema (old) ──┘
Stage 1: TypeDiffing (TypeDiffing.js)
Pure type comparison - Compares two type annotations and returns all structural differences.
- Reports ALL differences between types (added/removed properties, union changes, etc.)
- Returns
ComparisonResultwith status:matching,skipped,properties,members,unionMembers,functionChange,positionalTypeChange,nullableChange, orerror - Must remain pure - no React Native-specific logic belongs here
Stage 2: VersionDiffing (VersionDiffing.js)
Semantic safety analysis - Interprets TypeDiffing results in the context of React Native's boundary.
- Determines if changes are safe based on data flow direction:
toNative: Data flows from JS to Native (method parameters, component props)fromNative: Data flows from Native to JS (return values, getConstants)both: Bidirectional flow
- Encodes compatibility rules:
- Adding to a union sent TO native = UNSAFE (native won't expect it)
- Removing from a union received FROM native = UNSAFE (JS won't handle it)
- Adding optional properties = SAFE
- Making required properties optional when sending TO native = UNSAFE
Stage 3: ErrorFormatting (ErrorFormatting.js)
Human-readable output - Converts deep error objects into formatted strings.
- Must remain pure - no business logic
Supporting Files
ComparisonResult.js: Type definitions for all comparison result shapesDiffResults.js: Type definitions for schema diff results, error codes, and summary typesSortTypeAnnotations.js: Sorting utilities for comparing type annotations in a stable orderconvertPropToBasicTypes.js: Converts Component prop types to standard type annotations for comparisonindex.js: Public API - exportscompareSchemas()returning aCompatCheckResult
Key Type Definitions
// Main comparison statuses
type ComparisonResult =
| {status: 'matching'} // Types are identical
| {status: 'skipped'} // No old type to compare
| {status: 'properties', ...} // Object property changes
| {status: 'members', ...} // Enum member changes
| {status: 'unionMembers', ...} // Union member changes
| {status: 'functionChange', ...}// Function signature changes
| {status: 'error', ...} // Incompatible type change
// Summary statuses
type DiffSummary = {
status: 'ok' | 'patchable' | 'incompatible',
incompatibilityReport: {...}
}
Commands
Run tests from the react-native-compatibility-check directory:
cd packages/react-native-compatibility-check
# Run all tests
yarn test
# Run a specific test file
yarn test src/__tests__/TypeDiffing-test.js
# Run tests matching a pattern
yarn test --testNamePattern="compareTypes on unions"
Meta employees: Use js1 test SUBPATH instead (e.g., js1 test react-native-compatibility-check).
Testing Patterns
Test Fixtures
Tests use Flow files in __tests__/__fixtures__/ parsed by @react-native/codegen:
- Native Modules:
native-module-*/NativeModule.js.flow - Native Components:
native-component-*/NativeComponent.js.flow
The getTestSchema() utility parses these fixtures into schema objects.
Test Structure
- TypeDiffing-test.js: Tests pure type comparison logic
- VersionDiffing-test.js: Tests safety analysis with boundary direction
- ErrorFormatting-test.js: Tests error message generation (uses snapshots)
Adding Test Cases
- Create a new fixture directory under
__tests__/__fixtures__/ - Add a
.js.flowfile defining a Native Module or Component - Load it in tests using
getTestSchema(__dirname, '__fixtures__', 'fixture-name', 'FileName.js.flow')
Design Principles
Separation of Concerns
- TypeDiffing: Pure type comparison. Should work for ANY JavaScript types.
- VersionDiffing: React Native boundary semantics. Only place for RN-specific logic.
- ErrorFormatting: Presentation only. No business logic.
Module-scope Type Registries
TypeDiffing.js uses module-scope variables (_newerTypesReg, _olderTypesReg, _newerEnumMap, _olderEnumMap) to avoid threading lookups through all recursive calls. This is acceptable because the logic is serial.
Structural Type Comparison
Types are compared structurally, not nominally. Two different type aliases with identical structure are considered matching.
Compatibility Rules Reference
Data Flowing TO Native (parameters, props)
| Change | Safe? |
|---|---|
| Add optional property | ✅ |
| Add required property | ❌ |
| Remove property | ✅ |
| Make property optional | ❌ |
| Add union member | ❌ |
| Remove union member | ✅ |
| Add enum member | ❌ |
| Remove enum member | ✅ |
Data Flowing FROM Native (return values, constants)
| Change | Safe? |
|---|---|
| Add optional property | ✅ |
| Add required property | ❌ |
| Remove property | ✅ |
| Make property required | ❌ |
| Add union member | ✅ |
| Remove union member | ❌ |
| Add enum member | ✅ |
| Remove enum member | ❌ |
Common Gotchas
-
Component Commands: Adding/removing commands is intentionally allowed even though it could cause OTA issues, because there's no feature detection mechanism for commands.
-
Union ordering: Unions are sorted before comparison, so
'a' | 'b'equals'b' | 'a'. -
Nullable vs Optional: These are distinct concepts:
- Optional: Property may be absent (
prop?: T) - Nullable: Value may be null/undefined (
prop: ?T)
- Optional: Property may be absent (
-
Type Aliases: Resolved during comparison. Different alias names with identical structure are treated as matching.
-
Component Props with Defaults:
WithDefaulttypes are stripped during comparison - only the underlying type matters for compatibility. -
Int32EnumTypeAnnotation: Currently converted to
AnyTypeAnnotationbecause the tool lacks support for number literal unions.
Adding New Type Support
- Add the type case to
compareTypeAnnotation()inTypeDiffing.js - Add sorting logic in
SortTypeAnnotations.js(compareTypeAnnotationForSorting) - Add formatting in
ErrorFormatting.js(formatTypeAnnotation) - Add test fixtures and tests covering the new type
- If it affects safety analysis, update
VersionDiffing.jschecks
Code Style
- All source files use
@flow strict-localor@flow strict - All source files require
@formatpragma for Prettier - Tests use
@noflowor@flow(not strict)