Files
react-native/packages/react-native-codegen/src/CodegenSchema.d.ts
T
Eli WhiteandFacebook GitHub Bot 25c673e357 Fixing schema types for component command params of Arrays (#48476)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/48476

Command param array types were generating invalid schemas due to untyped parser code. The invalid schemas occurred for any alias type, including custom objects and basics like Int32. This was also inconsistent between Flow and TypeScript.

We already had one component utilizing this issue, so this just codifies that support into the schema so it reflects reality. This is only a partial solution. The more full solution would be to fully encode the custom types in the schemas like we do for Native Modules.

# More Information:

Tl;dr, DebuggingOverlay is abusing a FlowFixMe in codegen commands.

## The problem:

The [CodegenSchema](https://www.internalfb.com/code/fbsource/[d3ab2f79b377]/xplat/js/react-native-github/packages/react-native-codegen/src/CodegenSchema.js?lines=220) should be the source of truth for anything that can be in the schema. If something is in the schema that isn't allowed by the types, that's a bug. We have a bug. I'm adding compat-check support for components and it's blowing up on prod schemas because DebuggingOverlay causes an invalid schema.

## The details:

Support for Arrays as arguments in commands was added to the Codegen in D51866557. [Code Pointer](https://fburl.com/code/8yy1rm0p)

The intention appears to be to support arrays of primitives. There is a TODO for supporting complex types.

```
interface NativeCommands {
  +addOverlays: (
    viewRef: React.ElementRef<NativeType>,
    overlayColorsReadOnly: $ReadOnlyArray<string>,
  )
}
```

This support was added to TypeScript in D52046165 where it types the allowed Array arguments to be only

```
{
    readonly type: 'ArrayTypeAnnotation';
    readonly elementType:
    | Int32TypeAnnotation
    | DoubleTypeAnnotation
    | FloatTypeAnnotation
    | BooleanTypeAnnotation
    | StringTypeAnnotation
  };
```

However, because the Parsers are treating the input type as `any`, it isn't safe to pass through an input value into the schema as Flow won't catch mismatches.

The Flow parser just passes it through:

```
{
    type: 'ArrayTypeAnnotation',
    elementType: {
    // TODO: T172453752 support complex type annotation for array element
    type: paramValue.typeParameters.params[0].type,
}
```

Whereas the TypeScript parser has the more correct behavior of validating the inputs and returning specific outputs. Unfortunately, the return type is also typed here as $FlowFixMe, losing most of the benefits.

```
function getPrimitiveTypeAnnotation(type: string): $FlowFixMe {
  switch (type) {
    case 'Int32':
      return {
        type: 'Int32TypeAnnotation',
      };
    case 'Double':
      return {
        type: 'DoubleTypeAnnotation',
      };
    case 'Float':
      return {
        type: 'FloatTypeAnnotation',
      };
    case 'TSBooleanKeyword':
      return {
        type: 'BooleanTypeAnnotation',
      };
    case 'Stringish':
    case 'TSStringKeyword':
      return {
        type: 'StringTypeAnnotation',
      };
    default:
      throw new Error(`Unknown primitive type "${type}"`);
  }
}
```

[DebuggingOverlay](https://fburl.com/code/zfe3ipq7) is abusing this gap in the Flow parser by sticking an Array of Objects in.

```
export type ElementRectangle = {
  x: number,
  y: number,
  width: number,
  height: number,
};

...
  +highlightElements: (
    viewRef: React.ElementRef<DebuggingOverlayNativeComponentType>,
    elements: $ReadOnlyArray<ElementRectangle>,
  ) => void;
...
```

This isn't allowed in the schema, but it seems to fall through the holes of the flow parser and generators.

The resulting schema from Flow is this. Note the GenericTypeAnnotation which isn't allowed to be in the schema.

```
{
    "name": "highlightElements",
    "optional": false,
    "typeAnnotation": {
    "type": "FunctionTypeAnnotation",
    "params": [
        {
            "name": "elements",
            "optional": false,
            "typeAnnotation": {
                "type": "ArrayTypeAnnotation",
                "elementType": {
                    "type": "GenericTypeAnnotation"
                }
            }
        }
    ],
    "returnTypeAnnotation": {
        "type": "VoidTypeAnnotation"
    }
},
```

The TypeScript parser fails with `Error: Unsupported type annotation: GenericTypeAnnotation`.

The generators don't seem to check beyond the ArrayTypeAnnotation so they fall through to generating generic arrays.

```
// ios
elements:(const NSArray *)elements

// android
ReadableArray locations
```

## So how do I fix this?

I think there are a couple of different options here. The key problem is that the Schema types need to represent reality of what can be in the schema.

1. We revert DebuggingOverlay to not use features that aren't supported (I assume nobody would be happy with this, but the change shouldn't have been made in the first place)
2. **(This is the approach taken in this diff)** We add MixedTypeAnnotation to the allowed types in Command arrays and have it generate that and add official support for that to the TypeScript parser as well. That is probably the quickest and easiest approach. It leaves the same type unsafety we have today on the native side.
3. NativeModules seem to have a lot more complex type safety here. They persist the alias type in the schema so that the CompatCheck can check them on changes. And then in C++ they generate structs and RCTConvert functions although for Java and ObjC it looks like they just use the same untyped native code. The matching approach here would be to add `aliasMap` and the whole data to the schema for commands, use that for the compat check, and still generate the same unsafe native code.

```
export type ObjectAlias = {|
  x: number,
  y: number,
|};

export interface Spec extends TurboModule {
  +getAlias: (a: ObjectAlias) => string;
}
```

stores the ObjectAlias in the schema

```
{
  "aliasMap": {
    "ObjectAlias": {
      "type": "ObjectTypeAnnotation",
      "properties": [
        {
          "name": "x",
          "optional": false,
          "typeAnnotation": {
            "type": "NumberTypeAnnotation"
          }
        },
        {
          "name": "y",
          "optional": false,
          "typeAnnotation": {
            "type": "NumberTypeAnnotation"
          }
        },
      ]
    }
  },
  "spec": {
    "methods": [
      {
        "name": "getAlias",
        "optional": false,
        "typeAnnotation": {
          "type": "FunctionTypeAnnotation",
          "returnTypeAnnotation": {
            "type": "StringTypeAnnotation"
          },
          "params": [
            {
              "name": "a",
              "optional": false,
              "typeAnnotation": {
                "type": "TypeAliasTypeAnnotation",
                "name": "ObjectAlias"
              }
            }
          ]
        }
      }
    ]
  }
}
```

and then generates the appropriate structs on the native side and generates [this](https://www.internalfb.com/code/fbsource/[d3ab2f79b377]/xplat/js/react-native-github/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleHObjCpp-test.js.snap?lines=818)

```

Reviewed By: hoxyq

Differential Revision: D67806838

fbshipit-source-id: 31f20455c816fdb6b1a86f8f9d0f6f7d0a452754
2025-01-06 18:42:37 -08:00

442 lines
13 KiB
TypeScript

/**
* 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.
*/
export type PlatformType =
| 'iOS'
| 'android';
export interface SchemaType {
readonly modules: {
[hasteModuleName: string]: ComponentSchema | NativeModuleSchema;
};
}
/**
* Component Type Annotations
*/
export interface DoubleTypeAnnotation {
readonly type: 'DoubleTypeAnnotation';
}
export interface FloatTypeAnnotation {
readonly type: 'FloatTypeAnnotation';
}
export interface BooleanTypeAnnotation {
readonly type: 'BooleanTypeAnnotation';
}
export interface Int32TypeAnnotation {
readonly type: 'Int32TypeAnnotation';
}
export interface StringTypeAnnotation {
readonly type: 'StringTypeAnnotation';
}
export interface VoidTypeAnnotation {
readonly type: 'VoidTypeAnnotation';
}
export interface ObjectTypeAnnotation<T> {
readonly type: 'ObjectTypeAnnotation';
readonly properties: readonly NamedShape<T>[];
// metadata for objects that generated from interfaces
readonly baseTypes?: readonly string[] | undefined;
}
export interface MixedTypeAnnotation {
readonly type: 'MixedTypeAnnotation';
}
export interface EventEmitterTypeAnnotation {
readonly type: 'EventEmitterTypeAnnotation';
readonly typeAnnotation: NativeModuleEventEmitterTypeAnnotation;
}
export interface FunctionTypeAnnotation<P, R> {
readonly type: 'FunctionTypeAnnotation';
readonly params: readonly NamedShape<P>[];
readonly returnTypeAnnotation: R;
}
export interface NamedShape<T> {
readonly name: string;
readonly optional: boolean;
readonly typeAnnotation: T;
}
export interface ComponentSchema {
readonly type: 'Component';
readonly components: {
[componentName: string]: ComponentShape;
};
}
export interface ComponentShape extends OptionsShape {
readonly extendsProps: readonly ExtendsPropsShape[];
readonly events: readonly EventTypeShape[];
readonly props: readonly NamedShape<PropTypeAnnotation>[];
readonly commands: readonly NamedShape<CommandTypeAnnotation>[];
readonly deprecatedViewConfigName?: string | undefined;
}
export interface OptionsShape {
readonly interfaceOnly?: boolean | undefined;
// Use for components with no current paper rename in progress
// Does not check for new name
readonly paperComponentName?: string | undefined;
// Use for components that are not used on other platforms.
readonly excludedPlatforms?: readonly PlatformType[] | undefined;
// Use for components currently being renamed in paper
// Will use new name if it is available and fallback to this name
readonly paperComponentNameDeprecated?: string | undefined;
}
export interface ExtendsPropsShape {
readonly type: 'ReactNativeBuiltInType';
readonly knownTypeName: 'ReactNativeCoreViewProps';
}
export interface EventTypeShape {
readonly name: string;
readonly bubblingType:
| 'direct'
| 'bubble';
readonly optional: boolean;
readonly paperTopLevelNameDeprecated?: string | undefined;
readonly typeAnnotation: {
readonly type: 'EventTypeAnnotation';
readonly argument?: ObjectTypeAnnotation<EventTypeAnnotation> | undefined;
};
}
export type EventTypeAnnotation =
| BooleanTypeAnnotation
| StringTypeAnnotation
| DoubleTypeAnnotation
| FloatTypeAnnotation
| Int32TypeAnnotation
| MixedTypeAnnotation
| StringLiteralUnionTypeAnnotation
| ObjectTypeAnnotation<EventTypeAnnotation>
| ArrayTypeAnnotation<EventTypeAnnotation>
export type ComponentArrayTypeAnnotation = ArrayTypeAnnotation<
| BooleanTypeAnnotation
| StringTypeAnnotation
| DoubleTypeAnnotation
| FloatTypeAnnotation
| Int32TypeAnnotation
| {
readonly type: 'StringEnumTypeAnnotation';
readonly default: string;
readonly options: readonly string[];
}
| ObjectTypeAnnotation<PropTypeAnnotation>
| ReservedPropTypeAnnotation
| ArrayTypeAnnotation<ObjectTypeAnnotation<PropTypeAnnotation>>
>;
export type ComponentCommandArrayTypeAnnotation = ArrayTypeAnnotation<
| BooleanTypeAnnotation
| StringTypeAnnotation
| DoubleTypeAnnotation
| FloatTypeAnnotation
| Int32TypeAnnotation
// Mixed is not great. This generally means its a type alias to another type
// like an object or union. Ideally we'd encode that type in the schema so the compat-check can
// validate those deeper objects for breaking changes and the generators can do something smarter.
// As of now, the generators just create ReadableMap or (const NSArray *) which are untyped
| MixedTypeAnnotation
>;
export interface ArrayTypeAnnotation<T> {
readonly type: 'ArrayTypeAnnotation';
readonly elementType: T;
}
export type PropTypeAnnotation =
| {
readonly type: 'BooleanTypeAnnotation';
readonly default: boolean | null;
}
| {
readonly type: 'StringTypeAnnotation';
readonly default: string | null;
}
| {
readonly type: 'DoubleTypeAnnotation';
readonly default: number;
}
| {
readonly type: 'FloatTypeAnnotation';
readonly default: number | null;
}
| {
readonly type: 'Int32TypeAnnotation';
readonly default: number;
}
| {
readonly type: 'StringEnumTypeAnnotation';
readonly default: string;
readonly options: readonly string[];
}
| {
readonly type: 'Int32EnumTypeAnnotation';
readonly default: number;
readonly options: readonly number[];
}
| ReservedPropTypeAnnotation
| ObjectTypeAnnotation<PropTypeAnnotation>
| ComponentArrayTypeAnnotation
| MixedTypeAnnotation;
export interface ReservedPropTypeAnnotation {
readonly type: 'ReservedPropTypeAnnotation';
readonly name:
| 'ColorPrimitive'
| 'ImageSourcePrimitive'
| 'PointPrimitive'
| 'EdgeInsetsPrimitive'
| 'ImageRequestPrimitive'
| 'DimensionPrimitive';
}
export type CommandTypeAnnotation = FunctionTypeAnnotation<
CommandParamTypeAnnotation,
VoidTypeAnnotation
>;
export type CommandParamTypeAnnotation =
| ReservedTypeAnnotation
| BooleanTypeAnnotation
| Int32TypeAnnotation
| DoubleTypeAnnotation
| FloatTypeAnnotation
| StringTypeAnnotation
| ComponentCommandArrayTypeAnnotation;
export interface ReservedTypeAnnotation {
readonly type: 'ReservedTypeAnnotation';
readonly name: 'RootTag'; // Union with more custom types.
}
/**
* NativeModule Types
*/
export type Nullable<T extends NativeModuleTypeAnnotation> =
| NullableTypeAnnotation<T>
| T;
export interface NullableTypeAnnotation<T extends NativeModuleTypeAnnotation> {
readonly type: 'NullableTypeAnnotation';
readonly typeAnnotation: T;
}
export interface NativeModuleSchema {
readonly type: 'NativeModule';
readonly aliasMap: NativeModuleAliasMap;
readonly enumMap: NativeModuleEnumMap;
readonly spec: NativeModuleSpec;
readonly moduleName: string;
// Use for modules that are not used on other platforms.
// TODO: It's clearer to define `restrictedToPlatforms` instead, but
// `excludedPlatforms` is used here to be consistent with ComponentSchema.
readonly excludedPlatforms?: readonly PlatformType[] | undefined;
}
export interface NativeModuleSpec {
readonly eventEmitters: readonly NativeModuleEventEmitterShape[];
readonly methods: readonly NativeModulePropertyShape[];
}
export type NativeModulePropertyShape = NamedShape<
Nullable<NativeModuleFunctionTypeAnnotation>
>;
export type NativeModuleEventEmitterShape = NamedShape<EventEmitterTypeAnnotation>;
export interface NativeModuleEnumMap {
readonly [enumName: string]: NativeModuleEnumDeclarationWithMembers;
}
export interface NativeModuleAliasMap {
readonly [aliasName: string]: NativeModuleObjectTypeAnnotation;
}
export type NativeModuleFunctionTypeAnnotation = FunctionTypeAnnotation<
Nullable<NativeModuleParamTypeAnnotation>,
Nullable<NativeModuleReturnTypeAnnotation>
>;
export type NativeModuleObjectTypeAnnotation = ObjectTypeAnnotation<
Nullable<NativeModuleBaseTypeAnnotation>
>;
/**
* TODO(T72031674): Migrate all our NativeModule specs to not use
* invalid Array ElementTypes. Then, make the elementType required.
*/
interface NativeModuleArrayTypeAnnotation<T> extends ArrayTypeAnnotation<T | UnsafeAnyTypeAnnotation> { }
export interface UnsafeAnyTypeAnnotation {
readonly type: 'AnyTypeAnnotation',
}
export interface NativeModuleNumberLiteralTypeAnnotation {
readonly type: 'NumberLiteralTypeAnnotation';
readonly value: number;
}
export interface NativeModuleStringTypeAnnotation {
readonly type: 'StringTypeAnnotation';
}
export interface NativeModuleStringLiteralTypeAnnotation {
readonly type: 'StringLiteralTypeAnnotation';
readonly value: string;
}
export interface StringLiteralUnionTypeAnnotation {
readonly type: 'StringLiteralUnionTypeAnnotation';
readonly types: NativeModuleStringLiteralTypeAnnotation[];
}
export interface NativeModuleNumberTypeAnnotation {
readonly type: 'NumberTypeAnnotation';
}
export interface NativeModuleInt32TypeAnnotation {
readonly type: 'Int32TypeAnnotation';
}
export interface NativeModuleDoubleTypeAnnotation {
readonly type: 'DoubleTypeAnnotation';
}
export interface NativeModuleFloatTypeAnnotation {
readonly type: 'FloatTypeAnnotation';
}
export interface NativeModuleBooleanTypeAnnotation {
readonly type: 'BooleanTypeAnnotation';
}
export type NativeModuleEnumMember = {
readonly name: string;
readonly value: NativeModuleStringLiteralTypeAnnotation | NativeModuleNumberLiteralTypeAnnotation,
};
export type NativeModuleEnumMemberType =
| 'NumberTypeAnnotation'
| 'StringTypeAnnotation';
export interface NativeModuleEnumDeclaration {
readonly name: string;
readonly type: 'EnumDeclaration';
readonly memberType: NativeModuleEnumMemberType;
}
export interface NativeModuleEnumDeclarationWithMembers {
name: string;
type: 'EnumDeclarationWithMembers';
memberType: NativeModuleEnumMemberType;
members: readonly NativeModuleEnumMember[];
}
export interface NativeModuleGenericObjectTypeAnnotation {
readonly type: 'GenericObjectTypeAnnotation';
// a dictionary type is codegen as "Object"
// but we know all its members are in the same type
// when it happens, the following field is non-null
readonly dictionaryValueType?: Nullable<NativeModuleTypeAnnotation> | undefined;
}
export interface NativeModuleTypeAliasTypeAnnotation {
readonly type: 'TypeAliasTypeAnnotation';
readonly name: string;
}
export interface NativeModulePromiseTypeAnnotation {
readonly type: 'PromiseTypeAnnotation';
readonly elementType: Nullable<NativeModuleBaseTypeAnnotation> | VoidTypeAnnotation;
}
export type UnionTypeAnnotationMemberType =
| 'NumberTypeAnnotation'
| 'ObjectTypeAnnotation'
| 'StringTypeAnnotation';
export interface NativeModuleUnionTypeAnnotation {
readonly type: 'UnionTypeAnnotation';
readonly memberType: UnionTypeAnnotationMemberType;
}
export interface NativeModuleMixedTypeAnnotation {
readonly type: 'MixedTypeAnnotation';
}
export type NativeModuleEventEmitterBaseTypeAnnotation =
| NativeModuleBooleanTypeAnnotation
| NativeModuleDoubleTypeAnnotation
| NativeModuleFloatTypeAnnotation
| NativeModuleInt32TypeAnnotation
| NativeModuleNumberTypeAnnotation
| NativeModuleNumberLiteralTypeAnnotation
| NativeModuleStringTypeAnnotation
| NativeModuleStringLiteralTypeAnnotation
| StringLiteralUnionTypeAnnotation
| NativeModuleTypeAliasTypeAnnotation
| NativeModuleGenericObjectTypeAnnotation
| VoidTypeAnnotation;
export type NativeModuleEventEmitterTypeAnnotation =
| NativeModuleEventEmitterBaseTypeAnnotation
| ArrayTypeAnnotation<NativeModuleEventEmitterBaseTypeAnnotation>;
export type NativeModuleBaseTypeAnnotation =
NativeModuleStringTypeAnnotation
| NativeModuleStringLiteralTypeAnnotation
| StringLiteralUnionTypeAnnotation
| NativeModuleNumberTypeAnnotation
| NativeModuleNumberLiteralTypeAnnotation
| NativeModuleInt32TypeAnnotation
| NativeModuleDoubleTypeAnnotation
| NativeModuleFloatTypeAnnotation
| NativeModuleBooleanTypeAnnotation
| NativeModuleEnumDeclaration
| NativeModuleGenericObjectTypeAnnotation
| ReservedTypeAnnotation
| NativeModuleTypeAliasTypeAnnotation
| NativeModuleObjectTypeAnnotation
| NativeModuleUnionTypeAnnotation
| NativeModuleMixedTypeAnnotation
| NativeModuleArrayTypeAnnotation<NativeModuleBaseTypeAnnotation>;
export type NativeModuleParamTypeAnnotation =
| NativeModuleBaseTypeAnnotation
| NativeModuleParamOnlyTypeAnnotation;
export type NativeModuleReturnTypeAnnotation =
| NativeModuleBaseTypeAnnotation
| NativeModuleReturnOnlyTypeAnnotation;
export type NativeModuleTypeAnnotation =
| NativeModuleBaseTypeAnnotation
| NativeModuleParamOnlyTypeAnnotation
| NativeModuleReturnOnlyTypeAnnotation
| NativeModuleEventEmitterTypeAnnotation;
type NativeModuleParamOnlyTypeAnnotation = NativeModuleFunctionTypeAnnotation;
type NativeModuleReturnOnlyTypeAnnotation =
| NativeModuleFunctionTypeAnnotation
| NativeModulePromiseTypeAnnotation
| VoidTypeAnnotation;